-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1028 lines (856 loc) · 47 KB
/
Copy pathmain.py
File metadata and controls
1028 lines (856 loc) · 47 KB
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
import asyncio
import random
import secrets # 新增:密码学安全的随机数生成
import string
import traceback
import hashlib
import hmac
from datetime import datetime, timedelta
from typing import Dict, Optional, List, Any, Tuple, Set
from pathlib import Path
from dataclasses import dataclass, asdict, field
from enum import Enum
import json
import io
import numpy as np
from PIL import Image as PILImage, ImageDraw, ImageFont, ImageFilter
import astrbot.api.star as star
import astrbot.api.event.filter as filter
from astrbot.api.event import AstrMessageEvent, MessageEventResult, MessageChain
from astrbot.api.message_components import Plain, Image, At
from astrbot.api import logger
from astrbot.core.star.star_tools import StarTools
# 导入模块化的组件
from .core import (
VerificationStatus,
VerificationData,
MutedUserData,
GroupConfig,
PluginConfig,
LOCK_TIMEOUT_SECONDS,
OPERATION_TIMEOUT_RECALL,
OPERATION_TIMEOUT_SEND,
OPERATION_TIMEOUT_VERIFICATION,
)
from .managers import (
VerificationManager,
MuteManager,
DataPersistence,
StatisticsCollector,
GroupConfigManager,
BlacklistManager,
CleanupManager,
)
from .managers.blacklist import BlacklistUser
from .utils import (
ConcurrencyManager,
PlatformHelper,
ContentFilter,
HelpTextManager,
ConfigCacheManager,
ImageOptimizationManager,
ConfigValidator,
)
from .handlers import (
ConfigHandler,
MessageService,
VerificationService,
TimeoutService,
TestService,
DiagnosticService,
NewMemberHandler,
CommandHandler,
BlacklistHandler,
AutoEnableHandler,
NotifyService,
NotifyCommandHandler,
QuickApproveHandler,
)
# === 以下为插件主类 ===
@star.register("newbie_verification_2", "Soulter", "新人入群验证系统2-仅群1062786434", "3.0.0")
class Main(star.Star):
"""新人入群验证系统"""
def __init__(self, context: star.Context) -> None:
super().__init__(context)
# 初始化路径
plugin_dir = Path(__file__).parent
# 初始化数据持久化
self.persistence = DataPersistence(plugin_dir)
# 初始化配置
self.config: Optional[PluginConfig] = None
# 初始化管理器
self.verification_mgr: Optional[VerificationManager] = None
self.mute_mgr = MuteManager()
self.stats = StatisticsCollector()
self.group_config_mgr = GroupConfigManager(self)
self.blacklist_mgr = BlacklistManager()
self.cleanup_mgr: Optional[CleanupManager] = None
# 待验证用户数据
self.newbie_verification: Dict[str, VerificationData] = {}
# 待处理的放行码(验证失败后保留的放行码,供管理员拉黑使用)
self.pending_bypass_codes: Dict[str, Dict[str, Any]] = {}
# 管理员放行日志(保留30天)
self.admin_bypass_logs: Dict[str, Dict[str, Any]] = {}
# 待撤回的欢迎消息列表
self.pending_welcome_recalls: Dict[str, Dict[str, Any]] = {}
# 并发控制
self._verification_lock = asyncio.Lock()
self._data_save_lock = asyncio.Lock()
# 初始化工具类(在handlers/services之前)
self.concurrency_mgr = ConcurrencyManager(self)
self.platform_helper = PlatformHelper(self)
self.content_filter = ContentFilter(self)
self.help_text_mgr = HelpTextManager(self)
# 新增优化组件(占位符,在_initialize中初始化)
self.config_cache_mgr: Optional[ConfigCacheManager] = None
self.image_optimization_mgr: Optional[ImageOptimizationManager] = None
# 服务组件占位符(在 _initialize 中赋值)
self.message_service: Optional[MessageService] = None
self.verification_service: Optional[VerificationService] = None
self.timeout_service: Optional[TimeoutService] = None
self.test_service: Optional[TestService] = None
self.diagnostic_service: Optional[DiagnosticService] = None
self.new_member_handler: Optional[NewMemberHandler] = None
self.command_handler: Optional[CommandHandler] = None
self.blacklist_handler: Optional[BlacklistHandler] = None
self.auto_enable_handler: Optional[AutoEnableHandler] = None
self.notify_service: Optional[NotifyService] = None
self.notify_handler: Optional[NotifyCommandHandler] = None
self.quick_approve_handler: Optional[QuickApproveHandler] = None
# 后台任务
self._timeout_check_task: Optional[asyncio.Task] = None
self._auto_save_task: Optional[asyncio.Task] = None
self._lock_cleanup_task: Optional[asyncio.Task] = None
self._bypass_code_cleanup_task: Optional[asyncio.Task] = None
self._background_tasks: Set[asyncio.Task] = set()
self._is_running = False
# 命令处理器(在 _initialize 中赋值)
self.config_handler = None
# 启动初始化任务
asyncio.create_task(self._initialize())
async def _initialize(self):
"""异步初始化"""
try:
logger.info(" [NewbieVerification] Starting initialization...")
# 加载配置
self.config = await self.persistence.load_config()
# 验证配置文件
config_dict = self.config.to_dict()
is_valid, errors = ConfigValidator.validate_config(config_dict)
if not is_valid:
logger.warning(f"[NewbieVerification] 配置文件存在问题,但将继续运行: {errors}")
else:
logger.info("[NewbieVerification] 配置文件验证通过")
# 获取配置优化建议
recommendations = ConfigValidator.get_config_recommendations(config_dict)
if recommendations:
logger.info(f"[NewbieVerification] 配置优化建议: {recommendations}")
# 初始化优化组件
self.config_cache_mgr = ConfigCacheManager(self)
self.image_optimization_mgr = ImageOptimizationManager(self)
self.image_optimization_mgr.initialize()
# 初始化验证管理器
self.verification_mgr = VerificationManager(self.config)
# 加载持久化数据
verification_data = await self.persistence.load_verification_data()
self.newbie_verification = verification_data
muted_data = await self.persistence.load_muted_users()
self.mute_mgr.long_muted_users = muted_data
stats_data = await self.persistence.load_statistics()
if stats_data:
self.stats.load_stats(stats_data)
# 初始化黑名单管理器
self.blacklist_mgr.initialize(self.persistence.plugin_dir)
blacklist_data = await self.persistence.load_blacklist()
if blacklist_data:
self.blacklist_mgr.blacklist_data = {
user_id: BlacklistUser.from_dict(user_data)
for user_id, user_data in blacklist_data.items()
}
# 加载pending_bypass_codes数据
pending_codes = await self.persistence.load_pending_bypass_codes()
if pending_codes:
self.pending_bypass_codes = pending_codes
# 加载管理员放行日志
bypass_logs = await self.persistence.load_admin_bypass_logs()
if bypass_logs:
self.admin_bypass_logs = bypass_logs
# 加载待撤回的欢迎消息列表
welcome_recalls = await self.persistence.load_pending_welcome_recalls()
if welcome_recalls:
self.pending_welcome_recalls = welcome_recalls
# 标记为运行中
self._is_running = True
# 启动后台任务
self._timeout_check_task = self._register_background_task(
asyncio.create_task(self._check_timeout_loop())
)
self._auto_save_task = self._register_background_task(
asyncio.create_task(self._auto_save_loop())
)
self._lock_cleanup_task = self._register_background_task(
asyncio.create_task(self._clean_dead_locks_loop())
)
self._bypass_code_cleanup_task = self._register_background_task(
asyncio.create_task(self._bypass_code_cleanup_loop())
)
# 初始化命令处理器(模块化架构)
self.config_handler = ConfigHandler(self)
self.message_service = MessageService(self)
self.verification_service = VerificationService(self)
self.timeout_service = TimeoutService(self)
self.test_service = TestService(self)
self.diagnostic_service = DiagnosticService(self)
self.new_member_handler = NewMemberHandler(self)
self.command_handler = CommandHandler(self)
self.blacklist_handler = BlacklistHandler(self)
self.blacklist_handler.initialize()
self.auto_enable_handler = AutoEnableHandler(self)
self.notify_service = NotifyService(self)
self.notify_handler = NotifyCommandHandler(self)
self.quick_approve_handler = QuickApproveHandler(self)
# 初始化清理管理器
self.cleanup_mgr = CleanupManager(self)
logger.info(f" [NewbieVerification] Plugin initialized successfully")
logger.info(f" [NewbieVerification] Loaded {len(self.config.enabled_groups)} enabled group(s)")
logger.info(f" [NewbieVerification] {len(self.newbie_verification)} pending verifications")
logger.info(f" [NewbieVerification] {len(self.mute_mgr.long_muted_users)} muted users")
except Exception as e:
logger.error(f" [NewbieVerification] Initialization failed: {e}", exc_info=True)
def _register_background_task(self, task: asyncio.Task) -> asyncio.Task:
"""注册后台任务,便于统一管理生命周期"""
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
return task
async def _check_timeout_loop(self):
"""定时检查超时任务循环"""
logger.info(" [NewbieVerification] Timeout check loop started")
while self._is_running:
try:
await asyncio.sleep(self.config.check_interval_seconds)
await self.timeout_service.check_timeouts()
except asyncio.CancelledError:
logger.info(" [NewbieVerification] Timeout check loop cancelled")
break
except Exception as e:
logger.error(f" [NewbieVerification] Error in timeout check loop: {e}", exc_info=True)
async def _auto_save_loop(self):
"""自动保存数据循环"""
logger.info(" [NewbieVerification] Auto-save loop started")
while self._is_running:
try:
# 使用配置中的自动保存间隔
interval = self.config.auto_save_interval_seconds if self.config else 300
await asyncio.sleep(interval)
await self._save_all_data()
except asyncio.CancelledError:
logger.info(" [NewbieVerification] Auto-save loop cancelled")
break
except Exception as e:
logger.error(f" [NewbieVerification] Error in auto-save loop: {e}", exc_info=True)
async def _clean_dead_locks_loop(self):
"""定期清理僵死锁(卡死恢复系统)"""
logger.info(" [NewbieVerification] Lock cleanup loop started")
while self._is_running:
try:
# 使用配置中的锁清理间隔
interval = self.config.lock_cleanup_interval_seconds if self.config else 30
await asyncio.sleep(interval)
await self.concurrency_mgr.clean_dead_locks()
except asyncio.CancelledError:
logger.info(" [NewbieVerification] Lock cleanup loop cancelled")
break
except Exception as e:
logger.error(f" [NewbieVerification] Error in lock cleanup loop: {e}", exc_info=True)
async def _bypass_code_cleanup_loop(self):
"""定期检查并撤回过期的放行码和欢迎消息,清理过期日志"""
logger.info(" [NewbieVerification] Bypass code cleanup loop started")
while self._is_running:
try:
# 使用配置中的放行码清理间隔
interval = self.config.bypass_code_cleanup_interval_seconds if self.config else 60
await asyncio.sleep(interval)
await self.cleanup_mgr.check_expired_bypass_codes()
await self.cleanup_mgr.check_expired_welcome_messages()
await self.cleanup_mgr.clean_expired_logs()
except asyncio.CancelledError:
logger.info(" [NewbieVerification] Bypass code cleanup loop cancelled")
break
except Exception as e:
logger.error(f" [NewbieVerification] Error in bypass code cleanup loop: {e}", exc_info=True)
async def _save_all_data(self):
"""保存所有数据"""
async with self._data_save_lock:
try:
if self.config:
await self.persistence.save_config(self.config)
await self.persistence.save_verification_data(self.newbie_verification)
await self.persistence.save_muted_users(self.mute_mgr.long_muted_users)
await self.persistence.save_statistics(self.stats.to_dict())
# 保存黑名单数据(即使为空也要保存,确保能正确清空黑名单)
if self.blacklist_mgr:
blacklist_dict = {
user_id: user_data.to_dict()
for user_id, user_data in self.blacklist_mgr.blacklist_data.items()
}
await self.persistence.save_blacklist(blacklist_dict)
# 保存pending_bypass_codes数据(即使为空也要保存)
await self.persistence.save_pending_bypass_codes(self.pending_bypass_codes)
# 保存管理员放行日志(即使为空也要保存)
await self.persistence.save_admin_bypass_logs(self.admin_bypass_logs)
# 保存待撤回的欢迎消息列表(即使为空也要保存)
await self.persistence.save_pending_welcome_recalls(self.pending_welcome_recalls)
logger.debug("[NewbieVerification] All data saved successfully")
except Exception as e:
logger.error(f"[NewbieVerification] Failed to save data: {e}", exc_info=True)
def _get_group_config(self, group_id: str) -> GroupConfig:
return self.group_config_mgr.get_group_config(group_id)
def _get_group_timeout_hours(self, group_id: str) -> float:
return self.group_config_mgr.get_group_timeout_hours(group_id)
def _get_group_max_errors(self, group_id: str) -> int:
return self.group_config_mgr.get_group_max_errors(group_id)
def _get_group_regenerate_count(self, group_id: str) -> int:
return self.group_config_mgr.get_group_regenerate_count(group_id)
def _get_group_reminder_interval_hours(self, group_id: str) -> float:
return self.group_config_mgr.get_group_reminder_interval_hours(group_id)
def _get_effective_max_errors(self, group_cfg: GroupConfig, default_max_errors: int) -> int:
return self.group_config_mgr.get_effective_max_errors(group_cfg, default_max_errors)
async def handle_new_member(self, group_id: str, user_id: str, nickname: str,
platform: str = "aiocqhttp"):
"""处理新人入群"""
if not self.new_member_handler:
logger.warning("[NewbieVerification] 新人处理服务未就绪,跳过处理")
return
await self.new_member_handler.handle_new_member(group_id, user_id, nickname, platform)
@filter.permission_type(filter.PermissionType.ADMIN)
@filter.command("verify2help")
async def newbie_verification_help(self, event: AstrMessageEvent):
"""显示新人验证系统帮助(需要wl/op权限)"""
if not self.config:
return MessageEventResult().message(" 系统正在初始化,请稍后再试")
if not self.message_service:
logger.debug("[NewbieVerification] 消息服务未就绪,无法发送帮助信息")
return MessageEventResult().message(" 系统正在初始化,请稍后再试")
help_text = self.help_text_mgr.build_admin_help_text()
# 获取用户ID和平台
user_id = str(event.get_sender_id())
platform = self.platform_helper.detect_platform(event)
# 私聊发送完整帮助
try:
await self.message_service.send_private_message(user_id, help_text.strip(), platform=platform)
# 群聊只显示简短提示
if event.message_obj.type.value == "GroupMessage":
return MessageEventResult().message(" 系统帮助已通过私聊发送,请查看私信")
else:
return MessageEventResult()
except Exception as e:
logger.error(f"[NewbieVerification] 发送私聊帮助失败: {e}")
return MessageEventResult().message(" 发送私聊消息失败,请确保已添加机器人好友")
@filter.command("verify2")
async def verify_command(self, event: AstrMessageEvent):
"""新人验证系统命令 - 支持权限分级处理"""
if not self.command_handler:
logger.debug("[NewbieVerification] 命令处理器未就绪,忽略命令")
return MessageEventResult().message(" 系统正在初始化,请稍后再试")
# 权限检查:OP/WL 或 群主/管理员
user_id = str(event.get_sender_id())
platform = self.platform_helper.detect_platform(event)
# 检查全局权限(OP/WL)
is_global_admin = self._check_global_permission(event)
# 检查群内权限(群主/管理员)
is_group_admin = False
is_group_message = event.message_obj.type.value == "GroupMessage"
if is_group_message:
group_id = str(event.get_group_id())
is_group_admin = await self.platform_helper.is_group_admin_or_owner(event, user_id, group_id, platform)
# 判断权限
has_permission = is_global_admin or is_group_admin
if not has_permission:
return MessageEventResult().message(
" 权限不足\n"
" 需要以下权限之一:\n"
" • 全局管理员(OP/WL)- 可使用所有功能\n"
" • 群主/管理员 - 可使用本群的启用/禁用功能"
)
# 委托给 CommandHandler 处理,传递权限信息
return await self.command_handler.handle(event, is_global_admin, is_group_admin)
@filter.permission_type(filter.PermissionType.ADMIN)
@filter.command("verify2diag")
async def verify_diag_command(self, event: AstrMessageEvent):
"""验证系统诊断命令(需要wl/op权限)"""
if not self.config:
return MessageEventResult().message(" 系统正在初始化,请稍后再试")
if not self.diagnostic_service:
logger.debug("[NewbieVerification] 诊断服务未就绪,忽略诊断命令")
return MessageEventResult().message(" 系统正在初始化,请稍后再试")
# 检查是否有 testfont 子命令
args = event.get_message_str().split()
if len(args) >= 2 and args[1] == "testfont":
return await self.diagnostic_service.handle_test_font(event)
# 委托给DiagnosticService处理
return await self.diagnostic_service.handle_diag(event)
@filter.command("verify2config")
async def verify_config_command(self, event: AstrMessageEvent):
"""验证系统配置命令 - 支持权限分级处理和消息自动撤回"""
if not self.config:
return MessageEventResult().message(" 系统正在初始化,请稍后再试")
# 防御性检查:确保 config_handler 已初始化
if not hasattr(self, 'config_handler') or self.config_handler is None:
return MessageEventResult().message(" 系统正在初始化,请稍后再试")
# 权限检查:OP/WL 或 群主/管理员
user_id = str(event.get_sender_id())
platform = self.platform_helper.detect_platform(event)
# 检查全局权限(OP/WL)
is_global_admin = self._check_global_permission(event)
# 检查群内权限(群主/管理员)
is_group_admin = False
is_group_message = event.message_obj.type.value == "GroupMessage"
group_id = None
if is_group_message:
group_id = str(event.get_group_id())
is_group_admin = await self.platform_helper.is_group_admin_or_owner(event, user_id, group_id, platform)
# 获取用户发送的消息ID(用于后续撤回)
user_msg_id = None
if is_group_message:
try:
raw_message = getattr(event, 'message_obj', None)
if raw_message and hasattr(raw_message, 'raw_message'):
user_msg_id = raw_message.raw_message.get('message_id')
if user_msg_id:
user_msg_id = self.message_service.normalize_message_id(user_msg_id)
logger.debug(f"[NewbieVerification] 获取到用户配置消息ID: {user_msg_id}")
except Exception as e:
logger.warning(f"[NewbieVerification] 无法获取用户消息ID: {e}")
# 判断权限类型
has_permission = is_global_admin or is_group_admin
if not has_permission:
# 无权限:立即撤回用户消息并发送权限不足提示
permission_denied_msg = (
" 权限不足\n"
" 需要以下权限之一:\n"
" • 全局管理员(OP/WL)- 可使用所有配置功能\n"
" • 群主/管理员 - 可使用群级配置功能"
)
if is_group_message:
# 立即撤回用户消息
if user_msg_id:
asyncio.create_task(self._recall_user_config_message(user_msg_id, platform))
# 发送权限不足提示并启动撤回任务
try:
response_msg_id = await self.message_service.send_group_message(
group_id,
permission_denied_msg,
platform=platform
)
if response_msg_id:
self._schedule_config_message_recall(response_msg_id, platform, is_success=False)
return MessageEventResult()
except Exception as e:
logger.error(f"[NewbieVerification] 发送权限不足消息失败: {e}")
return MessageEventResult().message(permission_denied_msg)
else:
# 私聊直接返回
return MessageEventResult().message(permission_denied_msg)
# 有权限:委托给 ConfigHandler 处理
result = await self.config_handler.handle(event, is_global_admin, is_group_admin)
# 如果是群聊且返回了消息,拦截并改用 message_service 发送(以获取消息ID)
if is_group_message and result and hasattr(result, 'chain') and result.chain:
try:
# 提取消息文本
message_text = ""
for component in result.chain.chain:
if hasattr(component, 'text'):
message_text += component.text
if message_text:
# 判断是否为配置操作结果(需要撤回)
# 不撤回帮助文档和"已发送到私信"的提示
should_recall = self._should_recall_config_message(message_text)
if should_recall:
# 立即撤回用户的配置消息
if user_msg_id:
asyncio.create_task(self._recall_user_config_message(user_msg_id, platform))
# 判断消息类型(成功 vs 失败)
is_success_msg = self._is_success_config_message(message_text)
# 使用 message_service 发送响应消息
response_msg_id = await self.message_service.send_group_message(
group_id,
message_text,
platform=platform
)
if response_msg_id:
# 启动撤回任务,根据消息类型使用不同延迟
self._schedule_config_message_recall(response_msg_id, platform, is_success=is_success_msg)
return MessageEventResult()
except Exception as e:
logger.error(f"[NewbieVerification] 处理配置消息撤回失败: {e}", exc_info=True)
# 非群聊或无需特殊处理,直接返回原结果
return result
def _should_recall_config_message(self, message_text: str) -> bool:
"""判断配置消息是否需要撤回"""
# 不撤回的消息类型
no_recall_keywords = [
"已通过私聊发送",
"已发送到您的私信",
"已发送到私信",
"请查看私信",
"使用 /verifyconfig",
"验证系统配置命令",
]
for keyword in no_recall_keywords:
if keyword in message_text:
return False
# 需要撤回的消息类型(配置操作结果)
recall_keywords = [
"已设置为",
"已启用",
"已禁用",
"已添加",
"已移除",
"已重置",
"权限不足",
"系统正在初始化",
"参数值必须",
"范围:",
"无效",
"未知",
]
for keyword in recall_keywords:
if keyword in message_text:
return True
return False
def _is_success_config_message(self, message_text: str) -> bool:
"""判断配置消息是成功还是失败
Returns:
True: 成功消息
False: 失败消息(错误、权限不足等)
"""
# 失败消息关键词
fail_keywords = [
"权限不足",
"系统正在初始化",
"参数值必须",
"范围:",
"无效",
"未知",
"失败",
"错误",
]
for keyword in fail_keywords:
if keyword in message_text:
return False
# 成功消息关键词
success_keywords = [
"已设置为",
"已启用",
"已禁用",
"已添加",
"已移除",
"已重置",
]
for keyword in success_keywords:
if keyword in message_text:
return True
# 默认视为失败消息(保守策略)
return False
async def _recall_user_config_message(self, message_id: int, platform: str):
"""立即撤回用户的配置消息"""
try:
await asyncio.sleep(0.5)
success = await self.message_service.recall_message(message_id, platform, max_retries=2)
if success:
logger.info(f"[NewbieVerification] 已撤回用户配置消息: {message_id}")
else:
logger.warning(f"[NewbieVerification] 撤回用户配置消息失败: {message_id}")
except Exception as e:
logger.error(f"[NewbieVerification] 撤回用户配置消息异常: {e}")
def _schedule_config_message_recall(self, message_id: int, platform: str, is_success: bool = True):
"""调度配置消息撤回任务
Args:
message_id: 消息ID
platform: 平台标识
is_success: True=成功消息(使用成功延迟),False=失败消息(使用失败延迟)
"""
if is_success:
delay = self.config.config_success_message_recall_seconds
msg_type = "成功"
else:
delay = self.config.config_fail_message_recall_seconds
msg_type = "失败"
async def recall_task():
try:
await asyncio.sleep(delay)
success = await self.message_service.recall_message(message_id, platform, max_retries=2)
if success:
logger.info(f"[NewbieVerification] 已撤回配置{msg_type}响应消息: {message_id}")
else:
logger.warning(f"[NewbieVerification] 撤回配置{msg_type}响应消息失败: {message_id}")
except Exception as e:
logger.error(f"[NewbieVerification] 撤回配置{msg_type}响应消息异常: {e}")
# 创建后台任务
task = asyncio.create_task(recall_task())
self._register_background_task(task)
logger.debug(f"[NewbieVerification] 已调度配置{msg_type}消息撤回任务,将在 {delay} 秒后执行")
@filter.permission_type(filter.PermissionType.ADMIN)
@filter.command("blacklist2")
async def blacklist_command(self, event: AstrMessageEvent):
"""黑名单管理命令(仅管理员/群主可见)"""
logger.info(f"[NewbieVerification] 收到黑名单命令: {event.message_str}")
if not self.blacklist_handler:
logger.debug("[NewbieVerification] 黑名单处理器未就绪,忽略命令")
return MessageEventResult().message(" 系统正在初始化,请稍后再试")
return await self.blacklist_handler.handle(event)
def _check_global_permission(self, event: AstrMessageEvent) -> bool:
"""检查用户是否有全局管理员权限(OP/WL)
检查AstrBot配置中的 admins_id 列表
Args:
event: 消息事件
Returns:
bool: 是否有全局管理员权限
"""
try:
user_id = str(event.get_sender_id())
# 获取AstrBot配置
if hasattr(self.context, 'get_config'):
config = self.context.get_config()
# 检查 admins_id 列表
if hasattr(config, 'get') and config.get('admins_id'):
admins_list = config.get('admins_id', [])
return user_id in admins_list
# 备用检查方式:直接属性访问
if hasattr(config, 'admins_id') and config.admins_id:
admins_list = config.admins_id
return user_id in admins_list
return False
except Exception as e:
logger.error(f" [NewbieVerification] 权限检查异常: {e}", exc_info=True)
return False
@filter.event_message_type(filter.EventMessageType.ALL)
async def on_message(self, event: AstrMessageEvent):
"""监听所有事件,包括新人入群通知和验证码回复"""
if not self.config:
logger.debug("[NewbieVerification] Config not loaded, skipping")
return MessageEventResult()
if not self.verification_service:
logger.debug("[NewbieVerification] Verification service not ready, skipping")
return MessageEventResult()
# 检查是否为新人入群事件
raw_message = None
if hasattr(event, 'message_obj') and event.message_obj:
raw_message = getattr(event.message_obj, 'raw_message', None)
if not raw_message and hasattr(event, 'raw_message'):
raw_message = event.raw_message
# 调试日志:记录接收到的事件类型
if hasattr(event, 'message_obj') and event.message_obj:
msg_type = event.message_obj.type.value
logger.debug(f"[NewbieVerification] 收到消息事件 类型:{msg_type}")
if raw_message and isinstance(raw_message, dict):
post_type = raw_message.get('post_type')
notice_type = raw_message.get('notice_type')
# === 【修复】过滤掉非消息类型事件,避免notice事件被当作发言 ===
# notice事件包括:群邀请、禁言、撤回、群成员增加/减少等
# meta事件包括:心跳、生命周期等
if post_type == 'notice':
logger.debug(f"[NewbieVerification] 检测到notice事件 类型:{notice_type}")
# 只处理新人入群事件,其他notice事件直接跳过
if notice_type == 'group_increase':
group_id = str(raw_message.get('group_id', ''))
user_id = str(raw_message.get('user_id', ''))
platform = self.platform_helper.detect_platform(event)
logger.info(f"[NewbieVerification] 检测到入群事件 用户:{user_id} 群:{group_id} 平台:{platform}")
# 【两层黑名单机制】先检查黑名单
if self.blacklist_mgr:
blacklist_user = self.blacklist_mgr.is_blacklisted(user_id, group_id)
if blacklist_user:
logger.info(f"[NewbieVerification] 检测到黑名单用户 {user_id} 入群,准备踢出")
try:
# 踢出黑名单用户
bot = self.platform_helper.get_bot_instance(event)
if bot and hasattr(bot, 'api'):
await bot.api.call_action(
'set_group_kick',
group_id=int(group_id),
user_id=int(user_id),
reject_add_request=False # 不拒绝加群请求
)
logger.info(f"[NewbieVerification] 已踢出黑名单用户 {user_id}")
# 发送通知消息
await self.message_service.send_group_message(
group_id,
f"[警告] 检测到黑名单用户入群,已自动移除\n原因: {blacklist_user.reason}",
platform=platform
)
# 更新统计数据
self.stats.increment_blacklist_kicks()
return MessageEventResult()
except Exception as e:
logger.error(f"[NewbieVerification] 踢出黑名单用户失败: {e}", exc_info=True)
# 检查群是否启用验证
if group_id not in self.config.enabled_groups:
logger.info(f"[NewbieVerification] 群 {group_id} 未启用验证")
# 【新功能】OP 用户自动启用验证程序
if self.auto_enable_handler:
result = await self.auto_enable_handler.handle_op_auto_enable(
event, group_id, user_id, platform
)
if result is not None:
# 已处理(成功或失败)
return result
# 非 OP 用户或 handler 未就绪,跳过
logger.info(f"[NewbieVerification] 群 {group_id} 未启用验证,跳过")
return MessageEventResult()
# 【关键】检查是否为群主/管理员(管理员不需要验证)
is_admin = await self.platform_helper.is_group_admin_or_owner(event, user_id, group_id, platform)
if is_admin:
logger.info(f"[NewbieVerification] 用户 {user_id} 是群主/管理员,跳过验证")
return MessageEventResult()
# 【新功能】检查是否为OP/WL用户(全局管理员不需要验证)
is_global_admin = self._check_global_permission(event)
if is_global_admin:
logger.info(f"[NewbieVerification] 用户 {user_id} 是OP/WL全局管理员,跳过验证")
# 发送跳过验证提示消息到群聊
try:
# 获取用户昵称
try:
bot = self.platform_helper.get_bot_instance(event)
if bot and hasattr(bot, 'api'):
user_info = await bot.api.call_action(
'get_group_member_info',
group_id=int(group_id),
user_id=int(user_id)
)
nickname = user_info.get('card') or user_info.get('nickname') or f'用户{user_id}'
else:
nickname = f'用户{user_id}'
except Exception as e:
logger.error(f"[NewbieVerification] 获取OP/WL用户信息失败: {e}")
nickname = f'用户{user_id}'
# 发送提示消息(带@)
skip_msg = f"您是OP/WL全局管理员,本次验证已自动跳过,全局权限获取成功"
await self.message_service.send_group_at_message(
group_id,
user_id,
skip_msg,
platform=platform
)
logger.info(f"[NewbieVerification] 已发送OP/WL跳过验证提示消息给用户 {nickname}({user_id})")
except Exception as e:
logger.error(f"[NewbieVerification] 发送OP/WL跳过验证提示失败: {e}", exc_info=True)
return MessageEventResult()
# 获取用户昵称
try:
bot = self.platform_helper.get_bot_instance(event)
if bot and hasattr(bot, 'api'):
user_info = await bot.api.call_action(
'get_group_member_info',
group_id=int(group_id),
user_id=int(user_id)
)
nickname = user_info.get('card') or user_info.get('nickname') or f'用户{user_id}'
logger.debug(f"[NewbieVerification] 获取用户信息成功 昵称:{nickname}")
else:
nickname = f'用户{user_id}'
logger.warning(f"[NewbieVerification] 无法获取bot实例,使用默认昵称")
except Exception as e:
logger.error(f"[NewbieVerification] 获取用户信息失败: {e}", exc_info=True)
nickname = f'用户{user_id}'
# 处理新人入群
logger.info(f"[NewbieVerification] 开始处理新人验证 {nickname}({user_id}) 群:{group_id}")
await self.handle_new_member(group_id, user_id, nickname, platform)
logger.info(f" [NewbieVerification] 新人验证流程已触发")
return MessageEventResult()
elif notice_type == 'group_msg_emoji_like':
# 处理表情反应审批
logger.debug(f"[NewbieVerification] 检测到群消息表情反应")
if self.quick_approve_handler:
handled = await self.quick_approve_handler.handle_reaction_approve(raw_message)
if handled:
return MessageEventResult()
return MessageEventResult()
else:
# 其他notice事件(禁言、撤回、群减少等),直接跳过
logger.debug(f"[NewbieVerification] 跳过notice事件: {notice_type}")
return MessageEventResult()
elif post_type == 'meta':
# meta事件(心跳、生命周期等),直接跳过
logger.debug(f"[NewbieVerification] 跳过meta事件")
return MessageEventResult()
elif post_type != 'message':
# 其他非消息类型事件,直接跳过
logger.debug(f"[NewbieVerification] 跳过非消息事件: post_type={post_type}")
return MessageEventResult()
# ============ 【修复】跳过命令消息,让命令处理器接管 ============
# 检查消息是否为命令(以 . 或 / 开头)
msg_str = event.get_message_str()
if msg_str and (msg_str.startswith('.') or msg_str.startswith('/')):
# 这是一个命令,不应该被验证系统处理
# 让 AstrBot 的命令系统接管
logger.debug(f"[NewbieVerification] 检测到命令消息,跳过验证处理: {msg_str}")
return MessageEventResult()
# ============ 【性能优化】早期过滤:避免非验证用户的消息进入处理流程 ============
# 获取消息类型和发送者信息
message_type = event.message_obj.type.value if event.message_obj else None
if message_type == "GroupMessage":
# 群消息的早期过滤
group_id = str(event.get_group_id())
user_id = str(event.get_sender_id())
# 过滤1:检查群是否启用验证
if group_id not in self.config.enabled_groups:
# 使用debug级别,避免刷屏日志
return MessageEventResult()
# 检查是否为回复审批
if self.quick_approve_handler:
approve_result = await self.quick_approve_handler.handle_reply_approve(event)
if approve_result is not None:
# 匹配到回复审批,直接返回
return approve_result
# 过滤2:检查用户是否在验证列表(最关键的优化!)
verification_key = f"{group_id}_{user_id}"
if verification_key not in self.newbie_verification:
# 用户不在验证列表,是老用户,直接跳过所有处理
# 使用debug级别,避免刷屏日志
return MessageEventResult()
# 用户在验证列表,需要处理验证
logger.info(f"[NewbieVerification] 用户 {user_id} 在验证列表,进入验证处理流程")
# 只处理消息类型事件(post_type == 'message' 或没有raw_message)
return await self.verification_service.handle_verification_message(event)
async def terminate(self):
"""插件卸载/停用时的资源清理"""
try:
if hasattr(self, "_is_running"):
self._is_running = False
tasks_to_cancel: List[asyncio.Task] = []
if hasattr(self, "_timeout_check_task") and self._timeout_check_task:
self._timeout_check_task.cancel()
tasks_to_cancel.append(self._timeout_check_task)
self._timeout_check_task = None
if hasattr(self, "_auto_save_task") and self._auto_save_task:
self._auto_save_task.cancel()
tasks_to_cancel.append(self._auto_save_task)
self._auto_save_task = None
if hasattr(self, "_lock_cleanup_task") and self._lock_cleanup_task:
self._lock_cleanup_task.cancel()
tasks_to_cancel.append(self._lock_cleanup_task)
self._lock_cleanup_task = None
if hasattr(self, "_bypass_code_cleanup_task") and self._bypass_code_cleanup_task:
self._bypass_code_cleanup_task.cancel()