forked from Mrs4s/go-cqhttp
/
api.go
1529 lines (1449 loc) · 44.2 KB
/
api.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package coolq
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"math"
"os"
"path"
"path/filepath"
"runtime"
"runtime/debug"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/MiraiGo/utils"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/global"
)
// Version go-cqhttp的版本信息,在编译时使用ldflags进行覆盖
var Version = "unknown"
func init() {
if Version != "unknown" {
return
}
info, ok := debug.ReadBuildInfo()
if ok {
Version = info.Main.Version
}
}
// CQGetLoginInfo 获取登录号信息
//
// https://git.io/Jtz1I
func (bot *CQBot) CQGetLoginInfo() MSG {
return OK(MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname})
}
// CQGetQiDianAccountInfo 获取企点账号信息
func (bot *CQBot) CQGetQiDianAccountInfo() MSG {
if bot.Client.QiDian == nil {
return Failed(100, "QIDIAN_PROTOCOL_REQUEST", "请使用企点协议")
}
return OK(MSG{
"master_id": bot.Client.QiDian.MasterUin,
"ext_name": bot.Client.QiDian.ExtName,
"create_time": bot.Client.QiDian.CreateTime,
})
}
// CQGetFriendList 获取好友列表
//
// https://git.io/Jtz1L
func (bot *CQBot) CQGetFriendList() MSG {
fs := make([]MSG, 0, len(bot.Client.FriendList))
for _, f := range bot.Client.FriendList {
fs = append(fs, MSG{
"nickname": f.Nickname,
"remark": f.Remark,
"user_id": f.Uin,
})
}
return OK(fs)
}
// CQGetGroupList 获取群列表
//
// https://git.io/Jtz1t
func (bot *CQBot) CQGetGroupList(noCache bool) MSG {
gs := make([]MSG, 0, len(bot.Client.GroupList))
if noCache {
_ = bot.Client.ReloadGroupList()
}
for _, g := range bot.Client.GroupList {
gs = append(gs, MSG{
"group_id": g.Code,
"group_name": g.Name,
"group_memo": g.Memo,
"group_create_time": g.GroupCreateTime,
"group_level": g.GroupLevel,
"max_member_count": g.MaxMemberCount,
"member_count": g.MemberCount,
})
}
return OK(gs)
}
// CQGetGroupInfo 获取群信息
//
// https://git.io/Jtz1O
func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool) MSG {
group := bot.Client.FindGroup(groupID)
if group == nil || noCache {
group, _ = bot.Client.GetGroupInfo(groupID)
}
if group == nil {
gid := strconv.FormatInt(groupID, 10)
info, err := bot.Client.SearchGroupByKeyword(gid)
if err != nil {
return Failed(100, "GROUP_SEARCH_ERROR", "群聊搜索失败")
}
for _, g := range info {
if g.Code == groupID {
return OK(MSG{
"group_id": g.Code,
"group_name": g.Name,
"group_memo": g.Memo,
"group_create_time": 0,
"group_level": 0,
"max_member_count": 0,
"member_count": 0,
})
}
}
} else {
return OK(MSG{
"group_id": group.Code,
"group_name": group.Name,
"group_memo": group.Memo,
"group_create_time": group.GroupCreateTime,
"group_level": group.GroupLevel,
"max_member_count": group.MaxMemberCount,
"member_count": group.MemberCount,
})
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQGetGroupMemberList 获取群成员列表
//
// https://git.io/Jtz13
func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) MSG {
group := bot.Client.FindGroup(groupID)
if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
if noCache {
t, err := bot.Client.GetGroupMembers(group)
if err != nil {
log.Warnf("刷新群 %v 成员列表失败: %v", groupID, err)
return Failed(100, "GET_MEMBERS_API_ERROR", err.Error())
}
group.Members = t
}
members := make([]MSG, 0, len(group.Members))
for _, m := range group.Members {
members = append(members, convertGroupMemberInfo(groupID, m))
}
return OK(members)
}
// CQGetGroupMemberInfo 获取群成员信息
//
// https://git.io/Jtz1s
func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) MSG {
group := bot.Client.FindGroup(groupID)
if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
var member *client.GroupMemberInfo
if noCache {
var err error
member, err = bot.Client.GetMemberInfo(groupID, userID)
if err != nil {
log.Warnf("刷新群 %v 中成员 %v 失败: %v", groupID, userID, err)
return Failed(100, "GET_MEMBER_INFO_API_ERROR", err.Error())
}
} else {
member = group.FindMember(userID)
}
if member == nil {
return Failed(100, "MEMBER_NOT_FOUND", "群员不存在")
}
return OK(convertGroupMemberInfo(groupID, member))
}
// CQGetGroupFileSystemInfo 扩展API-获取群文件系统信息
//
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F%E4%BF%A1%E6%81%AF
func (bot *CQBot) CQGetGroupFileSystemInfo(groupID int64) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(fs)
}
// CQGetGroupRootFiles 扩展API-获取群根目录文件列表
//
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%A0%B9%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8
func (bot *CQBot) CQGetGroupRootFiles(groupID int64) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
files, folders, err := fs.Root()
if err != nil {
log.Errorf("获取群 %v 根目录文件失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(MSG{
"files": files,
"folders": folders,
})
}
// CQGetGroupFilesByFolderID 扩展API-获取群子目录文件列表
//
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%AD%90%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8
func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
files, folders, err := fs.GetFilesByFolder(folderID)
if err != nil {
log.Errorf("获取群 %v 根目录 %v 子文件失败: %v", groupID, folderID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(MSG{
"files": files,
"folders": folders,
})
}
// CQGetGroupFileURL 扩展API-获取群文件资源链接
//
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E8%B5%84%E6%BA%90%E9%93%BE%E6%8E%A5
func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) MSG {
url := bot.Client.GetGroupFileUrl(groupID, fileID, busID)
if url == "" {
return Failed(100, "FILE_SYSTEM_API_ERROR")
}
return OK(MSG{
"url": url,
})
}
// CQUploadGroupFile 扩展API-上传群文件
//
// https://docs.go-cqhttp.org/api/#%E4%B8%8A%E4%BC%A0%E7%BE%A4%E6%96%87%E4%BB%B6
func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) MSG {
if !global.PathExists(file) {
log.Errorf("上传群文件 %v 失败: 文件不存在", file)
return Failed(100, "FILE_NOT_FOUND", "文件不存在")
}
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
if folder == "" {
folder = "/"
}
if err = fs.UploadFile(file, name, folder); err != nil {
log.Errorf("上传群 %v 文件 %v 失败: %v", groupID, file, err)
return Failed(100, "FILE_SYSTEM_UPLOAD_API_ERROR", err.Error())
}
return OK(nil)
}
// CQGroupFileCreateFolder 拓展API-创建群文件文件夹
//
//
func (bot *CQBot) CQGroupFileCreateFolder(groupID int64, parentID, name string) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
if err = fs.CreateFolder(parentID, name); err != nil {
log.Errorf("创建群 %v 文件夹失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(nil)
}
// CQGroupFileDeleteFolder 拓展API-删除群文件文件夹
//
//
func (bot *CQBot) CQGroupFileDeleteFolder(groupID int64, id string) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
if err = fs.DeleteFolder(id); err != nil {
log.Errorf("删除群 %v 文件夹 %v 时出现文件: %v", groupID, id, err)
return Failed(200, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(nil)
}
// CQGroupFileDeleteFile 拓展API-删除群文件
//
//
func (bot *CQBot) CQGroupFileDeleteFile(groupID int64, parentID, id string, busID int32) MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Errorf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
if res := fs.DeleteFile(parentID, id, busID); res != "" {
log.Errorf("删除群 %v 文件 %v 时出现文件: %v", groupID, id, res)
return Failed(200, "FILE_SYSTEM_API_ERROR", res)
}
return OK(nil)
}
// CQGetWordSlices 隐藏API-获取中文分词
//
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E4%B8%AD%E6%96%87%E5%88%86%E8%AF%8D-%E9%9A%90%E8%97%8F-api
func (bot *CQBot) CQGetWordSlices(content string) MSG {
slices, err := bot.Client.GetWordSegmentation(content)
if err != nil {
return Failed(100, "WORD_SEGMENTATION_API_ERROR", err.Error())
}
for i := 0; i < len(slices); i++ {
slices[i] = strings.ReplaceAll(slices[i], "\u0000", "")
}
return OK(MSG{"slices": slices})
}
// CQSendGroupMessage 发送群消息
//
// https://git.io/Jtz1c
func (bot *CQBot) CQSendGroupMessage(groupID int64, i interface{}, autoEscape bool) MSG {
var str string
group := bot.Client.FindGroup(groupID)
if group == nil {
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
fixAt := func(elem []message.IMessageElement) {
for _, e := range elem {
if at, ok := e.(*message.AtElement); ok && at.Target != 0 && at.Display == "" {
at.Display = "@" + func() string {
mem := group.FindMember(at.Target)
if mem != nil {
return mem.DisplayName()
}
return strconv.FormatInt(at.Target, 10)
}()
}
}
}
if m, ok := i.(gjson.Result); ok {
if m.Type == gjson.JSON {
elem := bot.ConvertObjectMessage(m, true)
fixAt(elem)
mid := bot.SendGroupMessage(groupID, &message.SendingMessage{Elements: elem})
if mid == -1 {
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
}
log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(ToStringMessage(elem, int64(mid))), mid)
return OK(MSG{"message_id": mid})
}
str = func() string {
if m.Str != "" {
return m.Str
}
return m.Raw
}()
} else if s, ok := i.(string); ok {
str = s
}
if str == "" {
log.Warnf("群消息发送失败: 信息为空. MSG: %v", i)
return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
}
var elem []message.IMessageElement
if autoEscape {
elem = append(elem, message.NewText(str))
} else {
elem = bot.ConvertStringMessage(str, true)
}
fixAt(elem)
mid := bot.SendGroupMessage(groupID, &message.SendingMessage{Elements: elem})
if mid == -1 {
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
}
log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(str), mid)
return OK(MSG{"message_id": mid})
}
// CQSendGroupForwardMessage 扩展API-发送合并转发(群)
//
// https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91-%E7%BE%A4
func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) MSG {
if m.Type != gjson.JSON {
return Failed(100)
}
var sendNodes []*message.ForwardNode
ts := time.Now().Add(-time.Minute * 5)
hasCustom := func() bool {
for _, item := range m.Array() {
if item.Get("data.uin").Exists() {
return true
}
}
return false
}()
var convert func(e gjson.Result) []*message.ForwardNode
convert = func(e gjson.Result) (nodes []*message.ForwardNode) {
if e.Get("type").Str != "node" {
return nil
}
ts.Add(time.Second)
if e.Get("data.id").Exists() {
i, _ := strconv.Atoi(e.Get("data.id").String())
m := bot.GetMessage(int32(i))
if m != nil {
sender := m["sender"].(message.Sender)
nodes = append(nodes, &message.ForwardNode{
SenderId: sender.Uin,
SenderName: (&sender).DisplayName(),
Time: func() int32 {
msgTime := m["time"].(int32)
if hasCustom && msgTime == 0 {
return int32(ts.Unix())
}
return msgTime
}(),
Message: bot.ConvertStringMessage(m["message"].(string), true),
})
return
}
log.Warnf("警告: 引用消息 %v 错误或数据库未开启.", e.Get("data.id").Str)
return
}
uin, _ := strconv.ParseInt(e.Get("data.uin").Str, 10, 64)
msgTime, err := strconv.ParseInt(e.Get("data.time").Str, 10, 64)
if err != nil {
msgTime = ts.Unix()
}
name := e.Get("data.name").Str
c := e.Get("data.content")
if c.IsArray() {
flag := false
c.ForEach(func(_, value gjson.Result) bool {
if value.Get("type").String() == "node" {
flag = true
return false
}
return true
})
if flag {
var taowa []*message.ForwardNode
for _, item := range c.Array() {
taowa = append(taowa, convert(item)...)
}
nodes = append(nodes, &message.ForwardNode{
SenderId: uin,
SenderName: name,
Time: int32(msgTime),
Message: []message.IMessageElement{bot.Client.UploadGroupForwardMessage(groupID, &message.ForwardMessage{Nodes: taowa})},
})
return
}
}
content := bot.ConvertObjectMessage(e.Get("data.content"), true)
if uin != 0 && name != "" && len(content) > 0 {
var newElem []message.IMessageElement
for _, elem := range content {
if img, ok := elem.(*LocalImageElement); ok {
gm, err := bot.UploadLocalImageAsGroup(groupID, img)
if err != nil {
log.Warnf("警告:群 %v 图片上传失败: %v", groupID, err)
continue
}
newElem = append(newElem, gm)
continue
}
if video, ok := elem.(*LocalVideoElement); ok {
gm, err := bot.UploadLocalVideo(groupID, video)
if err != nil {
log.Warnf("警告:群 %v 视频上传失败: %v", groupID, err)
continue
}
newElem = append(newElem, gm)
continue
}
newElem = append(newElem, elem)
}
nodes = append(nodes, &message.ForwardNode{
SenderId: uin,
SenderName: name,
Time: int32(msgTime),
Message: newElem,
})
return
}
log.Warnf("警告: 非法 Forward node 将跳过")
return
}
if m.IsArray() {
for _, item := range m.Array() {
sendNodes = append(sendNodes, convert(item)...)
}
} else {
sendNodes = convert(m)
}
if len(sendNodes) > 0 {
ret := bot.Client.SendGroupForwardMessage(groupID, &message.ForwardMessage{Nodes: sendNodes})
if ret == nil || ret.Id == -1 {
log.Warnf("合并转发(群)消息发送失败: 账号可能被风控.")
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
}
return OK(MSG{
"message_id": bot.InsertGroupMessage(ret),
})
}
return Failed(100)
}
// CQSendPrivateMessage 发送私聊消息
//
// https://git.io/Jtz1l
func (bot *CQBot) CQSendPrivateMessage(userID int64, groupID int64, i interface{}, autoEscape bool) MSG {
var str string
if m, ok := i.(gjson.Result); ok {
if m.Type == gjson.JSON {
elem := bot.ConvertObjectMessage(m, false)
mid := bot.SendPrivateMessage(userID, groupID, &message.SendingMessage{Elements: elem})
if mid == -1 {
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
}
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userID, userID, limitedString(m.String()), mid)
return OK(MSG{"message_id": mid})
}
str = func() string {
if m.Str != "" {
return m.Str
}
return m.Raw
}()
} else if s, ok := i.(string); ok {
str = s
}
if str == "" {
return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
}
var elem []message.IMessageElement
if autoEscape {
elem = append(elem, message.NewText(str))
} else {
elem = bot.ConvertStringMessage(str, false)
}
mid := bot.SendPrivateMessage(userID, groupID, &message.SendingMessage{Elements: elem})
if mid == -1 {
return Failed(100, "SEND_MSG_API_ERROR", "请参考输出")
}
log.Infof("发送好友 %v(%v) 的消息: %v (%v)", userID, userID, limitedString(str), mid)
return OK(MSG{"message_id": mid})
}
// CQSetGroupCard 设置群名片(群备注)
//
// https://git.io/Jtz1B
func (bot *CQBot) CQSetGroupCard(groupID, userID int64, card string) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil {
m.EditCard(card)
return OK(nil)
}
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQSetGroupSpecialTitle 设置群组专属头衔
//
// https://git.io/Jtz10
func (bot *CQBot) CQSetGroupSpecialTitle(groupID, userID int64, title string) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil {
m.EditSpecialTitle(title)
return OK(nil)
}
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQSetGroupName 设置群名
//
// https://git.io/Jtz12
func (bot *CQBot) CQSetGroupName(groupID int64, name string) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
g.UpdateName(name)
return OK(nil)
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQSetGroupMemo 扩展API-发送群公告
//
// https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E7%BE%A4%E5%85%AC%E5%91%8A
func (bot *CQBot) CQSetGroupMemo(groupID int64, msg string, img string) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
if g.SelfPermission() == client.Member {
return Failed(100, "PERMISSION_DENIED", "权限不足")
}
if img != "" {
data, err := global.FindFile(img, "", global.ImagePath)
if err != nil {
return Failed(100, "IMAGE_NOT_FOUND", "图片未找到")
}
err = bot.Client.AddGroupNoticeWithPic(groupID, msg, data)
if err != nil {
return Failed(100, "SEND_NOTICE_ERROR", err.Error())
}
} else {
err := bot.Client.AddGroupNoticeSimple(groupID, msg)
if err != nil {
return Failed(100, "SEND_NOTICE_ERROR", err.Error())
}
}
return OK(nil)
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQSetGroupKick 群组踢人
//
// https://git.io/Jtz1V
func (bot *CQBot) CQSetGroupKick(groupID, userID int64, msg string, block bool) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil {
err := m.Kick(msg, block)
if err != nil {
return Failed(100, "NOT_MANAGEABLE", "机器人权限不足")
}
return OK(nil)
}
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQSetGroupBan 群组单人禁言
//
// https://git.io/Jtz1w
func (bot *CQBot) CQSetGroupBan(groupID, userID int64, duration uint32) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
if m := g.FindMember(userID); m != nil {
err := m.Mute(duration)
if err != nil {
if duration > 2592000 {
return Failed(100, "DURATION_IS_NOT_IN_RANGE", "非法的禁言时长")
}
return Failed(100, "NOT_MANAGEABLE", "机器人权限不足")
}
return OK(nil)
}
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQSetGroupWholeBan 群组全员禁言
//
// https://git.io/Jtz1o
func (bot *CQBot) CQSetGroupWholeBan(groupID int64, enable bool) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
g.MuteAll(enable)
return OK(nil)
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQSetGroupLeave 退出群组
//
// https://git.io/Jtz1K
func (bot *CQBot) CQSetGroupLeave(groupID int64) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
g.Quit()
return OK(nil)
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQGetAtAllRemain 扩展API-获取群 @全体成员 剩余次数
//
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4-%E5%85%A8%E4%BD%93%E6%88%90%E5%91%98-%E5%89%A9%E4%BD%99%E6%AC%A1%E6%95%B0
func (bot *CQBot) CQGetAtAllRemain(groupID int64) MSG {
if g := bot.Client.FindGroup(groupID); g != nil {
i, err := bot.Client.GetAtAllRemain(groupID)
if err != nil {
return Failed(100, "GROUP_REMAIN_API_ERROR", err.Error())
}
return OK(i)
}
return Failed(100, "GROUP_NOT_FOUND", "群聊不存在")
}
// CQProcessFriendRequest 处理加好友请求
//
// https://git.io/Jtz11
func (bot *CQBot) CQProcessFriendRequest(flag string, approve bool) MSG {
req, ok := bot.friendReqCache.Load(flag)
if !ok {
return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
}
if approve {
req.(*client.NewFriendRequest).Accept()
} else {
req.(*client.NewFriendRequest).Reject()
}
return OK(nil)
}
// CQProcessGroupRequest 处理加群请求/邀请
//
// https://git.io/Jtz1D
func (bot *CQBot) CQProcessGroupRequest(flag, subType, reason string, approve bool) MSG {
msgs, err := bot.Client.GetGroupSystemMessages()
if err != nil {
log.Errorf("获取群系统消息失败: %v", err)
return Failed(100, "SYSTEM_MSG_API_ERROR", err.Error())
}
if subType == "add" {
for _, req := range msgs.JoinRequests {
if strconv.FormatInt(req.RequestId, 10) == flag {
if req.Checked {
log.Errorf("处理群系统消息失败: 无法操作已处理的消息.")
return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
}
if approve {
req.Accept()
} else {
req.Reject(false, reason)
}
return OK(nil)
}
}
} else {
for _, req := range msgs.InvitedRequests {
if strconv.FormatInt(req.RequestId, 10) == flag {
if req.Checked {
log.Errorf("处理群系统消息失败: 无法操作已处理的消息.")
return Failed(100, "FLAG_HAS_BEEN_CHECKED", "消息已被处理")
}
if approve {
req.Accept()
} else {
req.Reject(false, reason)
}
return OK(nil)
}
}
}
log.Errorf("处理群系统消息失败: 消息 %v 不存在.", flag)
return Failed(100, "FLAG_NOT_FOUND", "FLAG不存在")
}
// CQDeleteMessage 撤回消息
//
// https:// git.io/Jtz1y
func (bot *CQBot) CQDeleteMessage(messageID int32) MSG {
msg := bot.GetMessage(messageID)
if msg == nil {
return Failed(100, "MESSAGE_NOT_FOUND", "消息不存在")
}
if _, ok := msg["group"]; ok {
if msg["internal-id"] == nil {
// TODO 撤回临时对话消息
log.Warnf("撤回 %v 失败: 无法撤回临时对话消息", messageID)
return Failed(100, "CANNOT_RECALL_TEMP_MSG", "无法撤回临时对话消息")
}
if err := bot.Client.RecallGroupMessage(msg["group"].(int64), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
log.Warnf("撤回 %v 失败: %v", messageID, err)
return Failed(100, "RECALL_API_ERROR", err.Error())
}
} else {
if msg["sender"].(message.Sender).Uin != bot.Client.Uin {
log.Warnf("撤回 %v 失败: 好友会话无法撤回对方消息.", messageID)
return Failed(100, "CANNOT_RECALL_FRIEND_MSG", "无法撤回对方消息")
}
if err := bot.Client.RecallPrivateMessage(msg["target"].(int64), int64(msg["time"].(int32)), msg["message-id"].(int32), msg["internal-id"].(int32)); err != nil {
log.Warnf("撤回 %v 失败: %v", messageID, err)
return Failed(100, "RECALL_API_ERROR", err.Error())
}
}
return OK(nil)
}
// CQSetGroupAdmin 群组设置管理员
//
// https://git.io/Jtz1S
func (bot *CQBot) CQSetGroupAdmin(groupID, userID int64, enable bool) MSG {
group := bot.Client.FindGroup(groupID)
if group == nil || group.OwnerUin != bot.Client.Uin {
return Failed(100, "PERMISSION_DENIED", "群不存在或权限不足")
}
mem := group.FindMember(userID)
if mem == nil {
return Failed(100, "GROUP_MEMBER_NOT_FOUND", "群成员不存在")
}
mem.SetAdmin(enable)
t, err := bot.Client.GetGroupMembers(group)
if err != nil {
log.Warnf("刷新群 %v 成员列表失败: %v", groupID, err)
return Failed(100, "GET_MEMBERS_API_ERROR", err.Error())
}
group.Members = t
return OK(nil)
}
// CQGetVipInfo 扩展API-获取VIP信息
//
// https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96vip%E4%BF%A1%E6%81%AF
func (bot *CQBot) CQGetVipInfo(userID int64) MSG {
vip, err := bot.Client.GetVipInfo(userID)
if err != nil {
return Failed(100, "VIP_API_ERROR", err.Error())
}
msg := MSG{
"user_id": vip.Uin,
"nickname": vip.Name,
"level": vip.Level,
"level_speed": vip.LevelSpeed,
"vip_level": vip.VipLevel,
"vip_growth_speed": vip.VipGrowthSpeed,
"vip_growth_total": vip.VipGrowthTotal,
}
return OK(msg)
}
// CQGetGroupHonorInfo 获取群荣誉信息
//
// https://git.io/Jtz1H
func (bot *CQBot) CQGetGroupHonorInfo(groupID int64, t string) MSG {
msg := MSG{"group_id": groupID}
convertMem := func(memList []client.HonorMemberInfo) (ret []MSG) {
for _, mem := range memList {
ret = append(ret, MSG{
"user_id": mem.Uin,
"nickname": mem.Name,
"avatar": mem.Avatar,
"description": mem.Desc,
})
}
return
}
if t == "talkative" || t == "all" {
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Talkative); err == nil {
if honor.CurrentTalkative.Uin != 0 {
msg["current_talkative"] = MSG{
"user_id": honor.CurrentTalkative.Uin,
"nickname": honor.CurrentTalkative.Name,
"avatar": honor.CurrentTalkative.Avatar,
"day_count": honor.CurrentTalkative.DayCount,
}
}
msg["talkative_list"] = convertMem(honor.TalkativeList)
}
}
if t == "performer" || t == "all" {
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Performer); err == nil {
msg["performer_lis"] = convertMem(honor.ActorList)
}
}
if t == "legend" || t == "all" {
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Legend); err == nil {
msg["legend_list"] = convertMem(honor.LegendList)
}
}
if t == "strong_newbie" || t == "all" {
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.StrongNewbie); err == nil {
msg["strong_newbie_list"] = convertMem(honor.StrongNewbieList)
}
}
if t == "emotion" || t == "all" {
if honor, err := bot.Client.GetGroupHonorInfo(groupID, client.Emotion); err == nil {
msg["emotion_list"] = convertMem(honor.EmotionList)
}
}
return OK(msg)
}
// CQGetStrangerInfo 获取陌生人信息
//
// https://git.io/Jtz17
func (bot *CQBot) CQGetStrangerInfo(userID int64) MSG {
info, err := bot.Client.GetSummaryInfo(userID)
if err != nil {
return Failed(100, "SUMMARY_API_ERROR", err.Error())
}
return OK(MSG{
"user_id": info.Uin,
"nickname": info.Nickname,
"qid": info.Qid,
"sex": func() string {
if info.Sex == 1 {
return "female"
} else if info.Sex == 0 {
return "male"
}
// unknown = 0x2
return "unknown"
}(),
"age": info.Age,
"level": info.Level,
"login_days": info.LoginDays,
})
}
// CQHandleQuickOperation 隐藏API-对事件执行快速操作
//
// https://git.io/Jtz15
func (bot *CQBot) CQHandleQuickOperation(context, operation gjson.Result) MSG {
postType := context.Get("post_type").Str
switch postType {
case "message":
anonymous := context.Get("anonymous")
isAnonymous := anonymous.Type != gjson.Null
msgType := context.Get("message_type").Str
reply := operation.Get("reply")
if reply.Exists() {
autoEscape := global.EnsureBool(operation.Get("auto_escape"), false)
at := operation.Get("at_sender").Bool() && !isAnonymous && msgType == "group"
if at && reply.IsArray() {
// 在 reply 数组头部插入CQ码
replySegments := make([]MSG, 0)
segments := make([]MSG, 0)
segments = append(segments, MSG{
"type": "at",
"data": MSG{
"qq": context.Get("sender.user_id").Int(),
},
})
err := json.UnmarshalFromString(reply.Raw, &replySegments)
if err != nil {
log.WithError(err).Warnf("处理 at_sender 过程中发生错误")
return Failed(-1, "处理 at_sender 过程中发生错误", err.Error())
}
segments = append(segments, replySegments...)
modified, err := json.MarshalToString(segments)
if err != nil {
log.WithError(err).Warnf("处理 at_sender 过程中发生错误")
return Failed(-1, "处理 at_sender 过程中发生错误", err.Error())
}
reply = gjson.Parse(modified)
} else if at && reply.Type == gjson.String {
reply = gjson.Parse(fmt.Sprintf(
"\"[CQ:at,qq=%d]%s\"",
context.Get("sender.user_id").Int(),
reply.String(),
))
}
if msgType == "group" {
bot.CQSendGroupMessage(context.Get("group_id").Int(), reply, autoEscape)
}
if msgType == "private" {
bot.CQSendPrivateMessage(context.Get("user_id").Int(), context.Get("group_id").Int(), reply, autoEscape)
}
}
if msgType == "group" {
if operation.Get("delete").Bool() {
bot.CQDeleteMessage(int32(context.Get("message_id").Int()))
}
if operation.Get("kick").Bool() && !isAnonymous {
bot.CQSetGroupKick(context.Get("group_id").Int(), context.Get("user_id").Int(), "", operation.Get("reject_add_request").Bool())
}
if operation.Get("ban").Bool() {
var duration uint32 = 30 * 60
if operation.Get("ban_duration").Exists() {
duration = uint32(operation.Get("ban_duration").Uint())
}
// unsupported anonymous ban yet
if !isAnonymous {
bot.CQSetGroupBan(context.Get("group_id").Int(), context.Get("user_id").Int(), duration)
}
}
}
case "request":
reqType := context.Get("request_type").Str
if operation.Get("approve").Exists() {
if reqType == "friend" {