/
bot.go
494 lines (457 loc) · 13.7 KB
/
bot.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package handler
import (
"crypto/md5"
"encoding/json"
"fmt"
"net/http"
"os"
"sync"
"time"
"github.com/ProtobufBot/Go-Mirai-Client/pkg/bot"
"github.com/ProtobufBot/Go-Mirai-Client/pkg/config"
"github.com/ProtobufBot/Go-Mirai-Client/pkg/device"
"github.com/ProtobufBot/Go-Mirai-Client/pkg/gmc/plugins"
"github.com/ProtobufBot/Go-Mirai-Client/pkg/plugin"
"github.com/ProtobufBot/Go-Mirai-Client/pkg/util"
"github.com/ProtobufBot/Go-Mirai-Client/proto_gen/dto"
_ "github.com/BurntSushi/toml"
"github.com/Mrs4s/MiraiGo/client"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/golang/protobuf/proto"
log "github.com/sirupsen/logrus"
)
var queryQRCodeMutex = &sync.RWMutex{}
var qrCodeBot *client.QQClient
func TokenLogin() {
if bot.PathExists("deviceInfo.toml") {
log.Info("尝试 Token 登录")
g, _ := bot.GmcTokenLogin()
cli := client.NewClientEmpty()
deviceInfo := device.GetDevice(g.DeviceSeed, g.ClientProtocol)
cli.UseDevice(deviceInfo)
if bot.PathExists("session.token") {
token, err := os.ReadFile("session.token")
if err == nil {
if err = cli.TokenLogin(token); err != nil {
_ = os.Remove("session.token")
log.Warnf("恢复会话失败: %v , 尝试使用正常流程登录.", err)
time.Sleep(time.Second)
cli.Disconnect()
cli.Release()
} else {
bot.Clients.LoadOrStore(cli.Uin, cli)
AfterLogin(cli)
}
}
} else {
log.Warn("Token 不存在,请尝试使用正常流程登录")
}
} else {
log.Warn("deviceInfo.toml 不存在,可能是 deviceInfo.toml 缺失或是首次登录")
}
}
func init() {
//log.Infof("加载日志插件 Log")
plugin.AddPrivateMessagePlugin(plugins.LogPrivateMessage)
plugin.AddGroupMessagePlugin(plugins.LogGroupMessage)
plugin.AddChannelMessagePlugin(plugins.LogChannelMessage)
//log.Infof("加载测试插件 Hello")
plugin.AddPrivateMessagePlugin(plugins.HelloPrivateMessage)
//log.Infof("加载上报插件 Report")
plugin.AddPrivateMessagePlugin(plugins.ReportPrivateMessage)
plugin.AddGroupMessagePlugin(plugins.ReportGroupMessage)
plugin.AddGroupNotifyEventPlugin(plugins.ReportGroupNotify)
plugin.AddChannelMessagePlugin(plugins.ReportChannelMessage)
plugin.AddTempMessagePlugin(plugins.ReportTempMessage)
plugin.AddMemberPermissionChangedPlugin(plugins.ReportMemberPermissionChanged)
plugin.AddMemberJoinGroupPlugin(plugins.ReportMemberJoin)
plugin.AddMemberLeaveGroupPlugin(plugins.ReportMemberLeave)
plugin.AddJoinGroupPlugin(plugins.ReportJoinGroup)
plugin.AddLeaveGroupPlugin(plugins.ReportLeaveGroup)
plugin.AddNewFriendRequestPlugin(plugins.ReportNewFriendRequest)
plugin.AddUserJoinGroupRequestPlugin(plugins.ReportUserJoinGroupRequest)
plugin.AddGroupInvitedRequestPlugin(plugins.ReportGroupInvitedRequest)
plugin.AddGroupMessageRecalledPlugin(plugins.ReportGroupMessageRecalled)
plugin.AddFriendMessageRecalledPlugin(plugins.ReportFriendMessageRecalled)
plugin.AddNewFriendAddedPlugin(plugins.ReportNewFriendAdded)
plugin.AddOfflineFilePlugin(plugins.ReportOfflineFile)
plugin.AddGroupMutePlugin(plugins.ReportGroupMute)
}
func CreateBot(c *gin.Context) {
g, _ := bot.GmcTokenLogin()
req := &dto.CreateBotReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, "bad request, not protobuf")
return
}
if req.BotId == 0 {
c.String(http.StatusBadRequest, "botId is 0")
return
}
_, ok := bot.Clients.Load(req.BotId)
if ok {
c.String(http.StatusInternalServerError, "botId already exists")
return
}
if req.ClientProtocol == 0 {
bot.GTL = &bot.GMCLogin{
DeviceSeed: req.DeviceSeed,
ClientProtocol: 6,
SignServer: g.SignServer,
SignServerKey: g.SignServerKey,
}
if req.SignServer != "" {
bot.GTL.SignServer = req.SignServer
}
if req.SignServerAuth != "" {
bot.GTL.SignServerKey = req.SignServerAuth
}
_ = os.WriteFile("deviceInfo.toml", []byte(fmt.Sprintf("DeviceSeed = %d \nClientProtocol= %d \nSignServer= \"%s\" \nSignServerkey= \"%s\"", bot.GTL.DeviceSeed, 6, bot.GTL.SignServer, bot.GTL.SignServerKey)), 0o644)
go func() {
CreateBotImpl(req.BotId, req.Password, req.DeviceSeed, 6, req.SignServerAuth)
}()
} else {
bot.GTL = &bot.GMCLogin{
DeviceSeed: req.DeviceSeed,
ClientProtocol: req.ClientProtocol,
SignServer: g.SignServer,
SignServerKey: g.SignServerKey,
}
if req.SignServer != "" {
bot.GTL.SignServer = req.SignServer
}
if req.SignServerAuth != "" {
bot.GTL.SignServerKey = req.SignServerAuth
}
_ = os.WriteFile("deviceInfo.toml", []byte(fmt.Sprintf("DeviceSeed = %d \nClientProtocol= %d \nSignServer= \"%s\" \nSignServerkey= \"%s\"", bot.GTL.DeviceSeed, bot.GTL.ClientProtocol, bot.GTL.SignServer, bot.GTL.SignServerKey)), 0o644)
go func() {
CreateBotImpl(req.BotId, req.Password, req.DeviceSeed, req.ClientProtocol, req.SignServerAuth)
}()
}
resp := &dto.CreateBotResp{}
Return(c, resp)
}
func DeleteBot(c *gin.Context) {
req := &dto.DeleteBotReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, "bad request, not protobuf")
return
}
cli, ok := bot.Clients.Load(req.BotId)
if !ok {
c.String(http.StatusBadRequest, "bot not exists")
return
}
bot.ReleaseClient(cli)
resp := &dto.DeleteBotResp{}
Return(c, resp)
}
func ListBot(c *gin.Context) {
req := &dto.ListBotReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, "bad request, not protobuf")
return
}
var resp = &dto.ListBotResp{
BotList: []*dto.Bot{},
}
bot.Clients.Range(func(_ int64, cli *client.QQClient) bool {
resp.BotList = append(resp.BotList, &dto.Bot{
BotId: cli.Uin,
IsOnline: cli.Online.Load(),
Captcha: func() *dto.Bot_Captcha {
if waitingCaptcha, ok := bot.WaitingCaptchas.Load(cli.Uin); ok {
return waitingCaptcha.Captcha
}
return nil
}(),
})
return true
})
Return(c, resp)
}
func SolveCaptcha(c *gin.Context) {
req := &dto.SolveCaptchaReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, "bad request, not protobuf")
return
}
waitingCaptcha, ok := bot.WaitingCaptchas.Load(req.BotId)
if !ok {
c.String(http.StatusInternalServerError, "captcha not found")
return
}
err = waitingCaptcha.Prom.Resolve(req.Result)
if err != nil {
c.String(http.StatusInternalServerError, "solve captcha error")
return
}
resp := &dto.SolveCaptchaResp{}
Return(c, resp)
}
func FetchQrCode(c *gin.Context) {
req := &dto.FetchQRCodeReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, "bad request, not protobuf")
return
}
if qrCodeBot != nil {
qrCodeBot.Release()
}
qrCodeBot = client.NewClientEmpty()
//deviceInfo := device.GetDevice(req.DeviceSeed, req.ClientProtocol)
deviceInfo := device.GetDevice(req.DeviceSeed, 2)
_ = os.WriteFile("deviceInfo.toml", []byte(fmt.Sprintf("DeviceSeed = %d\nClientProtocol = %d", req.DeviceSeed, 2)), 0o644)
qrCodeBot.UseDevice(deviceInfo)
log.Infof("初始化日志")
bot.InitLog(qrCodeBot)
fetchQRCodeResp, err := qrCodeBot.FetchQRCode()
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("failed to fetch qrcode, %+v", err))
return
}
resp := &dto.QRCodeLoginResp{
State: dto.QRCodeLoginResp_QRCodeLoginState(fetchQRCodeResp.State),
ImageData: fetchQRCodeResp.ImageData,
Sig: fetchQRCodeResp.Sig,
}
Return(c, resp)
}
func QueryQRCodeStatus(c *gin.Context) {
queryQRCodeMutex.Lock()
defer queryQRCodeMutex.Unlock()
req := &dto.QueryQRCodeStatusReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("failed to bind, %+v", err))
return
}
if qrCodeBot == nil {
c.String(http.StatusBadRequest, "please fetch qrcode first")
return
}
if qrCodeBot.Online.Load() {
c.String(http.StatusBadRequest, "already online")
return
}
queryQRCodeStatusResp, err := qrCodeBot.QueryQRCodeStatus(req.Sig)
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("failed to query qrcode status, %+v", err))
return
}
if queryQRCodeStatusResp.State == client.QRCodeConfirmed {
go func() {
queryQRCodeMutex.Lock()
defer queryQRCodeMutex.Unlock()
loginResp, err := qrCodeBot.QRCodeLogin(queryQRCodeStatusResp.LoginInfo)
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("failed to qrcode login, %+v", err))
return
}
if !loginResp.Success {
c.String(http.StatusInternalServerError, fmt.Sprintf("failed to qrcode login, %+v", err))
return
}
log.Infof("登录成功")
originCli, ok := bot.Clients.Load(qrCodeBot.Uin)
// 重复登录,旧的断开
if ok {
originCli.Release()
}
bot.Clients.Store(qrCodeBot.Uin, qrCodeBot)
go AfterLogin(qrCodeBot)
accountToken := qrCodeBot.GenToken()
_ = os.WriteFile("session.token", accountToken, 0o644)
qrCodeBot = nil
}()
}
resp := &dto.QRCodeLoginResp{
State: dto.QRCodeLoginResp_QRCodeLoginState(queryQRCodeStatusResp.State),
ImageData: queryQRCodeStatusResp.ImageData,
Sig: queryQRCodeStatusResp.Sig,
}
Return(c, resp)
}
func ListPlugin(c *gin.Context) {
req := &dto.ListPluginReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, "bad request")
return
}
var resp = &dto.ListPluginResp{
Plugins: []*dto.Plugin{},
}
config.Plugins.Range(func(key string, p *config.Plugin) bool {
resp.Plugins = append(resp.Plugins, &dto.Plugin{
Name: p.Name,
Disabled: p.Disabled,
Json: p.Json,
Urls: p.Urls,
EventFilter: p.EventFilter,
ApiFilter: p.ApiFilter,
RegexFilter: p.RegexFilter,
RegexReplace: p.RegexReplace,
ExtraHeader: func() []*dto.Plugin_Header {
headers := make([]*dto.Plugin_Header, 0)
for k, v := range p.ExtraHeader {
headers = append(headers, &dto.Plugin_Header{
Key: k,
Value: v,
})
}
return headers
}(),
})
return true
})
Return(c, resp)
}
func SavePlugin(c *gin.Context) {
req := &dto.SavePluginReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, "bad request")
return
}
if req.Plugin == nil {
c.String(http.StatusBadRequest, "plugin is nil")
return
}
p := req.Plugin
if p.ApiFilter == nil {
p.ApiFilter = []int32{}
}
if p.EventFilter == nil {
p.EventFilter = []int32{}
}
if p.Urls == nil {
p.Urls = []string{}
}
config.Plugins.Store(p.Name, &config.Plugin{
Name: p.Name,
Disabled: p.Disabled,
Json: p.Json,
Urls: p.Urls,
EventFilter: p.EventFilter,
ApiFilter: p.ApiFilter,
RegexFilter: p.RegexFilter,
RegexReplace: p.RegexReplace,
ExtraHeader: func() map[string][]string {
headers := map[string][]string{}
for _, h := range p.ExtraHeader {
headers[h.Key] = h.Value
}
return headers
}(),
})
config.WritePlugins()
resp := &dto.SavePluginResp{}
Return(c, resp)
}
func DeletePlugin(c *gin.Context) {
req := &dto.DeletePluginReq{}
err := Bind(c, req)
if err != nil {
c.String(http.StatusBadRequest, "bad request")
return
}
config.Plugins.Delete(req.Name)
config.WritePlugins()
resp := &dto.DeletePluginResp{}
Return(c, resp)
}
func Return(c *gin.Context, resp proto.Message) {
var (
data []byte
err error
)
switch c.ContentType() {
case binding.MIMEPROTOBUF:
data, err = proto.Marshal(resp)
case binding.MIMEJSON:
data, err = json.Marshal(resp)
}
if err != nil {
c.String(http.StatusInternalServerError, "marshal resp error")
return
}
c.Data(http.StatusOK, c.ContentType(), data)
}
func CreateBotImpl(uin int64, password string, deviceRandSeed int64, clientProtocol int32, signServerKey string) {
CreateBotImplMd5(uin, md5.Sum([]byte(password)), deviceRandSeed, clientProtocol, signServerKey)
}
func CreateBotImplMd5(uin int64, passwordMd5 [16]byte, deviceRandSeed int64, clientProtocol int32, signServerKey string) {
var deviceInfo *client.DeviceInfo
log.Infof("开始初始化设备信息")
if deviceRandSeed != 0 {
deviceInfo = device.GetDevice(deviceRandSeed, clientProtocol)
} else {
deviceInfo = device.GetDevice(uin, clientProtocol)
}
log.Infof("设备信息 %+v", string(deviceInfo.ToJson()))
log.Infof("创建机器人 %+v", uin)
cli := client.NewClientMd5(uin, passwordMd5)
cli.UseDevice(deviceInfo)
bot.Clients.Store(uin, cli)
log.Infof("初始化日志")
bot.InitLog(cli)
log.Infof("登录中...")
ok, err := bot.Login(cli)
if err != nil {
// TODO 登录失败,是否需要删除?
log.Errorf("failed to login, err: %+v", err)
return
}
if ok {
log.Infof("登录成功")
for _, data := range bot.RSR.Data.RequestCallback {
go bot.SubmitRequestCallback(uint64(uin), data.Cmd, data.CallBackId, []byte(data.Body))
}
time.Sleep(time.Second * 3)
if !bot.SubmitRequestCallbackStop {
log.Infof("登录成功")
AfterLogin(cli)
accountToken := cli.GenToken()
_ = os.WriteFile("session.token", accountToken, 0o644)
} else {
log.Warn("联网更新Token失败,请退出重登")
}
} else {
log.Infof("登录失败")
}
}
func AfterLogin(cli *client.QQClient) {
bot.RequestToken(uint64(cli.Uin))
if bot.IsRequestTokenAgain {
bot.RequestToken(uint64(cli.Uin))
}
go bot.TTIR(uint64(cli.Uin))
for {
time.Sleep(5 * time.Second)
if cli.Online.Load() {
break
}
log.Warnf("机器人不在线,可能在等待输入验证码,或出错了。如果出错请重启。")
}
plugin.Serve(cli)
log.Infof("插件加载完成")
log.Infof("刷新好友列表")
if err := cli.ReloadFriendList(); err != nil {
util.FatalError(fmt.Errorf("failed to load friend list, err: %+v", err))
}
log.Infof("共加载 %v 个好友.", len(cli.FriendList))
log.Infof("刷新群列表")
if err := cli.ReloadGroupList(); err != nil {
util.FatalError(fmt.Errorf("failed to load group list, err: %+v", err))
}
log.Infof("共加载 %v 个群.", len(cli.GroupList))
bot.ConnectUniversal(cli)
bot.SetRelogin(cli, 30, 20)
}