【发布时间】:2021-05-05 18:30:49
【问题描述】:
我正在尝试在 python 中编写一个脚本来侦听机器人的“第一次回复”然后退出。因此,我创建了一个客户端实例,然后向 Bot 发送一条消息,现在我只想记录 bot 的第一个回复(可以忽略即将到来的回复),并将 bot 回复保存到回复变量。现在如何退出侦听器模式,以便在收到回复后做其他事情。我尝试了 client.disconnect() 和 client.disconnected() 但现在可以正常工作,或者我可能不知道如何正确使用这些方法。我是 Telethon API 的新手。
当我运行这个脚本时,我的电报中的一条消息被发送到 bot(BotFather) 然后 bot 发送回复
机器人父亲的回复
我可以帮助您创建和管理 Telegram 机器人。如果你是新手 Bot API,请看手册(https://core.telegram.org/bots)。
你可以通过发送这些命令来控制我:
/newbot - 创建一个新的机器人 /mybots - 编辑你的机器人 [beta]
编辑机器人 /setname - 更改机器人的名称 /setdescription - 更改机器人 描述 /setabouttext - 更改有关信息的机器人 /setuserpic - 更改 bot 个人资料照片 /setcommands - 更改命令列表 /deletebot - 删除一个机器人
机器人设置 /token - 生成授权令牌 /revoke - revoke bot 访问令牌 /setinline - 切换内联模式 (https://core.telegram.org/bots/inline) /setinlinegeo - 切换内联 位置请求 (https://core.telegram.org/bots/inline#location-based-results) /setinlinefeedback - 更改内联反馈 (https://core.telegram.org/bots/inline#collecting-feedback) 设置 /setjoingroups - 可以将您的机器人添加到组中吗? /setprivacy - 切换 分组隐私模式(https://core.telegram.org/bots#privacy-mode)
Games /mygames - 编辑您的游戏 (https://core.telegram.org/bots/games) [beta] /newgame - 创建一个新的 游戏 (https://core.telegram.org/bots/games) /listgames - 获取列表 你的游戏 /editgame - 编辑游戏 /deletegame - 删除现有的 游戏
这个回复被分配到回复变量中
但是我的脚本 仍在收听其他即将发生的事件。有什么方法可以从 我可以关闭这个连接。
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 = ' '
@client.on(events.NewMessage(chats='https://t.me/BotFather'))
async def NewMessageListener(event):
Reply = event.message.message
with client:
client.send_message("https://t.me/BotFather", "/start")
client.run_until_disconnected()
# Disconnect client to stop run_until_disconnected()
# Do other stuff!!!
【问题讨论】:
标签: python-3.x telethon