/
privateCommand.go
1445 lines (1284 loc) · 43.7 KB
/
privateCommand.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 lsp
import (
"bufio"
"bytes"
"fmt"
"github.com/Mrs4s/MiraiGo/message"
localdb "github.com/Sora233/DDBOT/lsp/buntdb"
"github.com/Sora233/DDBOT/lsp/concern"
"github.com/Sora233/DDBOT/lsp/concern_type"
"github.com/Sora233/DDBOT/lsp/mmsg"
"github.com/Sora233/DDBOT/lsp/permission"
"github.com/Sora233/DDBOT/lsp/template"
localutils "github.com/Sora233/DDBOT/utils"
"github.com/Sora233/MiraiGo-Template/config"
"github.com/Sora233/sliceutil"
"github.com/alecthomas/kong"
"github.com/sirupsen/logrus"
"os"
"runtime/debug"
"strconv"
"strings"
"time"
)
type LspPrivateCommand struct {
msg *message.PrivateMessage
*Runtime
}
func NewLspPrivateCommand(l *Lsp, msg *message.PrivateMessage) *LspPrivateCommand {
c := &LspPrivateCommand{
msg: msg,
Runtime: NewRuntime(l),
}
c.Parse(c.msg.Elements)
return c
}
func (c *LspPrivateCommand) Execute() {
defer func() {
if err := recover(); err != nil {
logger.WithField("stack", string(debug.Stack())).
Errorf("panic recovered: %v", err)
c.textSend("エラー発生:看到该信息表示BOT出了一些问题,该问题已记录")
}
}()
if len(c.CommandName()) == 0 {
return
}
log := c.DefaultLogger().WithField("cmd", c.GetCmdArgs())
if c.l.PermissionStateManager.CheckBlockList(c.uin()) {
log.Debug("blocked")
return
}
if !c.DebugCheck() {
log.Debugf("debug mode, skip execute.")
return
}
log.Debug("execute command")
// all permission will be checked later
switch c.CommandName() {
case PingCommand:
c.PingCommand()
case HelpCommand:
c.HelpCommand()
case BlockCommand:
c.BlockCommand()
case WatchCommand:
c.WatchCommand(false)
case UnwatchCommand:
c.WatchCommand(true)
case EnableCommand:
c.EnableCommand(false)
case DisableCommand:
c.EnableCommand(true)
case GrantCommand:
c.GrantCommand()
case LogCommand:
c.LogCommand()
case ListCommand:
c.ListCommand()
case SysinfoCommand:
c.SysinfoCommand()
case ConfigCommand:
c.ConfigCommand()
case WhosyourdaddyCommand:
c.WhosyourdaddyCommand()
case QuitCommand:
c.QuitCommand()
case ModeCommand:
c.ModeCommand()
case GroupRequestCommand:
c.GroupRequestCommand()
case FriendRequestCommand:
c.FriendRequestCommand()
case AdminCommand:
c.AdminCommand()
case SilenceCommand:
c.SilenceCommand()
case NoUpdateCommand:
c.NoUpdateCommand()
case AbnormalConcernCheck:
c.AbnormalConcernCheckCommand()
case CleanConcern:
c.CleanConcernCommand()
default:
if CheckCustomPrivateCommand(c.CommandName()) {
func() {
log := c.DefaultLoggerWithCommand(c.CommandName()).WithField("CustomCommand", true)
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
c.sendChain(
c.templateMsg(
fmt.Sprintf("custom.command.private.%s.tmpl", c.CommandName()),
map[string]interface{}{
"cmd": c.CommandName(),
"args": c.GetArgs(),
"full_args": strings.Join(c.GetArgs(), " "),
},
),
)
}()
} else {
c.textReplyF("阁下似乎输入了一个无法识别的命令,请使用<%v>命令查看帮助。", c.l.CommandShowName(HelpCommand))
log.Debug("no command matched")
}
}
}
func (c *LspPrivateCommand) NoUpdateCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
if !c.l.PermissionStateManager.RequireAny(
permission.AdminRoleRequireOption(c.uin()),
) {
c.noPermission()
return
}
var noUpdateCmd struct {
Delete bool `optional:"" short:"d" help:"取消设置"`
}
_, output := c.parseCommandSyntax(&noUpdateCmd, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
var err error
key := localdb.DDBotNoUpdateKey(c.uin())
if noUpdateCmd.Delete {
_, err = localdb.Delete(key, localdb.IgnoreNotFoundOpt())
if err == nil {
c.textReply("成功 - 您将接收到更新消息")
}
} else {
err = localdb.Set(key, "")
if err == nil {
c.textReply("成功 - 您将不再接受更新消息")
}
}
if err != nil {
c.textReplyF("失败 - %v", err)
}
}
func (c *LspPrivateCommand) AbnormalConcernCheckCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
_, output := c.parseCommandSyntax(&struct{}{}, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
IAbnormalConcernCheck(c.NewMessageContext(log))
}
func (c *LspPrivateCommand) CleanConcernCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
if !c.l.PermissionStateManager.RequireAny(
permission.AdminRoleRequireOption(c.uin()),
) {
c.noPermission()
return
}
var cleanConcernCmd struct {
Abnormal bool `optional:"" help:"清除异常订阅"`
GroupCodes []int64 `optional:"" short:"g" help:"清除指定群的订阅,多个可用英文逗号隔开"`
Site string `optional:"" short:"s" help:"清除指定的网站订阅,默认为全部"`
Type string `optional:"" short:"t" help:"清除指定的订阅类型,默认为全部"`
}
_, output := c.parseCommandSyntax(&cleanConcernCmd, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
ICleanConcern(c.NewMessageContext(log), cleanConcernCmd.Abnormal,
cleanConcernCmd.GroupCodes, cleanConcernCmd.Site, cleanConcernCmd.Type)
}
func (c *LspPrivateCommand) WhosyourdaddyCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
_, output := c.parseCommandSyntax(&struct{}{}, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
if c.l.PermissionStateManager.CheckRole(c.uin(), permission.Admin) {
c.textReply("您已经是管理员了,请不要重复使用此命令。")
return
}
if c.l.PermissionStateManager.CheckNoAdmin() {
if err := c.l.PermissionStateManager.GrantRole(c.uin(), permission.Admin); err != nil {
log.WithField("permission", permission.Admin.String()).
Errorf("GrantRole error %v", err)
c.textReply("失败 - 内部错误")
} else {
log.Info("已配置bot初始管理员,现在可以开始使用bot了,祝你好运")
c.textReply("成功 - 您已成为bot管理员")
}
} else {
log.Debug("someone is trying WhosyourdaddyCommand")
c.textReply("失败 - 该bot不属于你!")
}
}
func (c *LspPrivateCommand) ListCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
var listCmd struct {
Group int64 `optional:"" short:"g" help:"要操作的QQ群号码"`
Site string `optional:"" short:"s" help:"网站参数"`
}
_, output := c.parseCommandSyntax(&listCmd, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
groupCode := listCmd.Group
if err := c.checkGroupCode(groupCode); err != nil {
c.textReply(err.Error())
return
}
log = log.WithFields(localutils.GroupLogFields(groupCode))
IList(c.NewMessageContext(log), groupCode, listCmd.Site)
}
func (c *LspPrivateCommand) ConfigCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
var configCmd struct {
At struct {
Site string `optional:"" short:"s" default:"bilibili" help:"网站参数"`
Id string `arg:"" help:"配置的主播id"`
Action string `arg:"" enum:"add,remove,clear,show" help:"add / remove / clear / show"`
QQ []int64 `arg:"" optional:"" help:"需要@的成员QQ号码"`
} `cmd:"" help:"配置推送时的@人员列表,默认为空" name:"at"`
AtAll struct {
Site string `optional:"" short:"s" default:"bilibili" help:"网站参数"`
Id string `arg:"" help:"配置的主播id"`
Switch string `arg:"" default:"on" enum:"on,off" help:"on / off"`
} `cmd:"" help:"配置推送时@全体成员,默认关闭,需要管理员权限" name:"at_all"`
TitleNotify struct {
Site string `optional:"" short:"s" default:"bilibili" help:"网站参数"`
Id string `arg:"" help:"配置的主播id"`
Switch string `arg:"" default:"off" enum:"on,off" help:"on / off"`
} `cmd:"" help:"配置直播间标题发生变化时是否进行推送,默认不推送" name:"title_notify"`
OfflineNotify struct {
Site string `optional:"" short:"s" default:"bilibili" help:"网站参数"`
Id string `arg:"" help:"配置的主播id"`
Switch string `arg:"" default:"off" enum:"on,off," help:"on / off"`
} `cmd:"" help:"配置下播时是否进行推送,默认不推送" name:"offline_notify"`
Filter struct {
Site string `optional:"" short:"s" default:"bilibili" help:"网站参数"`
Type struct {
Id string `arg:"" help:"配置的主播id"`
Type []string `arg:"" optional:"" help:"指定的种类"`
} `cmd:"" help:"只推送指定种类的动态" name:"type" group:"filter"`
NotType struct {
Id string `arg:"" help:"配置的主播id"`
Type []string `arg:"" optional:"" help:"指定不推送的种类"`
} `cmd:"" help:"不推送指定种类的动态" name:"not_type" group:"filter"`
Text struct {
Id string `arg:"" help:"配置的主播id"`
Keyword []string `arg:"" optional:"" help:"指定的关键字"`
} `cmd:"" help:"当动态内容里出现关键字时进行推送" name:"text" group:"filter"`
Clear struct {
Id string `arg:"" help:"配置的主播id"`
} `cmd:"" help:"清除过滤器" name:"clear" group:"filter"`
Show struct {
Id string `arg:"" help:"配置的主播id"`
} `cmd:"" help:"查看当前过滤器" name:"show" group:"filter"`
} `cmd:"" help:"配置动态过滤器" name:"filter"`
Group int64 `optional:"" short:"g" help:"要操作的QQ群号码"`
}
kongCtx, output := c.parseCommandSyntax(&configCmd, c.CommandName(),
kong.Description("管理BOT的配置,目前支持配置@成员、@全体成员、开启下播推送、开启标题推送、推送过滤"),
)
if output != "" {
c.textReply(output)
}
if c.exit || len(kongCtx.Path) <= 1 {
return
}
groupCode := configCmd.Group
if err := c.checkGroupCode(groupCode); err != nil {
c.textReply(err.Error())
return
}
kongPath := strings.Split(kongCtx.Command(), " ")
cmd := kongPath[0]
log = log.WithFields(localutils.GroupLogFields(groupCode)).WithField("sub_command", cmd)
switch cmd {
case "at":
site, ctype, err := c.ParseRawSiteAndType(configCmd.At.Site, "live")
if err != nil {
log.WithField("site", configCmd.At.Site).Errorf("ParseRawSiteAndType failed %v", err)
c.textSend(fmt.Sprintf("失败 - %v", err.Error()))
return
}
log = log.WithField("site", site).WithField("id", configCmd.At.Id).WithField("action", configCmd.At.Action).WithField("QQ", configCmd.At.QQ)
IConfigAtCmd(c.NewMessageContext(log), groupCode, configCmd.At.Id, site, ctype, configCmd.At.Action, configCmd.At.QQ)
case "at_all":
site, ctype, err := c.ParseRawSiteAndType(configCmd.AtAll.Site, "live")
if err != nil {
log.WithField("site", configCmd.AtAll.Site).Errorf("ParseRawSiteAndType failed %v", err)
c.textSend(fmt.Sprintf("失败 - %v", err.Error()))
return
}
var on = localutils.Switch2Bool(configCmd.AtAll.Switch)
log = log.WithField("site", site).WithField("id", configCmd.AtAll.Id).WithField("on", on)
IConfigAtAllCmd(c.NewMessageContext(log), groupCode, configCmd.AtAll.Id, site, ctype, on)
case "title_notify":
site, ctype, err := c.ParseRawSiteAndType(configCmd.TitleNotify.Site, "live")
if err != nil {
log.WithField("site", configCmd.TitleNotify.Site).Errorf("ParseRawSiteAndType failed %v", err)
c.textSend(fmt.Sprintf("失败 - %v", err.Error()))
return
}
var on = localutils.Switch2Bool(configCmd.TitleNotify.Switch)
log = log.WithField("site", site).WithField("id", configCmd.TitleNotify.Id).WithField("on", on)
IConfigTitleNotifyCmd(c.NewMessageContext(log), groupCode, configCmd.TitleNotify.Id, site, ctype, on)
case "offline_notify":
site, ctype, err := c.ParseRawSiteAndType(configCmd.OfflineNotify.Site, "live")
if err != nil {
log.WithField("site", configCmd.OfflineNotify.Site).Errorf("ParseRawSiteAndType failed %v", err)
c.textSend(fmt.Sprintf("失败 - %v", err.Error()))
return
}
var on = localutils.Switch2Bool(configCmd.OfflineNotify.Switch)
log = log.WithField("site", site).WithField("id", configCmd.OfflineNotify.Id).WithField("on", on)
IConfigOfflineNotifyCmd(c.NewMessageContext(log), groupCode, configCmd.OfflineNotify.Id, site, ctype, on)
case "filter":
filterCmd := kongPath[1]
site, ctype, err := c.ParseRawSiteAndType(configCmd.Filter.Site, "news")
if err != nil {
log.WithField("site", configCmd.Filter.Site).Errorf("ParseRawSiteAndType failed %v", err)
c.textSend(fmt.Sprintf("失败 - %v", err.Error()))
return
}
switch filterCmd {
case "type":
IConfigFilterCmdType(c.NewMessageContext(log), groupCode, configCmd.Filter.Type.Id, site, ctype, configCmd.Filter.Type.Type)
case "not_type":
IConfigFilterCmdNotType(c.NewMessageContext(log), groupCode, configCmd.Filter.NotType.Id, site, ctype, configCmd.Filter.NotType.Type)
case "text":
IConfigFilterCmdText(c.NewMessageContext(log), groupCode, configCmd.Filter.Text.Id, site, ctype, configCmd.Filter.Text.Keyword)
case "clear":
IConfigFilterCmdClear(c.NewMessageContext(log), groupCode, configCmd.Filter.Clear.Id, site, ctype)
case "show":
IConfigFilterCmdShow(c.NewMessageContext(log), groupCode, configCmd.Filter.Show.Id, site, ctype)
default:
log.WithField("filter_cmd", filterCmd).Errorf("unknown filter command")
c.textSend("未知的filter子命令")
}
default:
c.textSend("暂未支持,你可以催作者GKD")
}
}
func (c *LspPrivateCommand) WatchCommand(remove bool) {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
var (
site string
watchType concern_type.Type
err error
)
var watchCmd struct {
Site string `optional:"" short:"s" default:"bilibili" help:"网站参数"`
Type string `optional:"" short:"t" default:"" help:"类型参数"`
Group int64 `optional:"" short:"g" help:"要操作的QQ群号码"`
Id string `arg:""`
}
_, output := c.parseCommandSyntax(&watchCmd, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
site, watchType, err = c.ParseRawSiteAndType(watchCmd.Site, watchCmd.Type)
if err != nil {
log = log.WithField("args", c.GetArgs())
log.Errorf("parse raw concern failed %v", err)
c.textReply(fmt.Sprintf("参数错误 - %v", err))
return
}
log = log.WithField("site", site).WithField("type", watchType)
id := watchCmd.Id
groupCode := watchCmd.Group
if err := c.checkGroupCode(groupCode); err != nil {
c.textReply(err.Error())
return
}
log = log.WithFields(localutils.GroupLogFields(groupCode))
IWatch(c.NewMessageContext(log), groupCode, id, site, watchType, remove)
}
func (c *LspPrivateCommand) EnableCommand(disable bool) {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
var enableCmd struct {
Group int64 `optional:"" short:"g" help:"要操作的QQ群号码"`
Command string `arg:"" optional:"" help:"命令名"`
Global bool `optional:"" help:"系统级操作,对所有群生效"`
}
_, output := c.parseCommandSyntax(&enableCmd, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
if len(enableCmd.Command) == 0 {
c.textReply("失败 - 没有指定要操作的命令名")
log.Errorf("empty command")
return
}
command := CombineCommand(enableCmd.Command)
if !CheckOperateableCommand(command) {
log.Errorf("unknown command")
c.textReply("失败 - 命令名非法")
return
}
if enableCmd.Global {
if !c.l.PermissionStateManager.CheckRole(c.uin(), permission.Admin) {
c.noPermission()
return
}
if enableCmd.Group != 0 {
c.textReply(fmt.Sprintf("注意:--global模式,忽略参数-g %v", enableCmd.Group))
}
var err error
if disable {
err = c.l.PermissionStateManager.GlobalDisableGroupCommand(command)
} else {
err = c.l.PermissionStateManager.GlobalEnableGroupCommand(command)
}
if err == nil {
c.textReply("成功")
} else if err == permission.ErrPermissionExist {
if disable {
c.textReply("失败 - 该命令已禁用")
} else {
c.textReply("失败 - 该命令已启用")
}
}
} else {
if c.l.PermissionStateManager.CheckGlobalCommandDisabled(command) {
c.globalDisabledReply()
return
}
groupCode := enableCmd.Group
if err := c.checkGroupCode(groupCode); err != nil {
c.textReply(err.Error())
return
}
log = log.WithFields(localutils.GroupLogFields(groupCode)).
WithField("global", enableCmd.Global).
WithField("targetCommand", enableCmd.Command)
IEnable(c.NewMessageContext(log), groupCode, command, disable)
}
}
func (c *LspPrivateCommand) GrantCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
var grantCmd struct {
Group int64 `optional:"" short:"g" help:"要操作的QQ群号码"`
Command string `required:"" short:"c" xor:"1" help:"命令名"`
Role string `required:"" short:"r" xor:"1" enum:"Admin,GroupAdmin" help:"Admin / GroupAdmin"`
Delete bool `short:"d" help:"删除模式,执行删除权限操作"`
Target int64 `arg:"" help:"目标qq号"`
}
_, output := c.parseCommandSyntax(&grantCmd, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
groupCode := grantCmd.Group
grantFrom := c.uin()
grantTo := grantCmd.Target
if grantCmd.Command == "" && grantCmd.Role == "" {
log.Errorf("command and role both empty")
c.textReply("参数错误 - 必须指定-c / -r")
return
}
del := grantCmd.Delete
log = log.WithField("grantFrom", grantFrom).WithField("grantTo", grantTo).WithField("delete", del)
if grantCmd.Command != "" {
if err := c.checkGroupCode(groupCode); err != nil {
c.textReply(err.Error())
return
}
log = log.WithFields(localutils.GroupLogFields(groupCode))
IGrantCmd(c.NewMessageContext(log), groupCode, grantCmd.Command, grantTo, del)
} else if grantCmd.Role != "" {
role := permission.NewRoleFromString(grantCmd.Role)
if role != permission.Admin {
if err := c.checkGroupCode(groupCode); err != nil {
c.textReply(err.Error())
return
}
}
log = log.WithFields(localutils.GroupLogFields(groupCode))
IGrantRole(c.NewMessageContext(log), groupCode, role, grantTo, del)
}
}
func (c *LspPrivateCommand) BlockCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
if !c.l.PermissionStateManager.RequireAny(
permission.AdminRoleRequireOption(c.uin()),
) {
c.noPermission()
return
}
var blockCmd struct {
Uin int64 `arg:"" required:"" help:"要block的qq号或者qq群"`
Days int `optional:"" help:"要block的天数,默认是永久"`
Delete bool `optional:"" short:"d" help:"取消block"`
}
_, output := c.parseCommandSyntax(&blockCmd, c.CommandName())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
if blockCmd.Uin == c.uin() {
log.Errorf("can not block yourself")
c.textReply("失败 - 不能block自己")
return
}
log = log.WithField("TargetUin", blockCmd.Uin).
WithField("Days", blockCmd.Days).
WithField("Delete", blockCmd.Delete)
var name string
if fi := localutils.GetBot().FindFriend(blockCmd.Uin); fi != nil {
name = fi.Nickname
log = log.WithField("TargetName", name)
}
if gi := localutils.GetBot().FindGroup(blockCmd.Uin); gi != nil {
name = gi.Name
log = log.WithField("TargetGroupName", name)
}
if name == "" {
name = "未知目标"
}
if !blockCmd.Delete {
if err := c.l.PermissionStateManager.AddBlockList(blockCmd.Uin, time.Duration(blockCmd.Days)*time.Hour*24); err == nil {
log.Info("blocked")
c.textReplyF("成功 - %v", name)
} else if err == localdb.ErrKeyExist {
log.Errorf("block failed - duplicate")
c.textReply("失败 - 已经block过了")
} else {
log.Errorf("block failed err %v", err)
c.textReply("失败 - 内部错误")
}
} else {
if err := c.l.PermissionStateManager.DeleteBlockList(blockCmd.Uin); err == nil {
log.Info("unblocked")
c.textReplyF("成功 - %v", name)
} else if localdb.IsNotFound(err) {
log.Errorf("unblock failed - not exist")
c.textReply("失败 - 该目标未被block")
} else {
log.Errorf("unblock failed err %v", err)
c.textReply("失败 - 内部错误")
}
}
}
func (c *LspPrivateCommand) LogCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
if !c.l.PermissionStateManager.RequireAny(
permission.AdminRoleRequireOption(c.uin()),
) {
c.noPermission()
return
}
var logCmd struct {
N int `arg:"" optional:"" help:"要查询的行数"`
Date time.Time `optional:"" short:"d" format:"2006-01-02" help:"要查询的日期,需要日志保留才能生效"`
Keyword string `optional:"" short:"k" help:"要包含的关键字"`
}
_, output := c.parseCommandSyntax(&logCmd, c.CommandName())
if output != "" {
c.textSend(output)
}
if c.exit {
return
}
if logCmd.N == 0 {
logCmd.N = 10
}
if logCmd.Date.IsZero() {
logCmd.Date = time.Now()
}
logName := fmt.Sprintf("%v.log", logCmd.Date.Format("2006-01-02"))
b, err := os.ReadFile("logs/" + logName)
if err != nil {
c.textSend(fmt.Sprintf("失败 - %v", err))
return
}
var lines []string
sc := bufio.NewScanner(bytes.NewReader(b))
for sc.Scan() {
lines = append(lines, sc.Text())
}
if len(logCmd.Keyword) != 0 {
var filteredLines []string
for _, line := range lines {
if strings.Contains(line, logCmd.Keyword) {
filteredLines = append(filteredLines, line)
}
}
lines = filteredLines
}
if logCmd.N > len(lines) {
logCmd.N = len(lines)
}
lines = lines[len(lines)-logCmd.N:]
if len(lines) == 0 {
c.textSend("无结果")
} else {
c.textSend(strings.Join(lines, "\n"))
}
}
func (c *LspPrivateCommand) QuitCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
if !c.l.PermissionStateManager.RequireAny(
permission.AdminRoleRequireOption(c.uin()),
) {
c.noPermission()
return
}
var quitCmd struct {
GroupCode int64 `arg:"" optional:"" help:"要退出的群号"`
Force bool `optional:"" short:"f" help:"强制清除"`
}
_, output := c.parseCommandSyntax(&quitCmd, c.CommandName())
if output != "" {
c.textSend(output)
}
if c.exit {
return
}
if quitCmd.GroupCode == 0 {
log.Errorf("GroupCode is 0")
c.textSend("没有指定群号,请输入群号")
return
}
log = log.WithField("TargetGroupCode", quitCmd.GroupCode).WithField("Force", quitCmd.Force)
gi := c.bot.FindGroup(quitCmd.GroupCode)
var displayName string
if gi == nil {
displayName = strconv.FormatInt(quitCmd.GroupCode, 10)
} else {
displayName = gi.Name
}
if gi == nil {
if quitCmd.Force {
log.Debugf("没有找到该QQ群,force已启用")
c.textSend("没有找到该QQ群,请确认bot在群内,但由于指定了-f参数,将强制清除bot在该群的数据")
} else {
log.Errorf("没有找到该QQ群,force已禁用")
c.textSend("没有找到该QQ群,请确认bot在群内,如果要强制清除bot在该群内的数据,请指定-f参数")
return
}
} else {
gi.Quit()
log.Debugf("已退出群【%v】", displayName)
c.textSend(fmt.Sprintf("已退出群【%v】", displayName))
}
c.l.RemoveAllByGroup(quitCmd.GroupCode)
log.Debugf("已清除群【%v】的数据", displayName)
c.textSend(fmt.Sprintf("已清除群【%v】的数据", displayName))
}
func (c *LspPrivateCommand) ModeCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
if !c.l.PermissionStateManager.RequireAny(
permission.AdminRoleRequireOption(c.uin()),
) {
c.noPermission()
return
}
var modeCmd struct {
Mode string `arg:"" optional:"" help:"指定切换模式,支持<公开> <私人> <审核>,默认为公开"`
}
_, output := c.parseCommandSyntax(&modeCmd, c.CommandName(), kong.Description("切换BOT模式"), kong.UsageOnError())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
if modeCmd.Mode == "" {
mode := c.l.LspStateManager.GetCurrentMode()
log.Infof("当前Mode为%v", mode)
switch c.l.LspStateManager.GetCurrentMode() {
case PublicMode:
c.textReply("当前模式为公开")
case PrivateMode:
c.textReply("当前模式为私人")
case ProtectMode:
c.textReply("当前模式为审核")
}
return
}
log = log.WithField("Mode", modeCmd.Mode)
var err error
switch modeCmd.Mode {
case "公开":
err = c.l.LspStateManager.SetMode(PublicMode)
case "私人":
err = c.l.LspStateManager.SetMode(PrivateMode)
case "审核":
err = c.l.LspStateManager.SetMode(ProtectMode)
default:
log.Errorf("未知的模式")
c.textSend(fmt.Sprintf("未知的模式【%v】,仅支持<公开> <私人> <审核>,请查看命令文档", modeCmd.Mode))
return
}
if err != nil {
log.Errorf("切换模式失败 %v", err)
c.textReply(fmt.Sprintf("切换模式失败 - %v", err))
} else {
log.Infof("切换到%v模式", modeCmd.Mode)
c.textReply(fmt.Sprintf("成功 - 切换到%v模式", modeCmd.Mode))
}
}
func (c *LspPrivateCommand) GroupRequestCommand() {
log := c.DefaultLoggerWithCommand(c.CommandName())
log.Infof("run %v command", c.CommandName())
defer func() { log.Infof("%v command end", c.CommandName()) }()
if !c.l.PermissionStateManager.RequireAny(
permission.AdminRoleRequireOption(c.uin()),
) {
c.noPermission()
return
}
var groupRequestCmd struct {
RequestId int64 `arg:"" optional:"" help:"要处理的请求的RequestId"`
Reject bool `optional:"" short:"r" help:"拒绝请求"`
All bool `optional:"" short:"a" help:"处理全部"`
Message []string `arg:"" optional:"" help:"拒绝理由"`
}
_, output := c.parseCommandSyntax(&groupRequestCmd, c.CommandName(), kong.Description("处理群邀请"), kong.UsageOnError())
if output != "" {
c.textReply(output)
}
if c.exit {
return
}
rmsg := strings.Join(groupRequestCmd.Message, " ")
log = log.WithFields(logrus.Fields{
"Requestid": groupRequestCmd.RequestId,
"Reject": groupRequestCmd.Reject,
"All": groupRequestCmd.All,
"Message": rmsg,
})
if groupRequestCmd.RequestId == 0 {
requests, err := c.l.LspStateManager.ListGroupInvitedRequest()
if err != nil {
log.Errorf("ListGroupInvitedRequest error - %v", err)
c.textReply(fmt.Sprintf("失败 - %v", err))
return
}
if len(requests) == 0 {
log.Infof("没有查询到加群邀请")
c.textReply("没有查询到加群邀请")
return
}
if groupRequestCmd.Reject {
// 拒绝全部?
if !groupRequestCmd.All {
log.Info("拒绝全部加群邀请需要确认")
c.textReply(fmt.Sprintf("您似乎想要拒绝全部%v个加群邀请,如果确定想这样做,请输入:\n%v --all %v", len(requests), c.GetCmd(), strings.Join(c.GetArgs(), " ")))
return
}
// 拒绝全部!
log.Info("确认拒绝全部加群邀请")
for _, req := range requests {
log.Debugf("正在拒绝%v(%v)的加群%v(%v)邀请", req.InvitorNick, req.InvitorUin, req.GroupName, req.GroupCode)
c.bot.SolveGroupJoinRequest(req, false, false, rmsg)
if err := c.l.LspStateManager.DeleteGroupInvitedRequest(req.RequestId); err != nil {
log.Errorf("DeleteGroupInvitedRequest error %v", err)
}
}
log.Infof("已拒绝%v个加群邀请", len(requests))
c.textReply(fmt.Sprintf("成功 - 已拒绝全部%v个加群邀请", len(requests)))
return
}
if groupRequestCmd.All {
// 接受全部!
for _, req := range requests {
log.Infof("正在接受%v(%v)的加群%v(%v)邀请", req.InvitorNick, req.InvitorUin, req.GroupName, req.GroupCode)
c.bot.SolveGroupJoinRequest(req, true, false, "")
if err := c.l.LspStateManager.DeleteGroupInvitedRequest(req.RequestId); err != nil {
log.Errorf("DeleteGroupInvitedRequest error %v", err)
}
if err := c.l.PermissionStateManager.GrantGroupRole(req.GroupCode, req.InvitorUin, permission.GroupAdmin); err != nil {
log.Errorf("设置群管理员权限失败 - %v", err)
}
if err := c.l.PermissionStateManager.DeleteBlockList(req.GroupCode); err != nil {
log.Errorf("DeleteBlockList error %v", err)
}
}
log.Infof("已接受%v个加群邀请", len(requests))
c.textReply(fmt.Sprintf("成功 - 已接受全部%v个加群邀请", len(requests)))
return
}
// 展示加群邀请
var sb strings.Builder
for _, req := range requests {
sb.WriteString(fmt.Sprintf("ID:%v %v(%v) 邀请加入群 %v(%v)\n", req.RequestId, req.InvitorNick, req.InvitorUin, req.GroupName, req.GroupCode))
}
log.Infof("查询到%v个加群邀请", len(requests))
c.textReply(sb.String())
} else {
request, err := c.l.LspStateManager.GetGroupInvitedRequest(groupRequestCmd.RequestId)
if localdb.IsNotFound(err) {
log.Errorf("处理加群邀请失败 - 未找到该邀请")
c.textReply(fmt.Sprintf("失败 - 未找到该邀请【%v】", groupRequestCmd.RequestId))
return
} else if err != nil {
log.Errorf("GetGroupInvitedRequest error %v", err)
c.textReply(fmt.Sprintf("失败 - 内部错误"))
return
}
log := log.WithFields(logrus.Fields{
"GroupName": request.GroupName,
"GroupCode": request.GroupCode,
"InvitorUin": request.InvitorUin,
"InvitorNick": request.InvitorNick,
})
if groupRequestCmd.Reject {
c.bot.SolveGroupJoinRequest(request, false, false, rmsg)
log.Info("拒绝加群邀请成功")
c.textReply(fmt.Sprintf("成功- 已拒绝 %v(%v) 邀请加群 %v(%v)", request.InvitorNick, request.InvitorUin, request.GroupName, request.GroupCode))
} else {
c.bot.SolveGroupJoinRequest(request, true, false, "")
if err := c.l.PermissionStateManager.GrantGroupRole(request.GroupCode, request.InvitorUin, permission.GroupAdmin); err != nil {
log.Errorf("设置群管理员权限失败 - %v", err)
}
if err := c.l.PermissionStateManager.DeleteBlockList(request.GroupCode); err != nil {
log.Errorf("DeleteBlockList error %v", err)
}
log.Info("接受加群请求成功")
c.textReply(fmt.Sprintf("成功 - 已接受 %v(%v) 邀请加群 %v(%v)", request.InvitorNick, request.InvitorUin, request.GroupName, request.GroupCode))