How can I disconnect the client just after I received a new message from a chat, in Telethon library

Viewed 295

I'm using telethon and for some reason, I need to use one session to connect and disconnect my client, so I want after receiving an event from a specific chat (one message from a specific bot), the client will disconnect, this is what I am doing...

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()

If I use await client.disconnect() It does not make any change and gives me sqlite3.OperationalError: database is locked probably I am doing some mistake.

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()
    
1 Answers

You can do:

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()
Related