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

集成ChatFAI的Telegram Bot无法调用API获取响应问题排查

排查Telegram Bot集成ChatFAI API无响应问题

你开发的Telegram Bot已按ChatFAI官方文档配置,但调用API无法获取返回结果,结合提供的代码,可从以下几个方向排查问题:


1. 补充详细错误日志,定位API调用问题

当前代码仅通过状态码判断结果,未输出API返回的具体错误信息,无法精准定位问题。建议修改handle_message函数的错误分支,打印状态码和响应内容:

else:
    # 打印详细错误信息用于排查
    print(f"API请求失败,状态码: {response.status_code}")
    print(f"错误响应内容: {response.text}")
    bot.send_message(message.chat.id, f"API调用出错,状态码: {response.status_code}", disable_notification=True)

通过这些日志,能直接看到API返回的权限错误、参数错误等具体提示。

2. 验证ChatFAI API参数与端点合法性

  • 检查character_id:确认该ID完全匹配ChatFAI后台的角色ID,注意大小写、拼写是否有误。
  • 确认端点要求:部分版本的ChatFAI /chat 端点可能需要session_id参数维持会话上下文,若官方文档有此要求,需在payload中添加该参数,或从首次API响应中获取session_id并在后续请求中复用。
  • 直接用curl测试API:跳过Telegram Bot逻辑,用curl命令直接调用API,验证密钥和参数是否有效:
curl -X POST https://api.chatfai.com/v1/chat \
-H "Authorization: Bearer YOUR_CHATFAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "messages": [{"sender": "user", "content": "Hello"}],
    "character_id": "YOUR_CHATFAI_CHARACTER_ID"
}'

如果curl请求也失败,说明问题出在密钥、角色ID或API权限上,而非代码逻辑。

3. 增加网络异常捕获

当前代码未处理requests库的网络异常(如连接超时、DNS解析失败等),这类异常会直接导致代码中断,无法执行后续错误提示逻辑。建议添加try-except块:

def handle_message(message):
    headers = {
        "Authorization": f"Bearer {chatfai_api_key}",
        "Content-Type": "application/json"
    }

    payload = {
        "messages": [
            {"sender": "user", "content": message.text}
        ],
        "character_id": chatfai_character_id
    }

    try:
        response = requests.post(chatfai_chat_endpoint, headers=headers, json=payload, timeout=10)
        response.raise_for_status()  # 主动触发HTTP错误异常

        data = response.json()
        if "messages" in data:
            messages = data["messages"]
            if messages:
                response_text = messages[-1]["content"]
                bot.send_message(message.chat.id, response_text, disable_notification=True)
            else:
                bot.send_message(message.chat.id, "Oops! I didn't get a response from the ChatFAI API.", disable_notification=True)
        else:
            bot.send_message(message.chat.id, "Oops! Invalid response from the ChatFAI API.", disable_notification=True)
    except requests.exceptions.RequestException as e:
        print(f"请求异常: {str(e)}")
        bot.send_message(message.chat.id, f"请求ChatFAI API时出现异常: {str(e)}", disable_notification=True)

4. 确认Telegram Bot消息处理逻辑有效性

在handle_message函数开头添加print(message.text),验证函数是否能正常接收用户消息,避免因其他message_handler优先级更高导致该函数未被触发。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:15:19