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

Telegram机器人发送消息报400错误:Bad Request: chat not found求助

解决Telegram机器人发送消息时的"Bad Request: chat not found"错误(400状态码)

问题场景

开发项目时需要发送未来3天内到期的提醒,使用Telegram机器人发送消息时返回400错误,错误信息为Bad Request: chat not found。但该Telegram ID在项目其他功能(如提醒创建、更新、完成时发消息)中可正常使用,消息长度、Markdown格式也已排查无问题。

相关代码

def send_message(message, id):
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    response = requests.post(url, data={
                "chat_id": id,
                "text": message,
                "parse_mode": "Markdown"
            })
    print("Telegram Response:", response.text)
    return response.status_code

def send_due_reminders():
    today = datetime.today().date()
    
    try:
        conn, cursor = database_con()

        # 1. Check last update date
        cursor.execute("SELECT * FROM update_mess WHERE id = %s", ('reminders',))
        result = cursor.fetchone()
        print(result)

        if result:
            last_updated = result[2]
            telegram_id = int(result[1])
        else:
            return "No 'reminders' row found in update_mess table."

        if last_updated == today:
            return "Reminders already sent today."

        if not telegram_id:
            return "Telegram ID is not set."

        # 2. Get due reminders
        threshold_date = today + timedelta(days=3)
        cursor.execute("""
            SELECT id, title, task_detail, due_date, assigned_to
            FROM reminders
            WHERE status = 'Pending' AND due_date <= %s
        """, (threshold_date,))
        reminders = cursor.fetchall()

        if not reminders:
            return "No due reminders within 3 days."

        # 3. Format and send message
        message = "🔔 Upcoming Reminders (Due in 3 Days)\n\n"
        for r in reminders:
            message += (
                f"📌 Title: {r[1]}\n"
                f"📝 Task: {r[2]}\n"
                f"👤 Assigned To: {r[4]}\n"
                f"📅 Due Date: {r[3]}\n\n"
            )

        print(len(message))

        response = send_message(telegram_id, message)

        if response == 200:
            status = "Reminders were sent to Telegram successfully!"
        else:
            status = f"Telegram send failed with status code: {response}"

        # 4. Update last_updated
        cursor.execute("UPDATE update_mess SET last_updated = %s WHERE id = %s", (today, 'reminders'))
        conn.commit()

        return status

    except Exception as err:
        return f"Error: {err}"

    finally:
        cursor.close()
        conn.close()

执行输出

('reminders', '62XXXXXXX', datetime.date(2025, 6, 2))
len of mess:652
Telegram Response: {"ok":false,"error_code":400,"description":"Bad Request: chat not found"}

已排查操作

  • 确认该Telegram ID在项目其他功能中可正常接收消息
  • 尝试改为纯文本消息,排除Markdown解析问题
  • 确认消息长度仅652字符,未超过Telegram 4096字符限制

解决方案

核心问题:函数参数传递顺序错误

send_message函数定义的参数顺序是(message, id),但在send_due_reminders中调用时,传入的是send_message(telegram_id, message)——把telegram_id当成了message参数,把message当成了chat_id参数,导致Telegram API收到的chat_id是一段长文本,自然找不到对应的聊天对象。

修正方法

方法1:调整函数调用的参数顺序
把调用代码改成:

response = send_message(message, telegram_id)

方法2:调整函数定义的参数顺序(更符合直觉)
修改send_message的定义,把chat_id放在前面:

def send_message(chat_id, message):
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    response = requests.post(url, data={
                "chat_id": chat_id,
                "text": message,
                "parse_mode": "Markdown"
            })
    print("Telegram Response:", response.text)
    return response.status_code

这样调用时send_message(telegram_id, message)就符合逻辑了。

额外验证建议

修正后可以单独调用send_message测试,传入正确的chat_id和简单文本,确认返回200状态码,再整合到业务逻辑中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 23:28:24