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

如何让Telegram深度链接在Python-Telegram-Bot中正常跳转消息?

问题分析与解决

你遇到的核心问题是Telegram深度链接的格式没有根据聊天类型区分,tg://privatepost仅适用于频道和超级群组,普通群组或私人聊天需要用另一种链接格式。

为什么之前Telethon能用?

大概率是你之前测试的场景都是频道/超级群组,刚好匹配privatepost的适用范围;切换到Python-Telegram-Bot后,测试环境换成了普通群组,导致链接失效。

正确的深度链接规则

Telegram的深度链接分两种场景:

  • 频道/超级群组:用tg://privatepost?channel={原始ID}&post={消息ID},这里的原始ID是去掉-100前缀的数字(比如-100123456789取123456789)
  • 普通群组/私人聊天:用tg://openmessage?chat_id={完整聊天ID}&message_id={消息ID},这里的完整聊天ID要保留负号(比如普通群组的-12345678,私人聊天的12345678)

修正后的代码示例

修改你的链接生成函数,加入聊天类型判断:

def message_mention(text: str, chat_id: int, message_id: int, chat_type: str, escape: EscapeType | None = 'html'):
    text = escape_string(text, escape)
    if chat_id is None or message_id is None:
        return text

    chat_id_str = str(chat_id)
    # 根据聊天类型选择链接格式
    if chat_type in ['supergroup', 'channel']:
        # 频道/超级群组用privatepost,去掉-100前缀
        if chat_id_str.startswith('-100'):
            channel_id = chat_id_str[4:]
        else:
            channel_id = chat_id_str.lstrip('-')
        return f'<a href="tg://privatepost?channel={channel_id}&post={message_id}&single">{text}</a>'
    else:
        # 普通群组/私人聊天用openmessage,保留完整chat_id
        return f'<a href="tg://openmessage?chat_id={chat_id}&message_id={message_id}">{text}</a>'

在调用时传入聊天类型:

async def handler(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    chat_id = update.effective_chat.id
    message_id = update.effective_message.id
    chat_type = update.effective_chat.type

    mention = message_mention(
        "当前活跃游戏", 
        chat_id=chat_id, 
        message_id=message_id, 
        chat_type=chat_type
    )
    # 后续发送消息逻辑...

验证要点

  1. 确认聊天类型:用update.effective_chat.type可以获取到private/group/supergroup/channel四种类型
  2. 普通群组测试:用tg://openmessage链接后,应该能直接跳转到对应消息
  3. 频道/超级群组测试:用privatepost链接,确保channel参数是去掉-100后的纯数字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:05:56