-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc.go
More file actions
107 lines (94 loc) · 2.25 KB
/
func.go
File metadata and controls
107 lines (94 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"github.com/yanzay/tbot/v2"
)
type requestStruct struct {
idUser int
request string
}
func sendUserInfoToBD(m *tbot.Message) {
name := m.From.Username
id := m.From.ID
connStr := "user=postgres dbname=tg_bot password=1111 host=localhost sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
insert := fmt.Sprintf("INSERT INTO users (id,username) SELECT %d, '%s' WHERE NOT EXISTS (SELECT id FROM users WHERE id = %d)", id, name, id)
fmt.Println(insert)
_, err = db.Exec(insert)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Printf("\nSuccessfully connected to database!\n")
}
func sendRequestToDB(m *tbot.Message, req string) {
id := m.From.ID
connStr := "user=postgres dbname=tg_bot password=1111 host=localhost sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
panic(err)
}
insert := fmt.Sprintf("INSERT INTO requests (id_user,request) VALUES (%d,'%s')", id, req)
fmt.Println(insert)
_, err = db.Exec(insert)
if err != nil {
panic(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Printf("\nSuccessfully connected to database!\n")
}
func getResultsFromDB(m *tbot.Message) ([]requestStruct, error) {
id := m.From.ID
connStr := "user=postgres dbname=tg_bot password=1111 host=localhost sslmode=disable"
db, err := sql.Open("postgres", connStr)
defer db.Close()
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Printf("\nSuccessfully connected to database!\n")
rows, err := db.Query(fmt.Sprintf("SELECT id_user, request FROM requests WHERE id_user = %d ORDER BY id_request DESC LIMIT 20", id))
if err != nil {
panic(err)
}
defer rows.Close()
var resSlize []requestStruct
for rows.Next() {
r := requestStruct{}
err := rows.Scan(&r.idUser, &r.request)
CheckError(err)
resSlize = append(resSlize, r)
}
return resSlize, nil
}
func getWords(str string) []string {
result := []string{}
word := ""
for _, v := range str {
if v != ' ' {
word += string(v)
} else {
if len(word) != 0 {
result = append(result, word)
word = ""
}
}
}
if len(word) != 0 {
result = append(result, word)
}
return result
}