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

使用Telebot开发管理机器人:如何通过用户名获取用户ID?

如何通过用户名获取Telegram用户ID(Telebot实现)

核心解决方案

你使用的bot.get_chat(username)是正确的方向,Telebot封装的这个方法对应Telegram API的getChat接口,只要用户名格式正确(带@前缀),就能返回包含用户ID的Chat对象。

正确代码示例

import telebot

bot = telebot.TeleBot("你的机器人Token")

def get_user_id_by_username(username):
    # 确保用户名带@前缀,不带则自动补上
    if not username.startswith('@'):
        username = f'@{username}'
    try:
        chat = bot.get_chat(username)
        # 用户ID存储在chat.id字段中
        return chat.id
    except telebot.apihelper.ApiTelegramException as e:
        # 处理异常:用户名不存在、用户未与机器人互动等情况
        print(f"获取失败:{e.description}")
        return None

# 调用示例
user_id = get_user_id_by_username("@test_user")
if user_id:
    print(f"用户ID:{user_id}")

常见失败原因说明

  • 用户名未带@前缀,Telegram API无法识别为用户名查询
  • 用户从未与你的机器人有过互动(比如没发过消息、没加入机器人所在群组),机器人无法获取该用户信息,会返回"Chat not found"错误
  • 机器人Token权限异常或被限制

替代方案(适用于群组场景)

如果get_chat无法满足需求,可通过机器人所在群组的成员列表匹配用户名获取ID,仅适用于用户在该群组内的情况:

def get_user_id_from_group(group_id, target_username):
    try:
        members = bot.get_chat_members(group_id)
        target_username = target_username.lstrip('@')
        for member in members:
            if member.user.username == target_username:
                return member.user.id
        print("群组中未找到该用户")
        return None
    except telebot.apihelper.ApiTelegramException as e:
        print(f"获取失败:{e.description}")
        return None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:57:05