skip to Main Content

I have a problem with Telethon. I have a NewMessage() event listener, and it works just fine. But when exit the script with CTRL + C and start it again, it does not connect to the chat again.
I have to manually delete the connection in the Telegram app.

My question is:
How can I force the client to disconnect, when I press CTRL + C or when the program is closed.

from telethon import TelegramClient, events, sync
import globals, asyncio

client = TelegramClient('anon', 
globals.api_id, globals.api_hash)
@client.on(events.NewMessage(chats=globals.tLink))
async def my_event_handler(event):
    print(event.raw_text)

client.start()
client.run_until_disconnected()

2

Answers


  1. If you need to repeatedly restart the script, it might be reasonable to not create a separate/new session for every run. Try using None to not create a .session file, instead of creating an anon.session.

    client = TelegramClient(None, globals.api_id, globals.api_hash)
    
    Login or Signup to reply.
  2. This is how I do it:

    async def enviar():
       (code)
    
    async def main():
        global ME
        ME = await info_me();
        
        enviar_var = asyncio.create_task(enviar());
    
        await enviar_var;
        
            
    with client:
        try:
            client.loop.run_until_complete(main());
    
        except:
            print("Encerrando...");
            future = asyncio.Future();
            future.set_result("1");
            con.close();#I am using a SQLite database, you can ignore this line
            print("Adeus!");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search