【问题标题】:Telethon do something if no messages arrive如果没有消息到达,Telethon 会做一些事情
【发布时间】:2021-12-10 09:54:53
【问题描述】:

这段代码让 python 同步等待消息。 有没有什么方法可以在没有收到电话信息时每隔一段时间运行一个函数?

async def main():
    me = await client.get_me()
    print(me.stringify())
    @client.on(events.NewMessage('TelegramID'))
    async def new_message_listener(event):
        mensaje = event.message.message
        if mensaje != None:
           print(mensaje)

我希望它每 10 分钟不接收消息就做一些事情,而不会停止等待接收新消息。

【问题讨论】:

    标签: python python-3.x for-loop python-asyncio telethon


    【解决方案1】:

    只要 asyncio 事件循环在运行,就会收到消息。这意味着您可以执行以下操作,并且它仍然可以工作:

    import asyncio  # <- new
    
    async def main():
        me = await client.get_me()
        print(me.stringify())
        @client.on(events.NewMessage('TelegramID'))
        async def new_message_listener(event):
            mensaje = event.message.message
            if mensaje != None:
               print(mensaje)
    
        while client.is_connected():  # <- new
            await asyncio.sleep(10 * 60)
            # do something else every 10 minutes...
    

    【讨论】:

    • 谢谢,它运行良好。很好的说明
    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2021-12-30
    • 2011-12-02
    相关资源
    最近更新 更多