Repository navigation
Expand file tree
/
Copy pathmessage_handler.py
More file actions
2045 lines (1762 loc) · 99.4 KB
/
Copy pathmessage_handler.py
File metadata and controls
2045 lines (1762 loc) · 99.4 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
# message_handler.py
from telethon import TelegramClient, events
import os
import re
import logging
import traceback
from typing import Optional, BinaryIO, Dict, List, Any, Tuple
from tempfile import NamedTemporaryFile
import asyncio
from datetime import datetime, timedelta, time
from telegram import error as telegram_error
from locales import get_text
class MyMessageHandler:
def __init__(self, db, client: TelegramClient, bot):
self.db = db
self.client = client
self.bot = bot
# 用于跟踪临时文件
self.temp_files = {}
# 启动清理任务
self.cleanup_task = None
# 媒体缓存
self.media_cache = {}
# 已处理的媒体组
self.processed_media_groups = set()
async def start_cleanup_task(self):
"""启动定期清理任务"""
if self.cleanup_task is None:
self.cleanup_task = asyncio.create_task(self.cleanup_old_files())
async def cleanup_old_files(self):
"""定期清理过期的临时文件"""
while True:
try:
current_time = datetime.now()
files_to_remove = []
# 检查所有临时文件
for file_path, timestamp in list(self.temp_files.items()):
if current_time - timestamp > timedelta(hours=1): # 1小时后清理
if os.path.exists(file_path):
try:
os.remove(file_path)
logging.info(get_text('en', 'file_cleanup_success', file_path=file_path))
except Exception as e:
logging.error(get_text('en', 'file_cleanup_error', file_path=file_path, error=str(e)))
files_to_remove.append(file_path)
# 从跟踪列表中移除已清理的文件
for file_path in files_to_remove:
self.temp_files.pop(file_path, None)
# 清理媒体缓存
media_ids_to_remove = []
for media_id, media_info in list(self.media_cache.items()):
if current_time - media_info.get('timestamp', current_time) > timedelta(minutes=10): # 10分钟后清理
media_ids_to_remove.append(media_id)
# 从缓存中移除过期的媒体
for media_id in media_ids_to_remove:
self.media_cache.pop(media_id, None)
# 清理已处理的媒体组
self.processed_media_groups.clear()
except Exception as e:
logging.error(get_text('en', 'cleanup_task_error', error=str(e)))
# 每小时运行一次
await asyncio.sleep(3600)
async def clear_media_cache(self, media_id, delay_seconds=600):
"""延迟清理媒体缓存"""
await asyncio.sleep(delay_seconds)
if media_id in self.media_cache:
self.media_cache.pop(media_id, None)
logging.info(f"媒体缓存已清理: {media_id}")
def get_media_id(self, message) -> str:
"""获取媒体文件的唯一标识"""
try:
# 尝试不同的属性来生成唯一ID
if hasattr(message.media, 'photo'):
photo = message.media.photo
return f"photo_{photo.id}_{photo.access_hash}"
elif hasattr(message.media, 'document'):
doc = message.media.document
return f"document_{doc.id}_{doc.access_hash}"
elif hasattr(message.media, 'video'):
video = message.media.video
return f"video_{video.id}_{video.access_hash}"
else:
# 如果无法获取特定属性,使用消息的唯一标识
return f"media_{message.chat_id}_{message.id}"
except Exception as e:
logging.error(f"获取媒体ID时出错: {str(e)}")
# 如果出错,使用消息的唯一标识
return f"media_{message.chat_id}_{message.id}"
def get_media_type(self, message) -> str:
"""获取媒体类型"""
if hasattr(message.media, 'photo'):
return 'photo'
elif hasattr(message.media, 'document'):
# 检查是否是贴图
if hasattr(message.media.document, 'attributes'):
for attr in message.media.document.attributes:
if hasattr(attr, 'CONSTRUCTOR_ID') and attr.CONSTRUCTOR_ID == 0x6319d612: # DocumentAttributeSticker
return 'sticker'
elif hasattr(attr, '__class__') and 'DocumentAttributeSticker' in str(attr.__class__):
return 'sticker'
# 检查是否是视频
elif hasattr(attr, 'CONSTRUCTOR_ID') and attr.CONSTRUCTOR_ID == 0x0ef02ce6: # DocumentAttributeVideo
return 'video'
elif hasattr(attr, '__class__') and 'DocumentAttributeVideo' in str(attr.__class__):
return 'video'
# 检查是否是音频
elif hasattr(attr, 'CONSTRUCTOR_ID') and attr.CONSTRUCTOR_ID == 0x9852f9c6: # DocumentAttributeAudio
return 'audio'
elif hasattr(attr, '__class__') and 'DocumentAttributeAudio' in str(attr.__class__):
return 'audio'
# 检查是否是动画
elif hasattr(attr, 'CONSTRUCTOR_ID') and attr.CONSTRUCTOR_ID == 0x0051792c: # DocumentAttributeAnimated
return 'animation'
elif hasattr(attr, '__class__') and 'DocumentAttributeAnimated' in str(attr.__class__):
return 'animation'
# 检查MIME类型
if hasattr(message.media.document, 'mime_type'):
mime_type = message.media.document.mime_type
if mime_type:
if mime_type.startswith('video/'):
return 'video'
elif mime_type.startswith('audio/'):
return 'audio'
elif mime_type.startswith('image/'):
if mime_type == 'image/gif':
return 'animation'
return 'photo'
return 'document'
elif hasattr(message.media, 'video'):
return 'video'
else:
return 'unknown'
async def handle_channel_message(self, event):
"""处理频道消息"""
try:
message = event.message
if not message:
return
chat = await event.get_chat()
channel_info = self.db.get_channel_info(chat.id)
if not channel_info or not channel_info.get('is_active'):
return
# 获取所有转发频道
forward_channels = self.db.get_all_forward_channels(chat.id)
if not forward_channels:
return
# 获取消息内容用于过滤
content = ""
if getattr(message, 'text', None):
content = message.text
elif getattr(message, 'caption', None):
content = message.caption
# 获取媒体类型
media_type = 'text' # 默认为文本
if getattr(message, 'media', None):
media_type = self.get_media_type(message)
logging.info(f"检测到媒体类型: {media_type}")
# 获取当前时间
current_time = datetime.now()
current_time_str = current_time.strftime('%H:%M')
current_weekday = current_time.weekday() + 1 # 周一为1,周日为7
for channel in forward_channels:
try:
monitor_id = chat.id
forward_id = channel.get('channel_id')
# 检查时间段过滤
if not self.check_time_filter(monitor_id, forward_id, current_time_str, current_weekday):
logging.info(f"消息被时间段过滤器拦截: 监控频道={monitor_id}, 转发频道={forward_id}")
continue
# 检查内容过滤
if content:
logging.info(f"开始检查内容过滤器: 监控频道={monitor_id}, 转发频道={forward_id}")
content_preview = content[:100] + "..." if len(content) > 100 else content
logging.info(f"消息内容预览: '{content_preview}'")
if not self.check_content_filter(monitor_id, forward_id, content):
logging.info(f"消息被内容过滤器拦截: 监控频道={monitor_id}, 转发频道={forward_id}")
continue
else:
logging.info(f"消息通过内容过滤器: 监控频道={monitor_id}, 转发频道={forward_id}")
# 检查媒体类型过滤
if not self.check_media_filter(monitor_id, forward_id, media_type):
logging.info(f"消息被媒体类型过滤器拦截: 监控频道={monitor_id}, 转发频道={forward_id}, 媒体类型={media_type}")
continue
# 通过所有过滤器,转发消息
await self.handle_forward_message(message, chat, channel)
except Exception as e:
logging.error(get_text('en', 'forward_channel_error',
channel_id=channel.get('channel_id'),
error=str(e)))
continue
except Exception as e:
logging.error(get_text('en', 'message_handler_error', error=str(e)))
logging.error(get_text('en', 'error_details', details=traceback.format_exc()))
def check_time_filter(self, monitor_id: int, forward_id: int, current_time: str, current_weekday: int) -> bool:
"""检查时间段过滤器"""
try:
# 标准化频道ID
monitor_id = self._normalize_channel_id(monitor_id)
forward_id = self._normalize_channel_id(forward_id)
# 生成pair_id
pair_id = f"{monitor_id}:{forward_id}"
logging.info(f"生成频道配对ID(时间过滤): {pair_id}, 当前时间: {current_time}, 星期: {current_weekday}")
# 获取时间段过滤器
time_filters = self.db.get_time_filters(pair_id=pair_id)
logging.info(f"获取到时间过滤规则: {len(time_filters)} 条")
# 如果没有过滤器,允许所有时间
if not time_filters:
logging.info("没有时间过滤规则,允许所有时间")
return True
# 检查每个时间段过滤器
for filter_rule in time_filters:
# 检查当前星期是否在过滤器的星期范围内
days_of_week = filter_rule.get('days_of_week', '').split(',')
logging.info(f"检查星期范围: {days_of_week}, 当前星期: {current_weekday}")
# 处理星期范围,支持如 1-5 的范围表示
weekday_match = False
for day_item in days_of_week:
if '-' in day_item:
# 如果是范围,如 1-5
try:
start_day, end_day = map(int, day_item.split('-'))
if start_day <= current_weekday <= end_day:
weekday_match = True
break
except ValueError:
logging.warning(f"无效的星期范围格式: {day_item}")
else:
# 如果是单个星期,如 1
try:
if int(day_item.strip()) == current_weekday:
weekday_match = True
break
except ValueError:
logging.warning(f"无效的星期格式: {day_item}")
if days_of_week and not weekday_match:
logging.info(f"当前星期 {current_weekday} 不在过滤器的星期范围内 {days_of_week}")
continue
# 检查当前时间是否在过滤器的时间范围内
start_time = filter_rule.get('start_time')
end_time = filter_rule.get('end_time')
logging.info(f"检查时间范围: {start_time}-{end_time}, 当前时间: {current_time}")
if start_time and end_time:
# 如果当前时间在范围内
in_time_range = start_time <= current_time <= end_time
# 根据模式决定是否允许
mode = filter_rule.get('mode', 'ALLOW')
if mode == 'ALLOW' and in_time_range:
logging.info(f"当前时间在允许范围内,允许转发")
return True
elif mode == 'BLOCK' and in_time_range:
logging.info(f"当前时间在拦截范围内,拦截转发")
return False
# 如果没有匹配的规则,默认允许
logging.info("没有匹配的时间过滤规则,默认允许")
return True
except Exception as e:
logging.error(f"检查时间段过滤器时出错: {e}")
logging.error(f"错误详情: {traceback.format_exc()}")
# 出错时默认允许
return True
def check_content_filter(self, monitor_id: int, forward_id: int, content: str) -> bool:
"""检查内容过滤器"""
try:
# 标准化频道ID
monitor_id = self._normalize_channel_id(monitor_id)
forward_id = self._normalize_channel_id(forward_id)
# 生成pair_id
pair_id = f"{monitor_id}:{forward_id}"
logging.info(f"生成频道配对ID: {pair_id}")
# 获取过滤规则
filter_rules = self.db.get_filter_rules(pair_id=pair_id)
logging.info(f"获取到过滤规则: {len(filter_rules)} 条")
# 如果没有规则,允许所有内容
if not filter_rules:
logging.info("没有过滤规则,允许所有内容")
return True
# 分类规则
whitelist_rules = []
blacklist_rules = []
for rule in filter_rules:
if rule.get('rule_type') == 'WHITELIST':
whitelist_rules.append(rule)
elif rule.get('rule_type') == 'BLACKLIST':
blacklist_rules.append(rule)
logging.info(f"白名单规则: {len(whitelist_rules)} 条, 黑名单规则: {len(blacklist_rules)} 条")
# 如果有白名单规则,必须匹配至少一条才允许
if whitelist_rules:
whitelist_match = False
for rule in whitelist_rules:
logging.info(f"检查白名单规则: {rule.get('pattern')}")
if self.match_rule(rule, content):
whitelist_match = True
logging.info(f"白名单规则匹配成功: {rule.get('pattern')}")
break
if not whitelist_match:
logging.info("没有匹配任何白名单规则,拦截消息")
return False
# 如果有黑名单规则,匹配任一条则拒绝
for rule in blacklist_rules:
logging.info(f"检查黑名单规则: {rule.get('pattern')}")
if self.match_rule(rule, content):
logging.info(f"黑名单规则匹配成功: {rule.get('pattern')},拦截消息")
return False
# 通过所有过滤
logging.info("消息通过所有内容过滤器")
return True
except Exception as e:
logging.error(f"检查内容过滤器时出错: {e}")
logging.error(f"错误详情: {traceback.format_exc()}")
# 出错时默认允许
return True
def _normalize_channel_id(self, channel_id: int) -> int:
"""标准化频道ID格式,确保存储时不带-100前缀"""
str_id = str(channel_id)
if str_id.startswith('-100'):
return int(str_id[4:])
elif str_id.startswith('-'):
return int(str_id[1:])
return int(str_id)
def check_media_filter(self, monitor_id: int, forward_id: int, media_type: str) -> bool:
"""检查媒体类型过滤器"""
try:
# 标准化频道ID
monitor_id = self._normalize_channel_id(monitor_id)
forward_id = self._normalize_channel_id(forward_id)
# 生成pair_id
pair_id = f"{monitor_id}:{forward_id}"
logging.info(f"生成频道配对ID(媒体过滤): {pair_id}, 媒体类型: {media_type}")
# 获取媒体过滤规则
media_filters = self.db.get_media_filters(pair_id=pair_id)
logging.info(f"获取到媒体过滤规则: {len(media_filters)} 条")
# 如果没有规则,允许所有媒体类型
if not media_filters:
logging.info(f"没有媒体过滤规则,允许所有媒体类型: {media_type}")
return True
# 检查是否有匹配当前媒体类型的规则
for filter_rule in media_filters:
if filter_rule.get('media_type') == media_type:
action = filter_rule.get('action', 'ALLOW')
logging.info(f"找到媒体类型过滤规则: {media_type}, 动作: {action}")
# 如果动作是拦截,返回False
if action == 'BLOCK':
logging.info(f"媒体类型 {media_type} 被拦截")
return False
# 如果动作是允许,返回True
elif action == 'ALLOW':
logging.info(f"媒体类型 {media_type} 被允许")
return True
# 如果没有匹配的规则,默认允许
logging.info(f"没有找到匹配的媒体类型规则,默认允许: {media_type}")
return True
except Exception as e:
logging.error(f"检查媒体类型过滤器时出错: {e}")
logging.error(f"错误详情: {traceback.format_exc()}")
# 出错时默认允许
return True
def match_rule(self, rule: dict, content: str) -> bool:
"""检查内容是否匹配规则"""
try:
pattern = rule.get('pattern', '')
if not pattern:
logging.info("规则模式为空,跳过")
return False
filter_mode = rule.get('filter_mode', 'KEYWORD')
rule_type = rule.get('rule_type', '')
logging.info(f"开始匹配规则: 类型={rule_type}, 模式={filter_mode}, 内容='{pattern}'")
if filter_mode == 'KEYWORD':
# 关键词模式,将整个关键词作为一个整体进行匹配
pattern_lower = pattern.lower()
content_lower = content.lower()
# 记录内容的一部分用于调试
content_preview = content_lower[:100] + "..." if len(content_lower) > 100 else content_lower
logging.info(f"内容预览: '{content_preview}'")
# 直接检查内容是否包含关键词
match_result = pattern_lower in content_lower
if match_result:
logging.info(f"关键词匹配成功: '{pattern}' 在消息中被找到")
else:
logging.info(f"关键词匹配失败: '{pattern}' 不在消息中")
return match_result
elif filter_mode == 'REGEX':
# 正则表达式模式
try:
match_result = bool(re.search(pattern, content, re.IGNORECASE))
if match_result:
logging.info(f"正则表达式匹配成功: '{pattern}'")
else:
logging.info(f"正则表达式匹配失败: '{pattern}'")
return match_result
except re.error as regex_error:
logging.error(f"正则表达式错误: {regex_error}, 模式: '{pattern}'")
return False
logging.info(f"未知的过滤模式: {filter_mode}")
return False
except Exception as e:
logging.error(f"匹配规则时出错: {e}")
logging.error(f"错误详情: {traceback.format_exc()}")
return False
async def handle_media_send(self, message, channel_id, media_type: str = None, reply_to_message_id: int = None, from_chat = None):
"""处理媒体发送并确保清理"""
# 下载媒体文件
media_info = await self.download_media_file(message, media_type)
if not media_info:
logging.error("媒体文件下载失败")
return
file_path = media_info.get('file_path')
media_type = media_info.get('media_type')
try:
# 只有在没有回复消息时才添加说明文字
caption = None
if not reply_to_message_id and from_chat:
# 构建用户名部分
username = f"(@{from_chat.username})" if getattr(from_chat, 'username', None) else ""
# 使用简化的模板作为媒体文件的标题
caption = f"📨 转发自 {getattr(from_chat, 'title', 'Unknown Channel')} {username}"
elif message.text or message.caption:
caption = message.text or message.caption
# 发送文件
with open(file_path, 'rb') as media_file:
try:
file_data = media_file.read()
send_kwargs = {
'chat_id': channel_id,
'caption': caption,
'read_timeout': 1800,
'write_timeout': 1800
}
if reply_to_message_id:
send_kwargs['reply_to_message_id'] = reply_to_message_id
if media_type == 'photo':
send_kwargs['photo'] = file_data
await self.bot.send_photo(**send_kwargs)
elif media_type == 'video':
send_kwargs.update({
'video': file_data,
'supports_streaming': True
})
# 添加视频参数
if 'width' in media_info:
send_kwargs['width'] = media_info['width']
if 'height' in media_info:
send_kwargs['height'] = media_info['height']
if 'duration' in media_info:
send_kwargs['duration'] = media_info['duration']
# 如果有缩略图
if 'thumb_path' in media_info and os.path.exists(media_info['thumb_path']):
with open(media_info['thumb_path'], 'rb') as thumb_file:
send_kwargs['thumb'] = thumb_file.read()
await self.bot.send_video(**send_kwargs)
# 清理缩略图
if 'thumb_path' in media_info and os.path.exists(media_info['thumb_path']):
os.remove(media_info['thumb_path'])
elif media_type == 'audio':
send_kwargs.update({
'audio': file_data
})
# 添加音频参数
if 'duration' in media_info:
send_kwargs['duration'] = media_info['duration']
if 'performer' in media_info:
send_kwargs['performer'] = media_info['performer']
if 'title' in media_info:
send_kwargs['title'] = media_info['title']
await self.bot.send_audio(**send_kwargs)
elif media_type == 'animation':
send_kwargs.update({
'animation': file_data
})
# 添加动画参数
if 'width' in media_info:
send_kwargs['width'] = media_info['width']
if 'height' in media_info:
send_kwargs['height'] = media_info['height']
if 'duration' in media_info:
send_kwargs['duration'] = media_info['duration']
await self.bot.send_animation(**send_kwargs)
elif media_type == 'document':
send_kwargs['document'] = file_data
if 'filename' in media_info:
send_kwargs['filename'] = media_info['filename']
await self.bot.send_document(**send_kwargs)
elif media_type == 'sticker':
# 发送贴图
await self.bot.send_sticker(
chat_id=channel_id,
sticker=file_data,
reply_to_message_id=reply_to_message_id
)
logging.info(f"文件发送成功: {media_type}" +
(f" (回复到消息: {reply_to_message_id})" if reply_to_message_id else ""))
finally:
del file_data # 释放内存
# 发送成功后清理文件
await self.cleanup_file(file_path)
return True
except Exception as e:
logging.error(f"处理媒体文件时出错: {str(e)}")
if file_path:
await self.cleanup_file(file_path)
return False
async def handle_forward_message(self, message, from_chat, to_channel):
"""处理消息转发"""
if not message or not from_chat or not to_channel:
logging.error(get_text('en', 'missing_parameters'))
return
try:
channel_id = to_channel.get('channel_id')
if not channel_id:
logging.error(get_text('en', 'invalid_channel_id'))
return
# 手动添加 -100 前缀
original_channel_id = channel_id
channel_id = int("-100" + str(channel_id))
logging.info(f"处理频道ID: 原始值={original_channel_id}, 处理后={channel_id}")
# 检查是否是回复消息
reply_to_message_id = None
original_reply_message = None
reply_info = None
if hasattr(message, 'reply_to_msg_id') and message.reply_to_msg_id:
try:
# 获取原始回复消息
original_reply_message = await self.client.get_messages(from_chat.id, ids=message.reply_to_msg_id)
if original_reply_message:
# 保存回复消息信息以便后续使用
reply_content = original_reply_message.text or original_reply_message.caption or ""
reply_info = {
'id': original_reply_message.id,
'content': reply_content,
'short_content': reply_content[:50] + "..." if len(reply_content) > 50 else reply_content
}
# 在数据库中查找这条消息是否已经转发过
forwarded_reply = self.db.get_forwarded_message(from_chat.id, message.reply_to_msg_id, channel_id)
if forwarded_reply:
# 如果找到了转发的回复消息,使用其ID作为回复ID
reply_to_message_id = forwarded_reply['forwarded_message_id']
logging.info(f"找到原始回复消息的转发记录,将使用原生回复: {reply_to_message_id}")
except Exception as e:
logging.warning(f"获取原始回复消息失败: {e}")
forwarded_msg = None
# 不使用直接转发,始终使用处理过的转发
logging.info("按要求不使用直接转发,将使用处理过的转发方式")
# 检查频道是否存在
try:
# 尝试获取频道信息来验证频道是否存在
chat = await self.bot.get_chat(channel_id)
if not chat:
logging.error(f"频道 {channel_id} 不存在或机器人无法访问,请检查权限或频道ID")
return
except telegram_error.BadRequest as e:
if "Chat not found" in str(e):
logging.error(f"频道 {channel_id} 不存在或机器人无法访问,请检查权限或频道ID")
return
else:
logging.warning(f"验证频道失败: {str(e)}")
except Exception as e:
logging.warning(f"验证频道失败: {str(e)}")
# 如果直接转发失败,处理文本消息
if getattr(message, 'text', None) or getattr(message, 'caption', None):
content = message.text or message.caption
# 获取频道类型
chat_type_key = 'chat_type_channel' # 默认类型
if hasattr(from_chat, 'type'):
if from_chat.type == 'channel':
if getattr(from_chat, 'username', None):
chat_type_key = 'chat_type_public_channel'
else:
chat_type_key = 'chat_type_private_channel'
elif from_chat.type == 'group':
chat_type_key = 'chat_type_group'
elif from_chat.type == 'supergroup':
chat_type_key = 'chat_type_supergroup'
elif from_chat.type == 'gigagroup':
chat_type_key = 'chat_type_gigagroup'
# 获取用户语言
lang = self.db.get_user_language(to_channel.get('channel_id', 0)) or 'en'
# 获取频道类型显示文本
chat_type = get_text(lang, chat_type_key)
# 获取当前时间
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 构建用户名部分
username = f"(@{from_chat.username})" if getattr(from_chat, 'username', None) else ""
# 检查是否是回复消息
reply_text = ""
# 如果有回复消息但无法使用原生回复,则在消息中添加回复信息
if reply_info and not reply_to_message_id:
reply_text = get_text(lang, 'reply_to_message', text=reply_info['short_content']) + "\n"
logging.info(f"添加回复信息到消息中: {reply_info['short_content']}")
# 确保频道标题和类型正确显示
channel_title = getattr(from_chat, 'title', None)
if not channel_title:
channel_title = getattr(from_chat, 'first_name', 'Unknown Channel')
# 使用新的消息模板
forwarded_text = get_text(lang, 'forwarded_message_template',
title=channel_title,
username=username,
chat_type=chat_type,
time=current_time,
content=reply_text + content)
# 记录转发信息以便调试
logging.info(f"转发消息信息: 标题={channel_title}, 类型={chat_type}, 用户名={username}")
# 检查是否有自定义表情
has_custom_emoji = await self.handle_custom_emoji(message, channel_id)
# 发送文本消息,如果有自定义表情则禁用Markdown格式
try:
# 如果有原生回复消息的ID,使用原生回复
send_kwargs = {
'chat_id': channel_id,
'text': forwarded_text,
'parse_mode': None if has_custom_emoji else 'Markdown',
'disable_web_page_preview': True
}
# 检查是否有回复消息ID,并安全地添加
if reply_to_message_id:
# 直接添加回复ID,如果消息不存在,后面会捕获并处理错误
send_kwargs['reply_to_message_id'] = reply_to_message_id
logging.info(f"尝试使用原生回复: {reply_to_message_id}")
# 确保回复文本已添加到消息中,以防回复失败
if reply_info and reply_text not in forwarded_text:
send_kwargs['text'] = reply_text + forwarded_text
# 尝试发送消息
try:
forwarded_msg = await self.bot.send_message(**send_kwargs)
# 保存转发关系
self.db.save_forwarded_message(from_chat.id, message.id, channel_id, forwarded_msg.message_id)
except telegram_error.BadRequest as br_error:
# 处理特定的错误
if "Message to be replied not found" in str(br_error):
# 回复的消息不存在,移除回复ID后重试
logging.warning("回复的消息不存在,移除回复ID后重试")
if 'reply_to_message_id' in send_kwargs:
del send_kwargs['reply_to_message_id']
forwarded_msg = await self.bot.send_message(**send_kwargs)
self.db.save_forwarded_message(from_chat.id, message.id, channel_id, forwarded_msg.message_id)
elif "can't parse entities" in str(br_error).lower():
# 实体解析错误,尝试使用纯文本
logging.warning(f"实体解析错误,尝试使用纯文本: {br_error}")
send_kwargs['parse_mode'] = None
forwarded_msg = await self.bot.send_message(**send_kwargs)
self.db.save_forwarded_message(from_chat.id, message.id, channel_id, forwarded_msg.message_id)
else:
# 其他BadRequest错误,重新抛出
raise
except Exception as e:
# 如果发送失败,尝试使用纯文本
logging.warning(f"发送消息失败,尝试使用纯文本: {e}")
send_kwargs = {
'chat_id': channel_id,
'text': forwarded_text,
'parse_mode': None,
'disable_web_page_preview': True
}
# 不添加回复ID,避免可能的错误
forwarded_msg = await self.bot.send_message(**send_kwargs)
# 保存转发关系
self.db.save_forwarded_message(from_chat.id, message.id, channel_id, forwarded_msg.message_id)
logging.info(get_text('en', 'text_send_success', channel_id=channel_id))
# 异步处理媒体消息
if getattr(message, 'media', None) and forwarded_msg:
logging.info("检测到媒体消息,开始异步处理")
# 检查是否是媒体组
if hasattr(message, 'grouped_id') and message.grouped_id:
# 异步处理媒体组
logging.info("检测到媒体组,开始异步处理媒体组")
asyncio.create_task(self.handle_media_group(
message=message,
channel_id=channel_id,
forwarded_msg=forwarded_msg, # 传递已转发的消息对象
from_chat=from_chat
))
return
# 确定媒体类型
media_type = self.get_media_type(message)
logging.info(f"媒体类型: {media_type}")
# 如果是贴图,使用特殊处理
if media_type == 'sticker':
asyncio.create_task(self.handle_sticker_send(
message=message,
channel_id=channel_id,
from_chat=from_chat,
reply_to_message_id=forwarded_msg.message_id
))
return
# 异步处理媒体文件,使用编辑模式
asyncio.create_task(self.handle_media_edit(
message=message,
channel_id=channel_id,
media_type=media_type,
forwarded_msg=forwarded_msg, # 传递已转发的消息对象
from_chat=from_chat
))
except Exception as e:
logging.error(get_text('en', 'forward_message_error', error=str(e)))
logging.error(get_text('en', 'error_details', details=traceback.format_exc()))
raise
async def cleanup_file(self, file_path: str):
"""清理单个文件"""
try:
if file_path and os.path.exists(file_path):
os.remove(file_path)
self.temp_files.pop(file_path, None)
logging.info(get_text('en', 'file_cleanup_success', file_path=file_path))
except Exception as e:
logging.error(get_text('en', 'file_cleanup_error',
file_path=file_path,
error=str(e)))
async def download_progress_callback(self, current, total):
"""下载进度回调"""
if total:
percentage = current * 100 / total
if percentage % 20 == 0: # 每20%记录一次
logging.info(get_text('en', 'download_progress', percentage=percentage))
async def handle_edited_message(self, event):
"""处理消息编辑事件"""
try:
# 获取编辑后的消息
message = event.message
if not message:
return
# 获取频道信息
chat = await event.get_chat()
channel_info = self.db.get_channel_info(chat.id)
if not channel_info or not channel_info.get('is_active'):
return
# 获取所有转发频道
forward_channels = self.db.get_all_forward_channels(chat.id)
if not forward_channels:
return
# 获取消息内容
content = ""
if hasattr(message, 'text') and message.text:
content = message.text
elif hasattr(message, 'caption') and message.caption:
content = message.caption
logging.info(f"编辑消息内容: {content}")
if not content:
return
# 获取用户语言
lang = self.db.get_user_language(chat.id) or 'en'
# 向所有转发频道发送编辑通知
for channel in forward_channels:
try:
# 手动添加 -100 前缀
original_channel_id = channel.get('channel_id')
channel_id = int("-100" + str(original_channel_id))
logging.info(f"处理频道ID(编辑消息): 原始值={original_channel_id}, 处理后={channel_id}")
# 尝试找到原始消息的转发消息
forwarded_msg = None
try:
# 在数据库中查找这条消息是否已经转发过
if hasattr(message, 'id'):
forwarded_msg = self.db.get_forwarded_message(chat.id, message.id, channel_id)
if forwarded_msg:
logging.info(f"找到原始消息的转发记录: {forwarded_msg['forwarded_message_id']}")
except Exception as e:
logging.warning(f"获取原始消息的转发记录失败: {e}")
# 准备编辑通知消息
edit_notice = get_text(lang, 'edited_message')
edit_text = f"{edit_notice}\n\n{content}"
# 发送编辑通知,使用Markdown格式
send_kwargs = {
'chat_id': channel_id,
'text': edit_text,
'parse_mode': 'Markdown', # 使用Markdown格式化
'disable_web_page_preview': True
}
# 如果找到了原消息的转发记录,使用回复形式
if forwarded_msg:
send_kwargs['reply_to_message_id'] = forwarded_msg['forwarded_message_id']
logging.info("使用回复形式发送编辑通知")
try:
await self.bot.send_message(**send_kwargs)
logging.info(f"成功发送编辑通知到频道 {channel_id}")
except Exception as e:
# 如果Markdown解析失败,尝试使用纯文本
logging.warning(f"使用Markdown发送编辑通知失败: {e}")
send_kwargs['parse_mode'] = None
await self.bot.send_message(**send_kwargs)
except Exception as e:
logging.error(f"发送编辑通知到频道 {channel.get('channel_id')} 失败: {str(e)}")
continue
except Exception as e:
logging.error(f"处理消息编辑事件时出错: {str(e)}")
logging.error(f"错误详情: {traceback.format_exc()}")
async def handle_deleted_message(self, event):
"""处理消息删除事件"""
try:
# 注意:删除的消息事件只包含消息ID,不包含内容
# 我们需要从事件中获取频道ID和消息ID
# 获取频道ID
chat_id = event.chat_id
# 获取删除的消息ID
deleted_ids = getattr(event, 'deleted_ids', [])
if not deleted_ids and hasattr(event, 'deleted_id'):
deleted_ids = [event.deleted_id]
# logging.info(f"检测到消息删除事件: 频道ID={chat_id}, 消息ID={deleted_ids}")
if not chat_id:
logging.warning("MessageDeleted 事件没有频道ID,无法处理")
return
if not deleted_ids:
logging.warning("MessageDeleted 事件没有删除的消息ID,无法处理")
return
# 获取频道信息
channel_info = self.db.get_channel_info(chat_id)
if not channel_info or not channel_info.get('is_active'):
return
# 获取所有转发频道
forward_channels = self.db.get_all_forward_channels(chat_id)
if not forward_channels:
return
# 获取用户语言
lang = self.db.get_user_language(chat_id) or 'en'
# 构建删除通知消息
delete_notice = get_text(lang, 'deleted_message')
logging.info(f"准备发送删除通知: {delete_notice}")
# 向所有转发频道发送删除通知
for channel in forward_channels:
try:
# 手动添加 -100 前缀
original_channel_id = channel.get('channel_id')
channel_id = int("-100" + str(original_channel_id))
logging.info(f"处理频道ID(删除消息): 原始值={original_channel_id}, 处理后={channel_id}")
# 尝试找到原始消息的转发消息
forwarded_msg = None
original_message_content = None
try:
# 在数据库中查找这条消息是否已经转发过
if hasattr(event, 'deleted_ids') and event.deleted_ids:
for msg_id in event.deleted_ids:
forwarded_msg = self.db.get_forwarded_message(chat_id, msg_id, channel_id)
if forwarded_msg:
logging.info(f"找到原始消息的转发记录: {forwarded_msg['forwarded_message_id']}")
# 尝试获取原始消息内容(如果有缓存)
# 注意:这里我们无法获取原始内容,因为消息已被删除
# 如果需要实现这个功能,需要在转发时将消息内容保存到数据库
break
except Exception as e:
logging.warning(f"获取原始消息的转发记录失败: {e}")
# 发送删除通知
send_kwargs = {
'chat_id': channel_id,
'text': delete_notice + (f"\n\n原消息内容: {original_message_content}" if original_message_content else ""),
'parse_mode': 'Markdown'
}
# 如果找到了原消息的转发记录,使用回复形式
if forwarded_msg:
try:
send_kwargs['reply_to_message_id'] = forwarded_msg['forwarded_message_id']
logging.info("使用回复形式发送删除通知")
await self.bot.send_message(**send_kwargs)
logging.info(f"成功发送删除通知到频道 {channel_id}")