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
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.
This is how I do it: