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

如何用python-telegram-bot v20获取机器人所属频道列表

获取python-telegram-bot v20中机器人加入/管理的所有频道列表

核心限制说明

Telegram Bot API本身没有提供直接获取机器人已加入所有频道的接口,这是Bot权限机制的限制——只有当频道内触发Bot的更新事件(比如Bot收到频道消息、被设置为管理员的通知),Bot才能获取到对应频道的ID。

可行解决方案

1. 监听频道成员变更事件

通过监听ChatMemberUpdated事件,捕获Bot被添加为频道管理员或加入频道的动作,实时记录频道ID:

from telegram import Update
from telegram.ext import ApplicationBuilder, ChatMemberHandler, ContextTypes

# 用集合存储频道ID,自动去重
channel_ids = set()

async def chat_member_update_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
    chat_member = update.chat_member
    chat = chat_member.chat
    # 仅处理频道类型的对话
    if chat.type == "channel":
        new_status = chat_member.new_chat_member.status
        # 当Bot成为频道成员、管理员或创建者时记录频道
        if new_status in ["member", "administrator", "creator"]:
            channel_ids.add(chat.id)
            print(f"已记录频道: {chat.id} ({chat.title})")

def main():
    application = ApplicationBuilder().token("你的Bot令牌").build()
    # 添加成员变更事件处理器
    application.add_handler(ChatMemberHandler(chat_member_update_handler, ChatMemberHandler.CHAT_MEMBER))
    application.run_polling()

if __name__ == "__main__":
    main()

2. 持久化存储频道列表

将记录的频道ID保存到本地文件或数据库,避免重启Bot后丢失数据:

# 保存频道列表到本地文件
def save_channels():
    with open("channels_list.txt", "w") as f:
        for cid in channel_ids:
            f.write(f"{cid}\n")

# 从本地文件加载已记录的频道
def load_channels():
    global channel_ids
    try:
        with open("channels_list.txt", "r") as f:
            channel_ids = set(int(line.strip()) for line in f if line.strip())
    except FileNotFoundError:
        channel_ids = set()

注意事项

  • 只有Bot被新添加到频道、权限发生变更时,才能捕获到该频道信息;历史已加入但未触发过更新事件的频道,无法自动获取。
  • 确保Bot在频道中开启了读取消息权限,否则无法接收频道的更新事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:44:59