如何用py-telegram-bot-api获取Telegram频道历史并转发内容?
解决py-telegram-bot-api无法获取频道历史消息的问题
首先明确:py-telegram-bot-api是对Telegram Bot API的封装,而Telegram Bot API本身没有提供get_chat_history方法,所以库中自然不存在这个属性。Bot API的核心限制是:Bot只能获取它加入频道后新产生的消息,无法直接获取频道的全部历史消息。
以下是两种可行的解决方案:
方案一:用get_updates拉取Bot加入后的消息
如果你的Bot是频道管理员,且仅需要获取Bot加入后产生的消息,可以通过get_updates结合偏移量分页获取,同时完成转发:
import telebot # 替换为你的Bot Token BOT_TOKEN = "your_bot_token_here" # 替换为目标频道ID(可以是@开头的用户名或数字ID) SOURCE_CHANNEL = "@your_source_channel" # 替换为转发目标的聊天ID DEST_CHAT_ID = "@your_destination_chat" bot = telebot.TeleBot(BOT_TOKEN) def fetch_and_forward_history(offset=0, limit=100): while True: # 拉取更新 updates = bot.get_updates(offset=offset, limit=limit, chat_id=SOURCE_CHANNEL) if not updates: break for update in updates: if update.message: # 转发消息 bot.forward_message( chat_id=DEST_CHAT_ID, from_chat_id=SOURCE_CHANNEL, message_id=update.message.message_id ) # 更新偏移量,避免重复拉取 offset = updates[-1].update_id + 1 # 执行拉取和转发 fetch_and_forward_history()
注意事项:
- 此方法仅能获取Bot加入频道后产生的消息,无法获取更早的历史;
- 遵守Telegram API的频率限制,避免短时间内频繁调用
get_updates。
方案二:使用MTProto协议库获取全部历史消息
如果需要获取频道的完整历史(包括Bot加入前的消息),必须使用基于MTProto协议的第三方库(如Telethon或Pyrogram),这类库绕过Bot API的限制,直接与Telegram服务器通信。
Telethon实现示例
from telethon import TelegramClient # 替换为你的API ID和API Hash(从Telegram开发者平台获取) API_ID = 123456 API_HASH = "your_api_hash_here" # 会话文件名,首次运行会生成 SESSION_NAME = "channel_history_session" # 替换为来源频道和目标聊天的用户名/ID SOURCE_CHANNEL = "@your_source_channel" DEST_CHAT = "@your_destination_chat" async def fetch_and_forward(): async with TelegramClient(SESSION_NAME, API_ID, API_HASH) as client: # 获取频道实体 channel = await client.get_entity(SOURCE_CHANNEL) # 遍历频道所有历史消息 async for message in client.iter_messages(channel): # 转发消息 await client.forward_messages(DEST_CHAT, message) # 执行任务 TelegramClient(SESSION_NAME, API_ID, API_HASH).start() TelegramClient(SESSION_NAME, API_ID, API_HASH).loop.run_until_complete(fetch_and_forward())
Pyrogram实现示例
from pyrogram import Client API_ID = 123456 API_HASH = "your_api_hash_here" SESSION_NAME = "channel_history_session" SOURCE_CHANNEL = "@your_source_channel" DEST_CHAT = "@your_destination_chat" async def fetch_and_forward(): async with Client(SESSION_NAME, API_ID, API_HASH) as app: # 遍历频道历史消息 async for message in app.get_chat_history(SOURCE_CHANNEL): # 转发消息 await app.forward_messages( chat_id=DEST_CHAT, from_chat_id=SOURCE_CHANNEL, message_id=message.id ) # 执行任务 app = Client(SESSION_NAME, API_ID, API_HASH) app.run(fetch_and_forward())
注意事项:
- 需要先在Telegram开发者平台注册应用,获取API ID和API Hash;
- 支持使用Bot Token登录(Telethon和Pyrogram均支持),但如果频道是私有频道,需要确保账号有访问权限。
内容的提问来源于stack exchange,提问作者user14973800
相关产品推荐
相关产品推荐

