PythonAnywhere服务器无法接收Telegram Webhook更新求助
Telegram Webhook连接PythonAnywhere超时问题解决指南
问题现象
- 此前功能完全正常,更新代码仓库后,Telegram无法通过Webhook向PythonAnywhere服务器推送更新,
get_message函数完全未被调用 - 调用
getWebhookInfo返回连接超时,证书已确认无异常 - 尝试使用ngrok URL设置Webhook同样失败
相关代码
URL = 'name.pythonanywhere.com' app = Flask(__name__) bot.remove_webhook() bot.set_webhook(url=URL) bot.send_message(userID, 'helo') context = context.Context(default.Default()) @app.route('/', methods=['POST', 'GET']) def get_message(): update = types.Update.de_json(request.stream.read().decode('utf-8')) bot.process_new_updates([update]) return 'ok', 199
getWebhookInfo返回结果
{"ok":true,"result": {"url":"name.pythonanywhere.com", "has_custom_certificate":false, "pending_update_count":11, "last_error_date":1673875844, "last_error_message":"Connection timed out", "max_connections":40, "ip_address":"35.173.69.207"}}
排查与解决步骤
1. 修复Webhook URL的HTTPS前缀问题
Telegram强制要求Webhook必须使用HTTPS协议,你的URL缺少https://前缀,这是导致连接超时的核心原因。修改代码中的URL为:
URL = 'https://name.pythonanywhere.com'
重新设置Webhook即可。
2. 调整代码执行顺序与状态码
- 将Webhook的设置逻辑放到Flask应用启动的入口中,避免模块导入时重复执行:
if __name__ == '__main__': bot.remove_webhook() bot.set_webhook(url=URL) app.run() - 将返回状态码从199改为200,Telegram官方推荐使用200状态码确认接收成功:
return 'ok', 200
3. 检查PythonAnywhere应用状态
- 登录PythonAnywhere控制台,进入"Web"标签页,确认应用处于运行中状态,查看日志是否有启动报错
- 免费版PythonAnywhere应用长时间无访问会自动休眠,手动访问一次你的应用域名(
https://name.pythonanywhere.com)唤醒应用
4. ngrok失败的额外处理
- 使用ngrok时必须用生成的HTTPS地址(如
https://xxxx.ngrok.io),不能用HTTP - 确保ngrok映射的本地端口与Flask运行端口一致(Flask默认是5000,启动ngrok时执行
ngrok http 5000)
内容的提问来源于stack exchange,提问作者denikryt
相关产品推荐
相关产品推荐

