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

pyTelegramBotAPI在PythonAnywhere配置Webhook报错:需HTTPS链接,如何解决?

解决Telegram Webhook的"bad webhook: An HTTPS URL must be provided"报错

1. 把HTTP URL换成HTTPS

Telegram的Webhook强制要求使用HTTPS协议,你代码里写的http://NAME.pythonanywhere.com不符合要求,直接改成https://NAME.pythonanywhere.com就行。修改这行代码:

bot.set_webhook("https://NAME.pythonanywhere.com/{}".format(secret), max_connections=1)

2. 修复代码里的其他小bug

你的代码还有几处会导致运行失败的问题,得一起修正:

  • 缺少ApiTelegramException的导入:在代码开头添加from telebot.apihelper import ApiTelegramException
  • webhook函数里的flask.request要改成request:你已经导入了from flask import request,直接用request即可
  • 异常处理中的message变量未定义:原代码想打印被拉黑的用户信息,但message没有传入方法内,暂时可以先打印异常内容,后续再调整逻辑

修正后的完整代码示例:

import telebot
from telebot import types, TeleBot
from telebot.apihelper import ApiTelegramException
from flask import Flask, request, abort


class Exception_Handler:
    def handle(self, e: Exception):
        if isinstance(e, ApiTelegramException):
            if e.description == "Forbidden: bot was blocked by the user":
                # 原代码的message未定义,先打印异常信息
                print(f"用户已阻止机器人:{e}")


secret = "RANDOM_NUMBER"
bot: TeleBot = telebot.TeleBot('TOKEN', threaded=False, exception_handler=Exception_Handler())
# 替换为HTTPS地址
bot.set_webhook(f"https://NAME.pythonanywhere.com/{secret}", max_connections=1)

app = Flask(__name__)
@app.route(f'/{secret}', methods=["POST"])
def webhook():
    if request.headers.get('content-type') == 'application/json':
        json_string = request.get_data().decode('utf-8')
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
        return ''
    else:
        abort(403)

3. 关于PythonAnywhere的证书问题

PythonAnywhere为所有默认域名(比如NAME.pythonanywhere.com)都配置了Telegram信任的免费SSL证书,你完全不需要自己获取或配置证书。只要使用HTTPS的URL,Telegram就能正常完成证书验证,不需要额外传入证书相关参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:40:29