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

如何通过USERID获取用户名?附获取USERID的代码示例

通过用户ID获取对应用户名的可行方法

你当前获取用户ID的代码是:

user = update.message.from_user
userid = user['id']

方法一:直接从已有的user对象提取

其实不需要单独转换ID,from_user对象本身就包含用户名相关字段,直接读取即可:

# 获取用户名(如果用户设置了)
username = user.get('username')
# 如果没有用户名,可使用昵称组合
full_name = f"{user.get('first_name', '')} {user.get('last_name', '')}".strip()

方法二:仅通过用户ID查询(无当前user对象时)

如果只有用户ID,没有上下文里的user对象,可以调用Telegram Bot API的getChat接口来获取用户信息:

# 假设使用python-telegram-bot v13+版本(异步写法)
chat = await bot.get_chat(userid)
username = chat.username
full_name = f"{chat.first_name} {chat.last_name}".strip() if chat.last_name else chat.first_name

注意事项:

  • 并非所有Telegram用户都会设置username,所以要做好字段为None的兼容处理,优先使用昵称组合作为备选。
  • 调用getChat需要确保bot有权限访问该用户信息(比如用户和bot有过对话互动)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:55:09