【问题标题】:python telethon wait for replypython Telethon 等待回复
【发布时间】:2021-03-20 15:33:46
【问题描述】:

我目前有代码可以向我的朋友发送消息

但我怎么知道他是否回复

这是我当前的代码

请看注释行

from telethon import TelegramClient

api_id = '1234567'
api_hash = 'MYHASH'
client = TelegramClient('session', api_id, api_hash)
client.start(phone_number)
destination_user_username='friend'
entity=client.get_entity(destination_user_username)
client.send_message(entity=entity,message="hello")
#if he reply hi
client.send_message(entity=entity,message="have a nice day")

我该怎么做?

【问题讨论】:

  • 您能否为您的问题提供更多背景信息?你的“客户”是什么?提供足够的上下文以使某人可以获取您编写的内容并至少自行运行其中的一部分以尝试提供解决方案,这通常会帮助您更快地获得答案。
  • 我编辑它请帮助我
  • 是的,它是一个包
  • 那么在您将python telethon telegram reply 放入搜索引擎并查看the example code on GitHub that comes up near the top 之后发生了什么?我假设您尝试基于此编写一些代码,或者甚至可能只是按原样使用该项目(根据其自述文件),但我在您的问题中没有看到任何相关内容。

标签: python telethon


【解决方案1】:

我在doc找到了

解决方案1

for message in client.iter_messages(chat):
    print(message)

解决方案2

api_id = '1234567'
api_hash = 'MYHASH'
with TelegramClient('session') as client:
    destination_user_username='friend'
    entity=client.get_entity(destination_user_username)
    client.send_message(entity=entity,message="hello")

    from telethon import events
    @client.on(events.NewMessage(pattern='hi'))
    async def handler(event):
        # here received messgae, do something with event
        print(dir(event)) # check all possible methods/operations/attributes
        # reply once and then disconnect
        await event.reply("have a nice day")
        await client.disconnect()

    client.run_until_disconnected()

【讨论】:

  • 非常感谢朋友解决方案2的作品。但它不会停止。我只想等待 1 条回复
  • 第二个解决方案怎么样,我没有仔细检查文档,但是您似乎可以从event对象中获取所有信息,例如检查发件人,检查收到的消息,一个您需要注意的方式是必须使用 await 调用某些事件方法
  • 一个简单的方法是在函数末尾添加一个raise ValueError,但可能有一些合法的方法可以使用await client.disconnect()之类的代码结束事件循环。
  • 你自己去查文档吧,我之前没用过电话,只是快速扫了一眼文档。
  • 对不起,我也是第一次
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 2021-12-19
相关资源
最近更新 更多