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

Telethon自动回复机器人部署Heroku后仅运行1分钟即停止的求助

解决Heroku上Telethon机器人运行1分钟停止的问题

核心问题:Web Dyno的休眠机制

Heroku的web类型dyno要求进程绑定端口并监听HTTP请求,否则会在1分钟后判定服务未启动并终止进程。你的机器人是后台服务,不需要HTTP监听,因此必须改用worker类型dyno。

步骤1:修改Procfile

将原Procfile内容替换为:

worker: python3 bot.py

步骤2:启用Worker Dyno

登录Heroku控制台进入你的应用:

  • 切换到「Resources」标签页
  • 找到「worker python3 bot.py」选项,开启对应的dyno(可关闭web dyno以节省资源)

代码中的问题修复

1. 会话文件路径错误

原代码中session_file = "TelegramClient('@alixam12')"是错误写法,TelegramClient的会话参数只需传入会话名称,修改为:

session_file = "alixam12"

2. 异步函数避免阻塞调用

time.sleep()是同步阻塞方法,会破坏Telethon的事件循环,替换为异步的asyncio.sleep(),同时导入asyncio库:

import asyncio

# 在handle_new_message函数中替换原time.sleep
await asyncio.sleep(0.001)

3. 完善登录流程

原代码未处理首次登录的验证逻辑,添加授权确保机器人能正常运行:

with client:
    if not client.is_user_authorized():
        client.send_code_request(phone_number)
        # 首次运行需手动输入验证码,后续会自动复用会话文件
        client.sign_in(phone_number, input("请输入验证码:"))
    client.run_until_disconnected()

4. 用环境变量存储敏感信息

不要硬编码api_id、api_hash等敏感内容,改用Heroku环境变量:

import os

api_id = int(os.getenv("API_ID"))
api_hash = os.getenv("API_HASH")
phone_number = os.getenv("PHONE_NUMBER")

在Heroku控制台「Settings」→「Config Vars」中添加上述变量即可。

最终修复后的代码示例

import time
import asyncio
import os
from telethon import TelegramClient, events

# 从环境变量读取敏感配置
api_id = int(os.getenv("API_ID"))
api_hash = os.getenv("API_HASH")
phone_number = os.getenv("PHONE_NUMBER")
session_file = "alixam12"
message = "Salom"

client = TelegramClient(session_file, api_id, api_hash, sequential_updates=True)

@client.on(events.NewMessage(incoming=True))
async def handle_new_message(event):
    if event.is_private:
        from_ = await event.client.get_entity(event.from_id)
        if not from_.bot:
            print(time.asctime(), '-', event.message)
            await asyncio.sleep(0.001)
            await event.respond(message)
    print(time.asctime(), '-', 'Bot ishlamoqda...')

with client:
    if not client.is_user_authorized():
        client.send_code_request(phone_number)
        client.sign_in(phone_number, input("请输入验证码:"))
    client.run_until_disconnected()
    print(time.asctime(), '-', 'stopped')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:30:57