Telegram UserBot与自建Bot协同异常:自动转发无响应及Bot停滞问题
问题描述
- 搭建目标:通过Telegram UserBot将特定频道消息转发至自建Bot,由自建Bot自动响应转发内容
- 异常现象:
- 手动转发频道消息时,自建Bot可正常响应
- UserBot自动转发时,自建Bot无任何反应
- 运行UserBot代码后,自建Bot直接停止运行,即使直接发送消息也无响应
问题代码
# UserBot部分 @client.on(events.NewMessage(chats=CHANNEL_ID)) async def forward_to_bot(event): await client._forward_messages(‘bot name’, event.message) print(f"'{event.message.id}") client.start(phone) client.run_until_disconnected() # 自建Bot部分 @bot.message_handler func=lambda message: message.forward_from_chat and message.forward_from_chat.id == CHANNEL ID) def handle forwarded_message(message) : bot.reply_to(message, "Received forwarded message from the correct channel: {message, forward_from _chat.title]") bot.polling()
问题排查与修复方案
1. UserBot核心错误修复
- 启动逻辑位置错误:
client.start(phone)和client.run_until_disconnected()是UserBot的启动入口,不能放在消息处理函数内,否则每次收到频道消息就会重复启动UserBot,阻塞进程导致自建Bot无法运行。需将这两行移至全局代码块,仅执行一次。 - 内部方法误用与语法错误:
_forward_messages是Telethon内部方法,建议使用公开的forward_messages;目标参数‘bot name’要用英文引号,且需替换为自建Bot的完整用户名(如@your_custom_bot)。
修复后UserBot代码:
from telethon import TelegramClient, events CHANNEL_ID = 你的频道ID phone = "你的手机号" api_id = 你的API_ID api_hash = "你的API_HASH" client = TelegramClient('userbot_session', api_id, api_hash) @client.on(events.NewMessage(chats=CHANNEL_ID)) async def forward_to_bot(event): # 使用公开方法转发,目标为自建Bot用户名 await client.forward_messages('@your_custom_bot', event.message) print(f"已转发消息ID: {event.message.id}") # 全局启动UserBot,仅执行一次 if __name__ == '__main__': client.start(phone) client.run_until_disconnected()
2. 自建Bot代码修复
- 语法错误修正:
@bot.message_handler缺少括号,应改为@bot.message_handler(func=lambda...);函数名handle forwarded_message有空格,需改为handle_forwarded_message。 - 字符串格式化错误:回复内容里的
{message, forward_from _chat.title]格式混乱,应修正为{message.forward_from_chat.title}。 - 轮询逻辑错误:
bot.polling()是自建Bot的启动入口,不能放在消息处理函数内,否则每次收到消息就重复启动轮询,导致进程卡死。需移至全局代码块。
修复后自建Bot代码:
import telebot BOT_TOKEN = "你的BotToken" CHANNEL_ID = 你的频道ID bot = telebot.TeleBot(BOT_TOKEN) @bot.message_handler(func=lambda message: message.forward_from_chat and message.forward_from_chat.id == CHANNEL_ID) def handle_forwarded_message(message): bot.reply_to(message, f"已收到来自指定频道的转发消息:{message.forward_from_chat.title}") # 全局启动自建Bot轮询 if __name__ == '__main__': bot.polling(none_stop=True)
3. 运行注意事项
- UserBot和自建Bot必须分开运行:可通过两个终端窗口分别执行脚本,或使用后台进程(如nohup、screen)让两者同时运行,不能将两个Bot的启动逻辑写在同一个脚本中,否则会互相阻塞。
- 权限验证:确保UserBot已加入目标频道并有权限读取消息;UserBot需先主动给自建Bot发送一条消息,建立对话关系后才能正常转发内容。
内容的提问来源于stack exchange,提问作者ANDROID_IOS_BIGGENER
相关产品推荐
相关产品推荐

