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

如何用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:25:17