如何用python-telegram-bot控制新成员的消息历史可见性?
实现隐藏/显示新成员消息历史的方法
由于python-telegram-bot官方库暂未封装channels.togglePreHistoryHidden这个Telegram原生API端点,你可以通过Bot类的_raw_request方法直接调用该原生接口来实现需求,具体步骤如下:
核心实现代码
from telegram import Bot from telegram.error import TelegramError async def toggle_pre_history_hidden(bot: Bot, chat_id: int, hide_history: bool): # 获取正确的超级群/频道ID(普通群需转换为-100开头的格式) chat = await bot.get_chat(chat_id) channel_id = chat.id if chat.type in ["supergroup", "channel"] else None if not channel_id: raise ValueError("仅支持超级群或频道类型的聊天") # 构造API请求参数 request_params = { "channel": channel_id, "enabled": hide_history # True=隐藏历史,False=显示历史 } try: # 调用Telegram原生API端点 response = await bot._raw_request( method="channels.togglePreHistoryHidden", data=request_params ) return response except TelegramError as e: # 处理权限不足、无效ID等异常 print(f"调用失败: {e.message}") raise
关键注意事项
- 权限要求:机器人必须拥有该群组/频道的管理员权限,且需开启「更改群组信息」或对应管理权限,否则会触发权限不足错误。
- Chat ID格式:该接口仅支持超级群或频道,需确保传入的是
-100开头的完整聊天ID(可通过bot.get_chat(chat_id)获取正确ID)。 - 异步上下文:
_raw_request是异步方法,需在python-telegram-bot的异步框架中调用(比如在Application的handler函数内)。 - 错误处理:建议捕获
TelegramError异常,处理权限不足、无效聊天ID等常见问题。
内容的提问来源于stack exchange,提问作者sof
相关产品推荐
相关产品推荐

