【问题标题】:How can I disconnect the client just after I received a new message from a chat, in Telethon library如何在 Telethon 库中收到来自聊天的新消息后立即断开客户端
【发布时间】:2021-09-20 00:13:59
【问题描述】:

我正在使用 Telethon,出于某种原因,我需要使用一个会话来连接和断开我的客户端,所以我希望在收到来自特定聊天的事件(来自特定机器人的一条消息)后,客户端将断开连接,这就是我正在做的……

bot_id = "chat id of telegram bot"

await client.connect()

        @client.on(events.NewMessage(chats=bot_id))
        async def imp_msg(event):
            # print(event)
            await client.send_message(123456, event.message)

        await client.start()

如果我使用 await client.disconnect() 它不会做任何更改并给我sqlite3.OperationalError: database is locked 可能我做错了。

await client.connect()

    @client.on(events.NewMessage(chats=bot_id))
    async def imp_msg(event):
        # print(event)
        await client.send_message(123456, event.message)
        await client.disconnect()

    await client.start()
    

【问题讨论】:

标签: python python-3.x asynchronous telethon


【解决方案1】:

你可以这样做:

client = TelegramClient('session',api_id,api_hash)

async with client:
     print('Connected')
     @client.on(events.NewMessage(chats=bot_id))
     async def imp_msg(event):
         await client.send_message(123456, event.message)
         await client.disconnect()
     await client.run_until_disconnected()

【讨论】:

    猜你喜欢
    • 2012-06-04
    • 1970-01-01
    • 2022-01-17
    • 2019-11-09
    • 2022-06-16
    • 2015-03-28
    • 2016-07-26
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多