This repository has been archived by the owner on Jul 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vk.go
188 lines (154 loc) · 4.37 KB
/
vk.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/tidwall/gjson"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/url"
"strconv"
"time"
)
type Vk struct {
accessToken string
version string
}
type vkLongPollServer struct {
Key string
Server string
Ts string
}
func (v *Vk) Request(method string, params url.Values) (response gjson.Result, err error) {
params.Add("access_token", v.accessToken)
params.Add("v", v.version)
resp, err := http.PostForm(fmt.Sprintf("https://api.vk.com/method/%s", method), params)
if err != nil {
return gjson.Result{}, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return gjson.Result{}, fmt.Errorf("bad http code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return gjson.Result{}, err
}
result := gjson.GetBytes(body, "response")
if !result.Exists() {
errorMsg := gjson.GetBytes(body, "error.error_msg")
if !errorMsg.Exists() {
return gjson.Result{}, errors.New("unknown json struct error")
}
return gjson.Result{}, errors.New(errorMsg.Str)
}
return result, nil
}
// https://vk.com/dev/messages.send
func (v *Vk) SendMessage(peerId int64, text string) {
_, err := v.Request("messages.send", url.Values{
"peer_id": {strconv.FormatInt(peerId, 10)},
"random_id": {strconv.FormatInt(rand.Int63(), 10)},
"message": {text},
})
if err != nil {
log.Println("SendMessage error:", err)
}
}
// https://vk.com/dev/messages.send
// https://vk.com/dev/bots_docs_3
func (v *Vk) SendKeyboard(peerId int64, text string, keyboard *VkKeyboard) {
kb, _ := json.Marshal(keyboard)
_, err := v.Request("messages.send", url.Values{
"peer_id": {strconv.FormatInt(peerId, 10)},
"random_id": {strconv.FormatInt(rand.Int63(), 10)},
"message": {text},
"keyboard": {string(kb)},
"dont_parse_links": {"1"},
"disable_mentions": {"1"},
})
if err != nil {
log.Println("SendKeyboard error:", err)
}
}
func (v *Vk) GroupPoll(groupId string, event func(vk *Vk, message gjson.Result)) {
go func() {
lp := vkLongPollServer{}
for {
// Update Long Poll data
if len(lp.Key) == 0 {
response, err := v.Request("groups.getLongPollServer", url.Values{"group_id": {groupId}})
if err != nil {
log.Println("getLongPollServer error:", err.Error())
time.Sleep(5 * time.Second)
continue
}
if len(lp.Ts) == 0 {
lp.Ts = response.Get("ts").Str
}
lp.Server = response.Get("server").Str
lp.Key = response.Get("key").Str
log.Println("Long Poll server updated")
}
// Long Poll request
resp1, err := http.Get(fmt.Sprintf("%s?act=a_check&key=%s&ts=%s&wait=25", lp.Server, lp.Key, lp.Ts))
if err != nil {
log.Println("LP poll error:", err.Error())
time.Sleep(5 * time.Second)
continue
}
body, err := ioutil.ReadAll(resp1.Body)
resp1.Body.Close()
if err != nil {
log.Println("LP read error:", err.Error())
continue
}
updates := gjson.GetBytes(body, "updates")
// Long Poll error handling
if !updates.Exists() {
failedCode := gjson.GetBytes(body, "failed")
if !failedCode.Exists() {
log.Printf("LP json struct error: %#v\n", body)
continue
}
switch failedCode.Int() {
case 1: // history expired or lost
lp.Ts = gjson.GetBytes(body, "ts").Str
case 2: // key expired
lp.Key = ""
case 3: // data lost
lp.Key = ""
lp.Ts = ""
default:
log.Fatalf("LP unknown failed code: %s\n", failedCode.Str)
}
continue
}
updates.ForEach(func(_, value gjson.Result) bool {
if value.Get("type").Str != "message_new" {
return true
}
go event(v, value.Get("object"))
return true
})
lp.Ts = gjson.GetBytes(body, "ts").Str
}
}()
}
type LongPollMessage struct {
Date int64 `json:"date"`
FromId int64 `json:"from_id"`
// Id int `json:"id"`
// Out int `json:"out"`
// PeerId int64 `json:"peer_id"`
Text string `json:"text"`
// ConversationId int `json:"conversation_message_id"`
// FwdMessages []interface{} `json:"fwd_messages"`
// Important bool `json:"important"`
// RandomId int64 `json:"random_id"`
// Attachments []interface{} `json:"attachments"`
Payload string `json:"payload"`
// IsHidden bool `json:"is_hidden"`
}