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

如何在Python中通过telebot库从用户名获取chat_id?

解决Telebot通过用户名获取Chat ID并发送消息的问题

错误原因

出现Bad Request: chat not found的核心原因是:Telegram API不允许机器人主动给从未互动过的用户发消息,也无法通过用户名获取这类用户的Chat ID。只有当用户先给机器人发送过至少一条消息(包括通过启动链接发送的/start命令),Telegram才会记录机器人与该用户的对话关系,此时才能正常调用get_chat()或直接用用户名发消息。

可行解决方案

1. 确保用户已与机器人建立互动

要求目标用户列表中的每个用户,先给机器人发送任意一条消息,或者点击机器人的启动链接(格式:https://t.me/你的机器人用户名?start=任意内容),触发对话关系建立。

2. 正确实现通过用户名获取Chat ID的函数

如果用户已完成互动,可使用以下代码安全获取Chat ID:

import telebot
bot = telebot.TeleBot("你的BOT_TOKEN")

def get_chat_id(username):
    # 统一处理用户名格式(带@或不带都兼容)
    target_username = username if username.startswith("@") else f"@{username}"
    try:
        chat_info = bot.get_chat(target_username)
        return chat_info.id
    except telebot.apihelper.ApiTelegramException as e:
        print(f"获取用户{target_username}的Chat ID失败: {str(e)}")
        return None

# 批量处理示例
username_list = ["keiru", "user2", "@user3"]
for username in username_list:
    chat_id = get_chat_id(username)
    if chat_id:
        bot.send_message(chat_id, "批量发送的消息内容")

3. 备选方案:主动引导用户建立互动

如果无法让用户主动发消息,可生成专属启动链接发给用户,用户点击后会自动向机器人发送/start命令,此时机器人可在/start命令的处理函数中记录用户的Chat ID:

@bot.message_handler(commands=['start'])
def handle_start(message):
    user_id = message.chat.id
    username = message.chat.username
    # 将user_id和username存储到数据库或文件中
    with open("user_chat_ids.txt", "a") as f:
        f.write(f"{username}:{user_id}\n")
    bot.reply_to(message, "欢迎使用!之后我会给你发送消息。")

# 启动机器人轮询
bot.polling()

后续需要发消息时,直接从存储的文件/数据库中读取Chat ID即可。

4. 优化建议

  • 把获取到的Chat ID持久化存储(如JSON文件、SQLite数据库),避免每次发送都调用get_chat(),提升效率并减少API请求次数。
  • 处理异常情况:比如用户名不存在、用户已拉黑机器人等,避免程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:05:09