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

调用Telegram getUpdates接口获取chat ID时报409错误如何解决?

问题原因及解决方案

错误原因

你遇到的409报错是Telegram Bot的机制限制导致的:

{"ok":false,"error_code":409,"description":"Conflict: can't use getUpdates method while webhook is active; use deleteWebhook to delete the webhook first"}
Telegram Bot不允许getUpdates长轮询接口和Webhook模式同时运行,当前你的Bot已经绑定了Webhook地址,所以调用getUpdates会被直接拒绝。

可行解决方法

根据你的后续使用场景选择对应方案即可:

场景1:仅临时调用getUpdates获取chat ID,后续仍需使用Webhook

先调用删除Webhook接口,用完getUpdates拿到ID后再重新绑定原有Webhook即可,两种Python实现方式如下:

  • 直接用requests调用原生接口:
import requests

BOT_TOKEN = "替换为你的Bot Token"

# 第一步:删除现有Webhook
del_webhook_resp = requests.get(f"https://api.telegram.org/bot{BOT_TOKEN}/deleteWebhook")
print("删除Webhook结果:", del_webhook_resp.json())

# 第二步:调用getUpdates获取chat ID
updates_resp = requests.get(f"https://api.telegram.org/bot{BOT_TOKEN}/getUpdates")
updates_data = updates_resp.json()
if updates_data["ok"]:
    # 遍历结果取chat ID,最新消息一般在列表末尾
    for update in updates_data["result"]:
        if "message" in update:
            chat_id = update["message"]["chat"]["id"]
            print(f"获取到的chat ID:{chat_id}")
            break

# 第三步(可选,需保留Webhook的话执行):重新绑定原有Webhook地址
# WEBHOOK_URL = "替换为你的原有Webhook回调地址"
# requests.get(f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook?url={WEBHOOK_URL}")
  • 用python-telegram-bot v20+库实现:
from telegram import Bot
import asyncio

BOT_TOKEN = "替换为你的Bot Token"

async def get_chat_id():
    bot = Bot(BOT_TOKEN)
    # 删除Webhook,drop_pending_updates参数可选是否丢弃未处理的更新
    await bot.delete_webhook(drop_pending_updates=True)
    # 获取更新列表
    updates = await bot.get_updates()
    for update in updates:
        if update.message:
            print(f"chat ID:{update.effective_chat.id}")
            break
    # 可选:重新设置Webhook
    # await bot.set_webhook(url="替换为你的Webhook地址")

asyncio.run(get_chat_id())

场景2:后续开发打算一直用长轮询模式,不需要Webhook

直接在代码初始化Bot的阶段增加删除Webhook的逻辑即可,后续就可以正常调用getUpdates接收消息,不需要再处理Webhook相关配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:48:03