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

部署于Heroku的Python Telegram Bot无法正常进入闲置状态问题求助

解决方案
  • 25分钟一次的随机请求大概率来自公网端口扫描器、全网爬虫,这类服务会批量探测Heroku公开应用域名,发送的测试请求会触发dyno的活跃判定,导致应用无法进入闲置状态。
  • 最直接的修复方式是修改web服务路由规则,仅处理Telegram官方发送的webhook请求,其余所有请求直接返回404,避免无效请求被计为活跃。修改后的代码如下:
import telegram.ext
import bot
from config import TOKEN, PORT
from flask import Flask, request, abort

app = Flask(__name__)
updater = telegram.ext.Updater(TOKEN, use_context=True)
disp = updater.dispatcher

# 原有业务逻辑保持不变
def start(update,context):
    id = update.message.chat.id
    if(id == (hidden) or id == (hidden)):
        update.message.reply_text("Welcome! to Football Story Bot")
    else:
        update.message.reply_text("""
            We have detected unusual request from your device.
You have been banned from the service until further notice,
        """)

def help(update,context):
    id = update.message.chat.id
    if(id == (hidden) or id == (hidden)):
        update.message.reply_text("""
        The following commands are available:
        /start -> Welcome Message
        /help -> This Message
        /streams -> list of matches
        """)
    else:
        update.message.reply_text("""
            We have detected unusual request from your device.
You have been banned from the service until further notice,
        """)


def streams(update,context):
    id = update.message.chat.id
    if(id == (hidden) or id == (hidden)):
        update.message.reply_text("Searching for available matches")
        all_matches_name_list = bot.all_matches_name()
        link_str=''
        if(all_matches_name_list==None):
            update.message.reply_text("We are experiencing problem.Try again later, if problem persists then contact admin")
            return None
        for links in all_matches_name_list:
            link_str+=links+'\n'
        update.message.reply_text(link_str)
        update.message.reply_text("End Of Detected Matches")
    else:
        update.message.reply_text("""
            We have detected unusual request from your device.
You have been banned from the service until further notice,
        """)

def handle_message(update,context):
    id = update.message.chat.id
    if(id == (hidden) or id == (hidden)):
        update.message.reply_text("Searching for available streams")
        link_str=''
        sending_message=''
        for chars in update.message.text:
            if(chars=='@'):
                break
            sending_message+=chars
        individual_link = bot.selected_match(bot.all_matches_name(),sending_message)
        if(individual_link==None):
            update.message.reply_text("We are experiencing problem.Try again later, if problem persists then contact admin hai tw")
            return None
        if(len(individual_link)==0):
            update.message.reply_text("No links found. Links are updated 30min before match. If link is not found till Kick Off then contact admin")
            return None
        for links in individual_link:
            link_str+=links+'\n\n'
        update.message.reply_text(link_str)
        update.message.reply_text("End Of Streaming Links")
    else:
        update.message.reply_text("""
            We have detected unusual request from your device.
You have been banned from the service until further notice,
        """)

# 仅处理Telegram发送的POST格式webhook请求
@app.route(f'/{TOKEN}', methods=['POST'])
def webhook():
    update = telegram.Update.de_json(request.get_json(force=True), updater.bot)
    disp.process_update(update)
    return 'ok', 200

# 捕获所有其他路径的请求,直接返回404
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    # 如需定位请求来源,可取消下一行注释,在日志中查看请求信息
    # print(f"请求来源IP:{request.remote_addr},请求路径:{path},UA:{request.user_agent}")
    abort(404)

if __name__ == '__main__':
    updater.bot.set_webhook(url=f"你的应用域名{TOKEN}")
    app.run(host='0.0.0.0', port=PORT)
  • 部署前需要在requirements.txt中添加flask依赖。
  • 若需定位请求来源,也可以直接在Heroku应用控制台的日志面板查看所有请求记录,即可找到发送探测请求的主体。
  • 修改完成后,只有实际的用户消息请求会触发应用逻辑,无效探测请求不会被计入活跃判定,应用就可以正常在30分钟无活动后进入闲置状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:24:04