-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
160 lines (135 loc) · 5.97 KB
/
bot.py
File metadata and controls
160 lines (135 loc) · 5.97 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
import json
import logging
from telethon import TelegramClient, events
from telethon.tl.types import Channel, Chat
import asyncio
# Thiết lập logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Đọc config
def load_config():
try:
with open('config.json', 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
logger.error("Không tìm thấy file config.json!")
exit(1)
except json.JSONDecodeError:
logger.error("File config.json không đúng định dạng!")
exit(1)
config = load_config()
# Biến lưu trữ entity của các group
source_entity = None
target_entities = []
client = None
async def initialize_channels():
"""Khởi tạo và lưu trữ entity của các group"""
global source_entity, target_entities
try:
# Lấy entity của group nguồn
logger.info(f"Đang kết nối với group nguồn: {config['source_group']}")
try:
source_entity = await client.get_entity(config['source_group'])
# Kiểm tra loại chat
chat_type = "Nhóm" if isinstance(source_entity, Chat) else "Kênh" if isinstance(source_entity, Channel) else "Unknown"
logger.info(f"✓ Kết nối thành công với {chat_type} nguồn: {source_entity.title}")
except Exception as e:
logger.error(f"✗ Không thể kết nối với group nguồn: {str(e)}")
logger.error("Kiểm tra lại source_group ID trong config.json")
logger.error("Lưu ý: ID phải là Supergroup (bắt đầu bằng -100)")
return False
# Lấy entity của các group đích
logger.info(f"Đang kết nối với {len(config['target_groups'])} group đích...")
for group in config['target_groups']:
try:
entity = await client.get_entity(group)
target_entities.append(entity)
group_type = "Nhóm" if isinstance(entity, Chat) else "Kênh" if isinstance(entity, Channel) else "Unknown"
logger.info(f"✓ Kết nối thành công với {group_type}: {entity.title}")
except Exception as e:
logger.warning(f"⚠ Bỏ qua group {group}: {str(e)}")
if not target_entities:
logger.error("Không có group đích nào hợp lệ!")
return False
logger.info(f"Khởi tạo hoàn tất! Sẵn sàng forward từ 1 group đến {len(target_entities)} group.")
# Đăng ký event handler sau khi đã có source_entity
client.add_event_handler(
forward_handler,
events.NewMessage(chats=source_entity.id)
)
return True
except Exception as e:
logger.error(f"Lỗi khi khởi tạo: {str(e)}")
return False
async def forward_handler(event):
"""Handler để forward tin nhắn"""
try:
message = event.message
logger.info(f"📨 Nhận tin nhắn mới từ {source_entity.title}")
# Forward đến tất cả các nhóm đích
success_count = 0
fail_count = 0
for target in target_entities:
try:
await client.forward_messages(
entity=target,
messages=message,
from_peer=source_entity
)
success_count += 1
logger.info(f"✓ Forward thành công đến: {target.title}")
except Exception as e:
fail_count += 1
logger.warning(f"⚠ Không thể forward đến {target.title}: {str(e)}")
logger.info(f"📊 Kết quả: {success_count} thành công, {fail_count} thất bại")
except Exception as e:
logger.error(f"❌ Lỗi trong quá trình xử lý tin nhắn: {str(e)}")
async def main():
"""Hàm chính"""
global client
try:
logger.info("🚀 Đang khởi động bot...")
# Khởi tạo client - Sử dụng BOT
client = TelegramClient(
'auto_forward_bot',
config['api_id'],
config['api_hash']
)
# Kết nối client - Dùng BOT TOKEN
try:
await client.start(bot_token=config['bot_token'])
logger.info("✅ Bot đã đăng nhập thành công!")
except Exception as e:
logger.error(f"❌ Không thể đăng nhập bot: {str(e)}")
logger.error("Kiểm tra lại api_id, api_hash và bot_token trong config.json")
return
# Khởi tạo các kênh/nhóm
success = await initialize_channels()
if not success:
logger.error("❌ Khởi tạo thất bại! Bot sẽ dừng.")
logger.info("\n📝 Hướng dẫn sửa lỗi:")
logger.info("1. Chuyển group thành Supergroup (Settings → Group Type)")
logger.info("2. Lấy ID đúng bằng @userinfobot hoặc @getidsbot")
logger.info("3. ID phải bắt đầu bằng -100 (ví dụ: -1001234567890)")
logger.info("4. Thêm bot vào tất cả các group")
await client.disconnect()
return
# Chạy bot
logger.info("🤖 Bot đang chạy... Nhấn Ctrl+C để dừng.")
await client.run_until_disconnected()
except Exception as e:
logger.error(f"❌ Lỗi nghiêm trọng: {str(e)}")
if client and client.is_connected():
await client.disconnect()
if __name__ == '__main__':
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info("\n👋 Bot đã dừng bởi người dùng!")
except Exception as e:
logger.error(f"❌ Lỗi không xác định: {str(e)}")
import traceback
logger.error(traceback.format_exc())