-
Notifications
You must be signed in to change notification settings - Fork 0
/
messenger.go
94 lines (75 loc) · 1.93 KB
/
messenger.go
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
package sender
import (
"math/rand"
"net/url"
"strconv"
"strings"
"time"
)
type MessageResponse struct {
Response int `json:"response,omitempty"`
}
type Document struct {
Owner int
ID int
}
type Message struct {
User int
ID int
}
func sendMessage(document Document, token string, auth Auth) Message {
uri := getMessagesSendURI(document, token, auth)
resp, err := client.Get(uri)
checkErr(err)
defer resp.Body.Close()
messageResponse := &MessageResponse{}
getStructFromJSON(resp.Body, messageResponse)
message := Message{
User: auth.Recipient,
ID: messageResponse.Response,
}
return message
}
func getMessagesSendURI(document Document, token string, auth Auth) string {
rawQuery := getMessageSendRawQuery(document, token, auth)
uri := url.URL{
Scheme: "https",
Host: "api.vk.com",
Path: "method/messages.send",
RawQuery: rawQuery,
}
return uri.String()
}
func getMessageSendRawQuery(document Document, token string, auth Auth) string {
randomStr := getRandomString()
query := url.Values{}
query.Set("access_token", token)
query.Add("user_id", strconv.Itoa(auth.Recipient))
query.Add("attachment", document.String())
query.Add("v", version)
query.Add("random_id", randomStr)
return query.Encode()
}
func getRandomString() string {
randomSource := rand.NewSource(time.Now().UnixNano())
r := rand.New(randomSource)
// get 5-digit number
random := r.Intn(90000) + 9999
return strconv.Itoa(random)
}
func (doc Document) String() string {
builder := strings.Builder{}
builder.WriteString("doc")
builder.WriteString(strconv.Itoa(doc.Owner))
builder.WriteString("_")
builder.WriteString(strconv.Itoa(doc.ID))
return builder.String()
}
func (mes Message) String() string {
builder := strings.Builder{}
builder.WriteString("https://vk.com/im?sel=")
builder.WriteString(strconv.Itoa(mes.User))
builder.WriteString("&msgid=")
builder.WriteString(strconv.Itoa(mes.ID))
return builder.String()
}