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

如何用Telegram Bot向网站发送POST请求?代码故障排查

问题分析与修复

核心错误点

  • 消息处理器冲突:两个content_types=['text']的处理器会匹配所有文本消息。用户发/fill时,start和handler会同时执行,误将/fill作为参数发送POST请求;日常文本也会触发不必要的请求。
  • 无状态管理:Bot无法区分用户是在响应/fill的输入,还是发送普通消息。
  • 错误处理缺失:未捕获网络请求异常(如连接失败、超时),仅靠状态码无法定位真实问题。

修复后的代码

import requests
import telebot
from telebot import types

token = '***********************'
bot = telebot.TeleBot(token)

# 用字典存储用户状态,标记是否等待输入分数
user_states = {}

@bot.message_handler(content_types=['text'])
def handle_all_text(message):
    chat_id = message.chat.id
    # 处理/fill指令
    if message.text == '/fill':
        user_states[chat_id] = 'waiting_for_score'
        bot.send_message(chat_id, "Please write user's score.")
        return
    
    # 检查用户是否处于等待输入分数的状态
    if user_states.get(chat_id) == 'waiting_for_score':
        try:
            url = 'https://site.ru/assets/requesthandler.php'
            post_params = {'action': 'setParamValue', 'value': message.text}
            # 可根据需求添加headers,比如模拟浏览器请求
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            resp = requests.post(url, data=post_params, headers=headers, timeout=10)
            resp.raise_for_status()  # 抛出HTTP错误状态码对应的异常
            bot.send_message(chat_id, "Data saved successfully.")
        except requests.exceptions.RequestException as e:
            # 发送具体错误信息便于调试
            bot.send_message(chat_id, f"Error: {str(e)}")
        finally:
            # 重置用户状态
            del user_states[chat_id]
        return
    
    # 处理其他普通文本消息
    bot.send_message(chat_id, "Unknown command. Use /fill to start.")

bot.polling()

关键修改说明

  1. 状态管理:用user_states字典记录用户是否处于等待输入分数的状态,确保只有在/fill指令后发送的文本才会触发POST请求。
  2. 合并处理器:将所有文本消息处理逻辑合并到一个函数中,避免处理器冲突。
  3. 增强错误处理:添加try-except捕获所有请求异常,并用resp.raise_for_status()主动抛出HTTP错误,同时将具体错误信息返回给用户,方便调试。
  4. 可选Headers:添加浏览器UA头,部分服务器会拒绝无UA的请求,可根据目标网站实际情况调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:40:59