如何使用python-telegram-bot实现接收消息后主动跨频道转发
python-telegram-bot 跨频道转发消息实现方案
操作前请先将bot同时加入频道A、频道B,并为bot授予查看消息、发送消息的管理员权限,不需要直接调用requests接口,除reply_text外有两种更适配该场景的实现方式:
方法1:使用forward_message直接转发(推荐)
该方法可以原封不动将频道A的整条消息(包含文字、图片、视频、排版格式等所有内容)转发到频道B,不需要手动提取拼接内容,代码最简洁。
v20.x 异步版本(当前主流版本)代码示例:
from telegram import Update from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes # 替换为自己的bot token BOT_TOKEN = "你的bot token" # 替换为频道B的chat_id,格式为-100开头的负数 TARGET_CHAT_ID = -100xxxxxxxxx async def forward_channel_msg(update: Update, context: ContextTypes.DEFAULT_TYPE): # 校验消息来源为频道A,替换为频道A的chat_id if update.effective_chat.id == -100<频道A的chat_id>: await context.bot.forward_message( chat_id=TARGET_CHAT_ID, from_chat_id=update.effective_chat.id, message_id=update.effective_message.id ) if __name__ == "__main__": application = ApplicationBuilder().token(BOT_TOKEN).build() channel_handler = MessageHandler(filters.ChatType.CHANNEL, forward_channel_msg) application.add_handler(channel_handler) application.run_polling()
v13.x 同步版本代码示例:
from telegram import Update from telegram.ext import Updater, MessageHandler, Filters, CallbackContext BOT_TOKEN = "你的bot token" TARGET_CHAT_ID = -100xxxxxxxxx def forward_channel_msg(update: Update, context: CallbackContext): if update.effective_chat.id == -100<频道A的chat_id>: context.bot.forward_message( chat_id=TARGET_CHAT_ID, from_chat_id=update.effective_chat.id, message_id=update.effective_message.id ) if __name__ == "__main__": updater = Updater(BOT_TOKEN) dp = updater.dispatcher dp.add_handler(MessageHandler(Filters.chat_type.channel, forward_channel_msg)) updater.start_polling() updater.idle()
方法2:使用send_message发送自定义处理后的内容
如果你需要先修改、过滤原消息内容再发送,就用这个方法,不需要依赖回复上下文,直接指定目标频道ID即可发送。
v20.x 版本代码片段:
async def send_processed_msg(update: Update, context: ContextTypes.DEFAULT_TYPE): if update.effective_chat.id == -100<频道A的chat_id>: # 提取原消息内容,可在此处添加过滤、修改逻辑 original_content = update.effective_message.text or "" processed_content = f"来源通知:\n{original_content}" await context.bot.send_message( chat_id=TARGET_CHAT_ID, text=processed_content )
注意事项
- 频道ID均为
-100开头的负数值,你可以通过getUpdates接口查询获取对应频道的ID - 如果需要发送图片、视频等非文字内容,可以对应调用
send_photo、send_video、send_document等同系列方法,传入对应媒体的file_id和目标chat_id即可
内容的提问来源于stack exchange,提问作者Catao
相关产品推荐
相关产品推荐

