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

使用requests.post调用Telegram Bot API出现403 Forbidden错误求助

问题解决:Telegram Bot API 403 Forbidden错误

代码问题修正

你的代码存在核心问题:发送POST请求时错误地将参数放在params中(会拼接在URL上),而Telegram Bot API的POST请求建议将参数放在请求体里。修改方式如下:

方案1:使用data参数传递请求体

import requests
def send(text, chat_id, api_token):
    params = {'chat_id': chat_id, 'text': text, 'parse_mode': 'HTML'}
    url = f'https://api.telegram.org/bot{api_token}/sendMessage'
    # 将params改为data参数传递请求体
    resp = requests.post(url, data=params)
    resp.raise_for_status()

send('Hello World!', chat_id, api_token)

方案2:使用json参数(更规范,支持复杂格式)

import requests
def send(text, chat_id, api_token):
    params = {'chat_id': chat_id, 'text': text, 'parse_mode': 'HTML'}
    url = f'https://api.telegram.org/bot{api_token}/sendMessage'
    # 使用json参数自动序列化并设置正确的请求头
    resp = requests.post(url, json=params)
    resp.raise_for_status()

send('Hello World!', chat_id, api_token)

其他可能的排查点

若修改代码后仍出现403错误,检查以下内容:

  • 确认chat_id正确性:chat_id为纯数字格式,超级群/频道的chat_id需带-100前缀。可通过访问https://api.telegram.org/bot<你的api_token>/getUpdates获取准确的chat_id,避免抄错。
  • 核对api_token:确保完全匹配BotFather提供的内容,格式为数字:随机字符串,无多余空格或符号。
  • 确认已与Bot发起对话:必须用目标账号给Bot发送过至少一条消息,否则Bot无法主动发消息,会返回403。
  • 检查网络环境:若所在地区无法直接访问Telegram API,需配置代理。示例:
proxies = {
    'http': 'http://your-proxy-address:port',
    'https': 'http://your-proxy-address:port'
}
resp = requests.post(url, json=params, proxies=proxies)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 15:32:46