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

部署python-telegram-bot到Heroku后无响应的解决方法

解决Heroku部署Telegram Bot无响应问题

问题背景

使用Python 3.11.2和python-telegram-bot==20.2库在Heroku部署Telegram Bot后,Bot在Telegram中对任何操作均无响应。

具体修复步骤

1. 修正Procfile入口文件

你的Procfile指定启动的是get_news_from_reddit.py,但实际Bot的入口文件是send_news_to_channel.py,这会导致Heroku启动的不是Bot程序,自然无法响应。

修改Procfile内容为:

web: python3 send_news_to_channel.py

2. 确认环境变量配置

本地的.env文件不会被推送到Heroku,必须在Heroku应用的后台设置中手动添加TG_BOT_TOKEN环境变量,确保Bot能正确获取令牌。

3. 完善Webhook运行逻辑

当前代码启动Webhook后会直接退出,需要添加application.idle()维持程序运行,同时确认Webhook的域名与Heroku提供的应用域名一致:

def main():
    token = os.getenv("TG_BOT_TOKEN")
    application = Application.builder().token(token).build()
    application.add_handler(CommandHandler("most_popular_post", send_reddit_post))
    application.add_handler(CommandHandler("start", wake_up))
    
    application.start_webhook(
        listen="0.0.0.0",
        port=int(PORT),
        url_path=token,
    )
    application.bot.setWebhook('https://safe-chamber-19168.herokuapp.com/' + token)
    
    # 添加该行维持程序运行
    application.idle()

4. 检查依赖清单

确保requirements.txt包含所有必要依赖,至少需要:

python-telegram-bot==20.2
python-dotenv

5. 重新部署并验证

执行以下命令重新部署:

git add .
git commit -m 'fix Procfile and runtime logic'
git push heroku master
heroku ps:scale web=1

部署完成后,通过日志确认程序无报错:

heroku logs --tail

若日志显示Running on http://0.0.0.0:xxxx且无异常,再测试Bot的/start命令。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:03:26