You need to enable JavaScript to run this app. Telethon Python脚本中捕获BotFather首条回复后如何正确断开Telegram客户端
优惠活动
大模型
产品
解决方案
定价
更多

Telethon Python脚本中捕获BotFather首条回复后如何正确断开Telegram客户端

问题根源梳理
  • 作用域问题:事件回调内没有对全局Reply变量做global声明,直接赋值的内容属于函数局部变量,外层根本读不到修改后的值
  • 断连逻辑缺失:收到目标消息后没有主动触发客户端断开流程,run_until_disconnected()会一直阻塞等待连接断开,自然无法进入后续业务逻辑
  • 方法误用:
    • client.disconnect()是异步协程方法,必须在异步上下文内通过await调用才能真正执行断连,同步直接调用只会返回协程对象,不会有实际效果
    • client.disconnected()是返回当前连接状态的布尔属性,不是用来主动断连的操作方法,之前的用法从定义上就错了
可直接运行的修正代码
import random
import traceback
import configparser
from telethon import TelegramClient, events, sync
from telethon.errors import SessionPasswordNeededError
from telethon.errors.rpcerrorlist import PeerFloodError
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.functions.messages import GetDialogsRequest,GetHistoryRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser, PeerChannel

api_id =  # 替换为你的Api_ID
api_hash = # 替换为你的Api_Hash
phone = # 替换为你的session标识
client = TelegramClient(phone, api_id, api_hash)
Reply = ' '
# 标记位,确保只捕获第一条回复
got_first_reply = False

@client.on(events.NewMessage(chats='@BotFather'))
async def NewMessageListener(event):
    global Reply, got_first_reply
    # 已拿到第一条回复则直接跳过后续消息处理
    if got_first_reply:
        return
    # 存储第一条回复内容
    Reply = event.message.message
    got_first_reply = True
    # 异步触发客户端断连,结束事件阻塞
    await client.disconnect()

with client:
    # 向BotFather发送/start指令
    client.send_message('@BotFather', '/start')
    # 阻塞等待客户端主动断连后自动退出
    client.run_until_disconnected()

# 断连后即可正常执行后续其他逻辑
print("捕获到的BotFather回复:", Reply)
# Do other stuff!!!
实现逻辑说明
  • 收到BotFather的第一条消息时,立刻将内容存入全局Reply变量,之后主动调用await client.disconnect()断开客户端连接
  • 连接断开后,原本阻塞的client.run_until_disconnected()会自动返回,脚本流程会进入后续的业务逻辑段,不会再持续监听新消息
  • 标记位可以避免BotFather连续推送多条通知时,重复覆盖Reply的内容,确保只保存第一条收到的回复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 22:27:06