You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在回复用户后将消息转发至频道?(pyTelegramBot API)

解决方法

你当前的代码仅处理了/data命令本身的消息,并未监听用户后续的回复内容。要实现将用户回复的原始消息转发到频道,需通过以下步骤调整:

1. 记录机器人发送的提示消息ID

在触发/data命令时,保存机器人发送的提示消息ID,用于后续识别用户是否是回复这条提示:

# 多用户场景建议用字典存储,单用户可直接用全局变量
user_reply_msg_map = {}

@bot.message_handler(commands=["data"])
def info(message):
    markup = ForceReply()
    # 发送提示消息并保存其ID
    prompt_msg = bot.send_message(message.chat.id, "Info", reply_markup=markup)
    user_reply_msg_map[message.chat.id] = prompt_msg.message_id

2. 监听并转发用户的回复消息

添加专属消息处理器,捕获用户针对机器人提示消息的回复,并转发到目标频道:

@bot.message_handler(func=lambda msg: msg.reply_to_message is not None and user_reply_msg_map.get(msg.chat.id) == msg.reply_to_message.message_id)
def forward_user_reply(msg):
    # 用forward_message完整转发用户的原始消息(含格式、媒体等)
    bot.forward_message(chat_id=id_channel, from_chat_id=msg.chat.id, message_id=msg.message_id)
    # 处理后删除该用户的记录,避免重复触发
    del user_reply_msg_map[msg.chat.id]

关键说明

  • ForceReply会让用户的消息自动关联机器人的提示消息,通过msg.reply_to_message可判断消息是否为目标回复
  • 使用forward_message能完整保留用户原始消息的所有属性(如作者、媒体内容),比send_message更贴合"转发原始消息"的需求

内容的提问来源于stack exchange,提问作者Ángel Romero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:40:10