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

Python Telegram Bot使用User ID提及无用户名用户的实现问题

问题原因

你现有代码存在3个核心错误导致无用户名用户无法被正常提及:

  • 无用户名场景下,你已经拼接了[用户名](tg://user?id=xxx)的Markdown提及语法,但后续构造消息文本时额外加了@前缀,破坏了Markdown格式
  • 调用send_message方法时没有传入parse_mode参数,Telegram服务端不会解析你拼接的Markdown提及语法
  • 未对用户名里的Markdown特殊字符做转义,可能触发格式解析失败

修正后代码

from telegram.utils.helpers import escape_markdown

def welcome(update, context, new_member):
    # 问候入群的新用户
    message = update.message
    chat_id = message.chat.id
    # 统一处理用户提及格式
    if new_member.username:
        # 有用户名的情况直接用@提及
        mention = f"@{escape_markdown(new_member.username)}"
    else:
        # 无用户名的情况用ID构造Markdown提及
        escaped_first_name = escape_markdown(new_member.first_name)
        mention = f"[{escaped_first_name}](tg://user?id={new_member.id})"
    
    logger.info(
        "%s joined to chat %d (%s)",
        escape(mention),
        chat_id,
        escape(message.chat.title),
    )

    text = (
        f"Hello {mention}! Welcome to the {escape_markdown(message.chat.title)} "
        "telegram group!\n"
        "Please introduce yourself."
    )

    # 传入parse_mode参数让服务端解析Markdown格式
    context.bot.send_message(chat_id=chat_id, text=text, parse_mode='Markdown')

改动说明

  • 移除了消息文本中额外添加的@前缀,针对有无用户名的场景单独构造合规的提及格式
  • 新增了escape_markdown对用户输入的名字、群名做转义,避免特殊字符导致Markdown解析失败
  • 在send_message调用中添加了parse_mode='Markdown'参数,触发Telegram服务端解析提及语法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 16:42:00