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

使用Python telebot库开发的Telegram Bot无法在频道运行如何解决

核心原因
  1. 消息类型不匹配:Telegram 频道的更新属于channel_post类型,你当前代码中使用的@bot.message_handler仅会处理普通私聊、群组的message类型更新,根本无法捕获到频道的消息推送。
  2. 拉取更新范围未包含频道:bot.polling()默认拉取的更新列表仅包含普通消息、回调等类型,不会主动拉取频道的channel_post更新。
  3. 频道权限不足:Bot 被添加到频道时如果没有授予「查看频道消息」「发送消息」的管理员权限,也无法正常响应内容。
修复方案
  • 首先进入对应Telegram频道的管理后台,将Bot添加为管理员,勾选「查看频道消息」「发送消息」两项基础权限。
  • 新增频道消息的处理装饰器@bot.channel_post_handler,用法和@bot.message_handler完全一致,用来匹配频道内的消息;如果不需要区分普通消息和频道消息的处理逻辑,可以直接给同一个处理函数叠加两个装饰器,减少重复代码。
  • 调整bot.polling()的参数,显式指定需要拉取的更新类型,把channel_post加入允许列表。
修改后的完整代码
import telebot
# 注意你原代码里的常量模块名拼写错误,应该是constants
from constants import API_KEY

bot = telebot.TeleBot(API_KEY, parse_mode=None)

# 叠加两个装饰器,同时适配普通消息和频道消息,无需重复写逻辑
@bot.message_handler(commands=['help', 'hello'])
@bot.channel_post_handler(commands=['help', 'hello'])
def send_help_message(msg):
    bot.reply_to(msg, "Hello this is test bot for ml5")
    print(msg)

@bot.message_handler(func=lambda msg: msg.content_type == 'text' )
@bot.channel_post_handler(func=lambda msg: msg.content_type == 'text' )
def send_message(msg):
    bot.reply_to(msg, "Gotcha")

# 显式指定允许拉取的更新类型,包含普通消息和频道帖子
bot.polling(allowed_updates=['message', 'channel_post'])

内容的提问来源于stack exchange,提问作者Yomal Senarath

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:36:03