/
api.go
2171 lines (2054 loc) · 66.5 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"
"encoding/json"
"fmt"
"math"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/Mrs4s/MiraiGo/binary"
"github.com/Mrs4s/MiraiGo/client"
"github.com/Mrs4s/MiraiGo/message"
"github.com/Mrs4s/MiraiGo/utils"
"github.com/segmentio/asm/base64"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/Mrs4s/go-cqhttp/db"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/internal/base"
"github.com/Mrs4s/go-cqhttp/internal/cache"
"github.com/Mrs4s/go-cqhttp/internal/download"
"github.com/Mrs4s/go-cqhttp/internal/msg"
"github.com/Mrs4s/go-cqhttp/internal/param"
"github.com/Mrs4s/go-cqhttp/modules/filter"
"github.com/Mrs4s/go-cqhttp/pkg/onebot"
)
type guildMemberPageToken struct {
guildID uint64
nextIndex uint32
nextRoleID uint64
nextQueryParam string
}
var defaultPageToken = guildMemberPageToken{
guildID: 0,
nextIndex: 0,
nextRoleID: 2,
}
// CQGetLoginInfo 获取登录号信息
//
// https://git.io/Jtz1I
// @route11(get_login_info)
// @route12(get_self_info)
func (bot *CQBot) CQGetLoginInfo() global.MSG {
return OK(global.MSG{"user_id": bot.Client.Uin, "nickname": bot.Client.Nickname})
}
// CQGetQiDianAccountInfo 获取企点账号信息
// @route(qidian_get_account_info)
func (bot *CQBot) CQGetQiDianAccountInfo() global.MSG {
if bot.Client.QiDian == nil {
return Failed(100, "QIDIAN_PROTOCOL_REQUEST", "请使用企点协议")
}
return OK(global.MSG{
"master_id": bot.Client.QiDian.MasterUin,
"ext_name": bot.Client.QiDian.ExtName,
"create_time": bot.Client.QiDian.CreateTime,
})
}
// CQGetGuildServiceProfile 获取频道系统个人资料
// @route(get_guild_service_profile)
func (bot *CQBot) CQGetGuildServiceProfile() global.MSG {
return OK(global.MSG{
"nickname": bot.Client.GuildService.Nickname,
"tiny_id": fU64(bot.Client.GuildService.TinyId),
"avatar_url": bot.Client.GuildService.AvatarUrl,
})
}
// CQGetGuildList 获取已加入的频道列表
// @route(get_guild_list)
func (bot *CQBot) CQGetGuildList() global.MSG {
fs := make([]global.MSG, 0, len(bot.Client.GuildService.Guilds))
for _, info := range bot.Client.GuildService.Guilds {
/* 做成单独的 api 可能会好些?
channels := make([]global.MSG, 0, len(info.Channels))
for _, channel := range info.Channels {
channels = append(channels, global.MSG{
"channel_id": channel.ChannelId,
"channel_name": channel.ChannelName,
"channel_type": channel.ChannelType,
})
}
*/
fs = append(fs, global.MSG{
"guild_id": fU64(info.GuildId),
"guild_name": info.GuildName,
"guild_display_id": fU64(info.GuildCode),
// "channels": channels,
})
}
return OK(fs)
}
// CQGetGuildMetaByGuest 通过访客权限获取频道元数据
// @route(get_guild_meta_by_guest)
func (bot *CQBot) CQGetGuildMetaByGuest(guildID uint64) global.MSG {
meta, err := bot.Client.GuildService.FetchGuestGuild(guildID)
if err != nil {
log.Errorf("获取频道元数据时出现错误: %v", err)
return Failed(100, "API_ERROR", err.Error())
}
return OK(global.MSG{
"guild_id": fU64(meta.GuildId),
"guild_name": meta.GuildName,
"guild_profile": meta.GuildProfile,
"create_time": meta.CreateTime,
"max_member_count": meta.MaxMemberCount,
"max_robot_count": meta.MaxRobotCount,
"max_admin_count": meta.MaxAdminCount,
"member_count": meta.MemberCount,
"owner_id": fU64(meta.OwnerId),
})
}
// CQGetGuildChannelList 获取频道列表
// @route(get_guild_channel_list)
func (bot *CQBot) CQGetGuildChannelList(guildID uint64, noCache bool) global.MSG {
guild := bot.Client.GuildService.FindGuild(guildID)
if guild == nil {
return Failed(100, "GUILD_NOT_FOUND")
}
if noCache {
channels, err := bot.Client.GuildService.FetchChannelList(guildID)
if err != nil {
log.Warnf("获取频道 %v 子频道列表时出现错误: %v", guildID, err)
return Failed(100, "API_ERROR", err.Error())
}
guild.Channels = channels
}
channels := make([]global.MSG, 0, len(guild.Channels))
for _, c := range guild.Channels {
channels = append(channels, convertChannelInfo(c))
}
return OK(channels)
}
// CQGetGuildMembers 获取频道成员列表
// @route(get_guild_member_list)
func (bot *CQBot) CQGetGuildMembers(guildID uint64, nextToken string) global.MSG {
guild := bot.Client.GuildService.FindGuild(guildID)
if guild == nil {
return Failed(100, "GUILD_NOT_FOUND")
}
token := &defaultPageToken
if nextToken != "" {
i, exists := bot.nextTokenCache.Get(nextToken)
if !exists {
return Failed(100, "NEXT_TOKEN_NOT_EXISTS")
}
token = i
if token.guildID != guildID {
return Failed(100, "GUILD_NOT_MATCH")
}
}
ret, err := bot.Client.GuildService.FetchGuildMemberListWithRole(guildID, 0, token.nextIndex, token.nextRoleID, token.nextQueryParam)
if err != nil {
return Failed(100, "API_ERROR", err.Error())
}
res := global.MSG{
"members": convertGuildMemberInfo(ret.Members),
"finished": ret.Finished,
"next_token": nil,
}
if !ret.Finished {
next := &guildMemberPageToken{
guildID: guildID,
nextIndex: ret.NextIndex,
nextRoleID: ret.NextRoleId,
nextQueryParam: ret.NextQueryParam,
}
id := base64.StdEncoding.EncodeToString(binary.NewWriterF(func(w *binary.Writer) {
w.WriteUInt64(uint64(time.Now().UnixNano()))
w.WriteString(utils.RandomString(5))
}))
bot.nextTokenCache.Add(id, next, time.Minute*10)
res["next_token"] = id
}
return OK(res)
}
// CQGetGuildMemberProfile 获取频道成员资料
// @route(get_guild_member_profile)
func (bot *CQBot) CQGetGuildMemberProfile(guildID, userID uint64) global.MSG {
if bot.Client.GuildService.FindGuild(guildID) == nil {
return Failed(100, "GUILD_NOT_FOUND")
}
profile, err := bot.Client.GuildService.FetchGuildMemberProfileInfo(guildID, userID)
if err != nil {
log.Warnf("获取频道 %v 成员 %v 资料时出现错误: %v", guildID, userID, err)
return Failed(100, "API_ERROR", err.Error())
}
roles := make([]global.MSG, 0, len(profile.Roles))
for _, role := range profile.Roles {
roles = append(roles, global.MSG{
"role_id": fU64(role.RoleId),
"role_name": role.RoleName,
})
}
return OK(global.MSG{
"tiny_id": fU64(profile.TinyId),
"nickname": profile.Nickname,
"avatar_url": profile.AvatarUrl,
"join_time": profile.JoinTime,
"roles": roles,
})
}
// CQGetGuildRoles 获取频道角色列表
// @route(get_guild_roles)
func (bot *CQBot) CQGetGuildRoles(guildID uint64) global.MSG {
r, err := bot.Client.GuildService.GetGuildRoles(guildID)
if err != nil {
log.Warnf("获取频道 %v 角色列表时出现错误: %v", guildID, err)
return Failed(100, "API_ERROR", err.Error())
}
roles := make([]global.MSG, len(r))
for i, role := range r {
roles[i] = global.MSG{
"role_id": fU64(role.RoleId),
"role_name": role.RoleName,
"argb_color": role.ArgbColor,
"independent": role.Independent,
"member_count": role.Num,
"max_count": role.MaxNum,
"owned": role.Owned,
"disabled": role.Disabled,
}
}
return OK(roles)
}
// CQCreateGuildRole 创建频道角色
// @route(create_guild_role)
func (bot *CQBot) CQCreateGuildRole(guildID uint64, name string, color uint32, independent bool, initialUsers gjson.Result) global.MSG {
userSlice := []uint64{}
if initialUsers.IsArray() {
for _, user := range initialUsers.Array() {
userSlice = append(userSlice, user.Uint())
}
}
role, err := bot.Client.GuildService.CreateGuildRole(guildID, name, color, independent, userSlice)
if err != nil {
log.Warnf("创建频道 %v 角色时出现错误: %v", guildID, err)
return Failed(100, "API_ERROR", err.Error())
}
return OK(global.MSG{
"role_id": fU64(role),
})
}
// CQDeleteGuildRole 删除频道角色
// @route(delete_guild_role)
func (bot *CQBot) CQDeleteGuildRole(guildID uint64, roleID uint64) global.MSG {
err := bot.Client.GuildService.DeleteGuildRole(guildID, roleID)
if err != nil {
log.Warnf("删除频道 %v 角色时出现错误: %v", guildID, err)
return Failed(100, "API_ERROR", err.Error())
}
return OK(nil)
}
// CQSetGuildMemberRole 设置用户在频道中的角色
// @route(set_guild_member_role)
func (bot *CQBot) CQSetGuildMemberRole(guildID uint64, set bool, roleID uint64, users gjson.Result) global.MSG {
userSlice := []uint64{}
if users.IsArray() {
for _, user := range users.Array() {
userSlice = append(userSlice, user.Uint())
}
}
err := bot.Client.GuildService.SetUserRoleInGuild(guildID, set, roleID, userSlice)
if err != nil {
log.Warnf("设置用户在频道 %v 中的角色时出现错误: %v", guildID, err)
return Failed(100, "API_ERROR", err.Error())
}
return OK(nil)
}
// CQModifyRoleInGuild 修改频道角色
// @route(update_guild_role)
func (bot *CQBot) CQModifyRoleInGuild(guildID uint64, roleID uint64, name string, color uint32, indepedent bool) global.MSG {
err := bot.Client.GuildService.ModifyRoleInGuild(guildID, roleID, name, color, indepedent)
if err != nil {
log.Warnf("修改频道 %v 角色时出现错误: %v", guildID, err)
return Failed(100, "API_ERROR", err.Error())
}
return OK(nil)
}
// CQGetTopicChannelFeeds 获取话题频道帖子列表
// @route(get_topic_channel_feeds)
func (bot *CQBot) CQGetTopicChannelFeeds(guildID, channelID uint64) global.MSG {
guild := bot.Client.GuildService.FindGuild(guildID)
if guild == nil {
return Failed(100, "GUILD_NOT_FOUND")
}
channel := guild.FindChannel(channelID)
if channel == nil {
return Failed(100, "CHANNEL_NOT_FOUND")
}
if channel.ChannelType != client.ChannelTypeTopic {
return Failed(100, "CHANNEL_TYPE_ERROR")
}
feeds, err := bot.Client.GuildService.GetTopicChannelFeeds(guildID, channelID)
if err != nil {
log.Warnf("获取频道 %v 帖子时出现错误: %v", channelID, err)
return Failed(100, "API_ERROR", err.Error())
}
c := make([]global.MSG, 0, len(feeds))
for _, feed := range feeds {
c = append(c, convertChannelFeedInfo(feed))
}
return OK(c)
}
// CQGetFriendList 获取好友列表
//
// https://git.io/Jtz1L
// @route(get_friend_list)
func (bot *CQBot) CQGetFriendList(spec *onebot.Spec) global.MSG {
fs := make([]global.MSG, 0, len(bot.Client.FriendList))
for _, f := range bot.Client.FriendList {
fs = append(fs, global.MSG{
"nickname": f.Nickname,
"remark": f.Remark,
"user_id": spec.ConvertID(f.Uin),
})
}
return OK(fs)
}
// CQGetUnidirectionalFriendList 获取单向好友列表
//
// @route(get_unidirectional_friend_list)
func (bot *CQBot) CQGetUnidirectionalFriendList() global.MSG {
list, err := bot.Client.GetUnidirectionalFriendList()
if err != nil {
log.Warnf("获取单向好友列表时出现错误: %v", err)
return Failed(100, "API_ERROR", err.Error())
}
fs := make([]global.MSG, 0, len(list))
for _, f := range list {
fs = append(fs, global.MSG{
"nickname": f.Nickname,
"user_id": f.Uin,
"source": f.Source,
})
}
return OK(fs)
}
// CQDeleteUnidirectionalFriend 删除单向好友
//
// @route(delete_unidirectional_friend)
// @rename(uin->user_id)
func (bot *CQBot) CQDeleteUnidirectionalFriend(uin int64) global.MSG {
list, err := bot.Client.GetUnidirectionalFriendList()
if err != nil {
log.Warnf("获取单向好友列表时出现错误: %v", err)
return Failed(100, "API_ERROR", err.Error())
}
for _, f := range list {
if f.Uin == uin {
if err = bot.Client.DeleteUnidirectionalFriend(uin); err != nil {
log.Warnf("删除单向好友时出现错误: %v", err)
return Failed(100, "API_ERROR", err.Error())
}
return OK(nil)
}
}
return Failed(100, "FRIEND_NOT_FOUND", "好友不存在")
}
// CQDeleteFriend 删除好友
// @route(delete_friend)
// @rename(uin->"[user_id\x2Cid].0")
func (bot *CQBot) CQDeleteFriend(uin int64) global.MSG {
if bot.Client.FindFriend(uin) == nil {
return Failed(100, "FRIEND_NOT_FOUND", "好友不存在")
}
if err := bot.Client.DeleteFriend(uin); err != nil {
log.Warnf("删除好友时出现错误: %v", err)
return Failed(100, "DELETE_API_ERROR", err.Error())
}
return OK(nil)
}
// CQGetGroupList 获取群列表
//
// https://git.io/Jtz1t
// @route(get_group_list)
func (bot *CQBot) CQGetGroupList(noCache bool, spec *onebot.Spec) global.MSG {
gs := make([]global.MSG, 0, len(bot.Client.GroupList))
if noCache {
_ = bot.Client.ReloadGroupList()
}
for _, g := range bot.Client.GroupList {
gs = append(gs, global.MSG{
"group_id": spec.ConvertID(g.Code),
"group_name": g.Name,
"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
// @route(get_group_info)
func (bot *CQBot) CQGetGroupInfo(groupID int64, noCache bool, spec *onebot.Spec) global.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(global.MSG{
"group_id": spec.ConvertID(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(global.MSG{
"group_id": spec.ConvertID(group.Code),
"group_name": group.Name,
"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
// @route(get_group_member_list)
func (bot *CQBot) CQGetGroupMemberList(groupID int64, noCache bool) global.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([]global.MSG, 0, len(group.Members))
for _, m := range group.Members {
members = append(members, convertGroupMemberInfo(groupID, m))
}
return OK(members)
}
// CQGetGroupMemberInfo 获取群成员信息
//
// https://git.io/Jtz1s
// @route(get_group_member_info)
func (bot *CQBot) CQGetGroupMemberInfo(groupID, userID int64, noCache bool) global.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
// @route(get_group_file_system_info)
func (bot *CQBot) CQGetGroupFileSystemInfo(groupID int64) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Warnf("获取群 %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
// @route(get_group_root_files)
func (bot *CQBot) CQGetGroupRootFiles(groupID int64) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Warnf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
files, folders, err := fs.Root()
if err != nil {
log.Warnf("获取群 %v 根目录文件失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(global.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
// @route(get_group_files_by_folder)
func (bot *CQBot) CQGetGroupFilesByFolderID(groupID int64, folderID string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Warnf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
files, folders, err := fs.GetFilesByFolder(folderID)
if err != nil {
log.Warnf("获取群 %v 根目录 %v 子文件失败: %v", groupID, folderID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(global.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
// @route(get_group_file_url)
// @rename(bus_id->"[busid\x2Cbus_id].0")
func (bot *CQBot) CQGetGroupFileURL(groupID int64, fileID string, busID int32) global.MSG {
url := bot.Client.GetGroupFileUrl(groupID, fileID, busID)
if url == "" {
return Failed(100, "FILE_SYSTEM_API_ERROR")
}
return OK(global.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
// @route(upload_group_file)
func (bot *CQBot) CQUploadGroupFile(groupID int64, file, name, folder string) global.MSG {
if !global.PathExists(file) {
log.Warnf("上传群文件 %v 失败: 文件不存在", file)
return Failed(100, "FILE_NOT_FOUND", "文件不存在")
}
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Warnf("获取群 %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.Warnf("上传群 %v 文件 %v 失败: %v", groupID, file, err)
return Failed(100, "FILE_SYSTEM_UPLOAD_API_ERROR", err.Error())
}
return OK(nil)
}
// CQUploadPrivateFile 扩展API-上传私聊文件
//
// @route(upload_private_file)
func (bot *CQBot) CQUploadPrivateFile(userID int64, file, name string) global.MSG {
target := message.Source{
SourceType: message.SourcePrivate,
PrimaryID: userID,
}
fileBody, err := os.Open(file)
if err != nil {
log.Warnf("上传私聊文件 %v 失败: %+v", file, err)
return Failed(100, "OPEN_FILE_ERROR", "打开文件失败")
}
defer func() { _ = fileBody.Close() }()
localFile := &client.LocalFile{
FileName: name,
Body: fileBody,
}
if err := bot.Client.UploadFile(target, localFile); err != nil {
log.Warnf("上传私聊 %v 文件 %v 失败: %+v", userID, file, err)
return Failed(100, "FILE_SYSTEM_UPLOAD_API_ERROR", err.Error())
}
return OK(nil)
}
// CQGroupFileCreateFolder 拓展API-创建群文件文件夹
//
// @route(create_group_file_folder)
func (bot *CQBot) CQGroupFileCreateFolder(groupID int64, parentID, name string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Warnf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
if err = fs.CreateFolder(parentID, name); err != nil {
log.Warnf("创建群 %v 文件夹失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(nil)
}
// CQGroupFileDeleteFolder 拓展API-删除群文件文件夹
//
// @route(delete_group_folder)
// @rename(id->folder_id)
func (bot *CQBot) CQGroupFileDeleteFolder(groupID int64, id string) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Warnf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
if err = fs.DeleteFolder(id); err != nil {
log.Warnf("删除群 %v 文件夹 %v 时出现文件: %v", groupID, id, err)
return Failed(200, "FILE_SYSTEM_API_ERROR", err.Error())
}
return OK(nil)
}
// CQGroupFileDeleteFile 拓展API-删除群文件
//
// @route(delete_group_file)
// @rename(id->file_id, bus_id->"[busid\x2Cbus_id].0")
func (bot *CQBot) CQGroupFileDeleteFile(groupID int64, id string, busID int32) global.MSG {
fs, err := bot.Client.GetGroupFileSystem(groupID)
if err != nil {
log.Warnf("获取群 %v 文件系统信息失败: %v", groupID, err)
return Failed(100, "FILE_SYSTEM_API_ERROR", err.Error())
}
if res := fs.DeleteFile("", id, busID); res != "" {
log.Warnf("删除群 %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
// @route(.get_word_slices)
func (bot *CQBot) CQGetWordSlices(content string) global.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(global.MSG{"slices": slices})
}
// CQSendMessage 发送消息
//
// @route11(send_msg)
// @rename(m->message)
func (bot *CQBot) CQSendMessage(groupID, userID int64, m gjson.Result, messageType string, autoEscape bool) global.MSG {
switch {
case messageType == "group":
return bot.CQSendGroupMessage(groupID, m, autoEscape)
case messageType == "private":
fallthrough
case userID != 0:
return bot.CQSendPrivateMessage(userID, groupID, m, autoEscape)
case groupID != 0:
return bot.CQSendGroupMessage(groupID, m, autoEscape)
}
return global.MSG{}
}
// CQSendForwardMessage 发送合并转发消息
//
// @route11(send_forward_msg)
// @rename(m->messages)
func (bot *CQBot) CQSendForwardMessage(groupID, userID int64, m gjson.Result, messageType string) global.MSG {
switch {
case messageType == "group":
return bot.CQSendGroupForwardMessage(groupID, m)
case messageType == "private":
fallthrough
case userID != 0:
return bot.CQSendPrivateForwardMessage(userID, m)
case groupID != 0:
return bot.CQSendGroupForwardMessage(groupID, m)
}
return global.MSG{}
}
// CQSendGroupMessage 发送群消息
//
// https://git.io/Jtz1c
// @route11(send_group_msg)
// @rename(m->message)
func (bot *CQBot) CQSendGroupMessage(groupID int64, m gjson.Result, autoEscape bool) global.MSG {
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 == "" {
mem := group.FindMember(at.Target)
if mem != nil {
at.Display = "@" + mem.DisplayName()
} else {
at.Display = "@" + strconv.FormatInt(at.Target, 10)
}
}
}
}
var elem []message.IMessageElement
if m.Type == gjson.JSON {
elem = bot.ConvertObjectMessage(onebot.V11, m, message.SourceGroup)
} else {
str := m.String()
if str == "" {
log.Warnf("群 %v 消息发送失败: 信息为空.", groupID)
return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
}
if autoEscape {
elem = []message.IMessageElement{message.NewText(str)}
} else {
elem = bot.ConvertStringMessage(onebot.V11, str, message.SourceGroup)
}
}
fixAt(elem)
mid, err := bot.SendGroupMessage(groupID, &message.SendingMessage{Elements: elem})
if err != nil {
return Failed(100, "SEND_MSG_API_ERROR", err.Error())
}
log.Infof("发送群 %v(%v) 的消息: %v (%v)", group.Name, groupID, limitedString(m.String()), mid)
return OK(global.MSG{"message_id": mid})
}
// CQSendGuildChannelMessage 发送频道消息
//
// @route(send_guild_channel_msg)
// @rename(m->message)
func (bot *CQBot) CQSendGuildChannelMessage(guildID, channelID uint64, m gjson.Result, autoEscape bool) global.MSG {
guild := bot.Client.GuildService.FindGuild(guildID)
if guild == nil {
return Failed(100, "GUILD_NOT_FOUND", "频道不存在")
}
channel := guild.FindChannel(channelID)
if channel == nil {
return Failed(100, "CHANNEL_NOT_FOUND", "子频道不存在")
}
if channel.ChannelType != client.ChannelTypeText {
log.Warnf("无法发送频道信息: 频道类型错误, 不接受文本信息")
return Failed(100, "CHANNEL_NOT_SUPPORTED_TEXT_MSG", "子频道类型错误, 无法发送文本信息")
}
fixAt := func(elem []message.IMessageElement) {
for _, e := range elem {
if at, ok := e.(*message.AtElement); ok && at.Target != 0 && at.Display == "" {
mem, _ := bot.Client.GuildService.FetchGuildMemberProfileInfo(guildID, uint64(at.Target))
if mem != nil {
at.Display = "@" + mem.Nickname
} else {
at.Display = "@" + strconv.FormatInt(at.Target, 10)
}
}
}
}
var elem []message.IMessageElement
if m.Type == gjson.JSON {
elem = bot.ConvertObjectMessage(onebot.V11, m, message.SourceGuildChannel)
} else {
str := m.String()
if str == "" {
log.Warn("频道发送失败: 信息为空.")
return Failed(100, "EMPTY_MSG_ERROR", "消息为空")
}
if autoEscape {
elem = []message.IMessageElement{message.NewText(str)}
} else {
elem = bot.ConvertStringMessage(onebot.V11, str, message.SourceGuildChannel)
}
}
fixAt(elem)
mid := bot.SendGuildChannelMessage(guildID, channelID, &message.SendingMessage{Elements: elem})
if mid == "" {
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
}
log.Infof("发送频道 %v(%v) 子频道 %v(%v) 的消息: %v (%v)", guild.GuildName, guild.GuildId, channel.ChannelName, channel.ChannelId, limitedString(m.String()), mid)
return OK(global.MSG{"message_id": mid})
}
func (bot *CQBot) uploadForwardElement(m gjson.Result, target int64, sourceType message.SourceType) *message.ForwardElement {
ts := time.Now().Add(-time.Minute * 5)
groupID := target
source := message.Source{SourceType: sourceType, PrimaryID: target}
if sourceType == message.SourcePrivate {
// ios 设备的合并转发来源群号不能为 0
if len(bot.Client.GroupList) == 0 {
groupID = 1
} else {
groupID = bot.Client.GroupList[0].Uin
}
}
builder := bot.Client.NewForwardMessageBuilder(groupID)
var convertMessage func(m gjson.Result) *message.ForwardMessage
convertMessage = func(m gjson.Result) *message.ForwardMessage {
fm := message.NewForwardMessage()
var w worker
resolveElement := func(elems []message.IMessageElement) []message.IMessageElement {
for i, elem := range elems {
p := &elems[i]
switch o := elem.(type) {
case *msg.LocalVideo:
w.do(func() {
gm, err := bot.uploadLocalVideo(source, o)
if err != nil {
log.Warnf(uploadFailedTemplate, "合并转发", target, "视频", err)
} else {
*p = gm
}
})
case *msg.LocalImage:
w.do(func() {
gm, err := bot.uploadLocalImage(source, o)
if err != nil {
log.Warnf(uploadFailedTemplate, "合并转发", target, "图片", err)
} else {
*p = gm
}
})
}
}
return elems
}
convert := func(e gjson.Result) *message.ForwardNode {
if e.Get("type").Str != "node" {
return nil
}
if e.Get("data.id").Exists() {
i := e.Get("data.id").Int()
m, _ := db.GetMessageByGlobalID(int32(i))
if m != nil {
mSource := message.SourcePrivate
if m.GetType() == "group" {
mSource = message.SourceGroup
}
msgTime := m.GetAttribute().Timestamp
if msgTime == 0 {
msgTime = ts.Unix()
}
return &message.ForwardNode{
SenderId: m.GetAttribute().SenderUin,
SenderName: m.GetAttribute().SenderName,
Time: int32(msgTime),
Message: resolveElement(bot.ConvertContentMessage(m.GetContent(), mSource, false)),
}
}
log.Warnf("警告: 引用消息 %v 错误或数据库未开启.", e.Get("data.id").Str)
return nil
}
uin := e.Get("data.[user_id,uin].0").Int()
msgTime := e.Get("data.time").Int()
if msgTime == 0 {
msgTime = ts.Unix()
}
name := e.Get("data.[name,nickname].0").Str
c := e.Get("data.content")
if c.IsArray() {
nested := false
c.ForEach(func(_, value gjson.Result) bool {
if value.Get("type").Str == "node" {
nested = true
return false
}
return true
})
if nested { // 处理嵌套
nestedNode := builder.NestedNode()
builder.Link(nestedNode, convertMessage(c))
return &message.ForwardNode{
SenderId: uin,
SenderName: name,
Time: int32(msgTime),
Message: []message.IMessageElement{nestedNode},
}
}
}
content := bot.ConvertObjectMessage(onebot.V11, c, sourceType)
if uin != 0 && name != "" && len(content) > 0 {
return &message.ForwardNode{
SenderId: uin,
SenderName: name,
Time: int32(msgTime),
Message: resolveElement(content),
}
}
log.Warnf("警告: 非法 Forward node 将跳过. uin: %v name: %v content count: %v", uin, name, len(content))
return nil
}
if m.IsArray() {
for _, item := range m.Array() {
node := convert(item)
if node != nil {
fm.AddNode(node)
}
}
} else {
node := convert(m)
if node != nil {
fm.AddNode(node)
}
}
w.wait()
return fm
}
return builder.Main(convertMessage(m))
}
// 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
// @route11(send_group_forward_msg)
// @rename(m->messages)
func (bot *CQBot) CQSendGroupForwardMessage(groupID int64, m gjson.Result) global.MSG {
if m.Type != gjson.JSON {
return Failed(100)
}
source := message.Source{
SourceType: message.SourcePrivate,
PrimaryID: 0,
}
fe := bot.uploadForwardElement(m, groupID, message.SourceGroup)
if fe == nil {
return Failed(100, "EMPTY_NODES", "未找到任何可发送的合并转发信息")
}
ret := bot.Client.SendGroupForwardMessage(groupID, fe)
if ret == nil || ret.Id == -1 {
log.Warnf("合并转发(群 %v)消息发送失败: 账号可能被风控.", groupID)
return Failed(100, "SEND_MSG_API_ERROR", "请参考 go-cqhttp 端输出")
}
mid := bot.InsertGroupMessage(ret, source)
log.Infof("发送群 %v(%v) 的合并转发消息: %v (%v)", groupID, groupID, limitedString(m.String()), mid)
return OK(global.MSG{
"message_id": mid,
"forward_id": fe.ResId,
})
}
// CQSendPrivateForwardMessage 扩展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
// @route11(send_private_forward_msg)
// @rename(m->messages)
func (bot *CQBot) CQSendPrivateForwardMessage(userID int64, m gjson.Result) global.MSG {