MmDYi
MmDYi

Reputation: 61

Telethon automatic reconnecting

Hi there I have an idea for this script as usaull telethon libary when the system internet was dissconnect (not isp) it will try for 5 time(s) , I want to increase the number of trying to reconnect for exmple for many times or a infinity loop for trying to reconnect .this is my code if the internet was dissconnet telethon trying to reconnect for 5 times I want increase that as infinity loop

from config import configuration
from telethon.sync import TelegramClient, events


client = TelegramClient('anon', configuration["api_id"], configuration["api_hash"])

print('please wait this action take a less than minute'.title())

with client:
    for dialog in client.iter_dialogs():
        if dialog.is_channel:
            if dialog.name == configuration["send_channel"]:
                channel_id = dialog.id
                break

print('start'.title())


@client.on(events.NewMessage(chats=configuration["monitoring_channel"]))
async def my_event_handler(event):
    print(event.raw_text)
    await client.send_message(entity=channel_id, message=event.message)


client.start()
client.run_until_disconnected()

enter image description here

Upvotes: 1

Views: 1413

Answers (1)

gerda die gandalfziege
gerda die gandalfziege

Reputation: 762

This code retries to connect again if the connection failed.

from config import configuration
from telethon.sync import TelegramClient, events


client = TelegramClient('anon', configuration["api_id"], configuration["api_hash"])

print('please wait this action take a less than minute'.title())

with client:

    for dialog in client.iter_dialogs():

        if dialog.is_channel and dialog.name == configuration["send_channel"]:

            channel_id = dialog.id

            break

print('start'.title())


@client.on(events.NewMessage(chats=configuration["monitoring_channel"]))
async def my_event_handler(event):
    print(event.raw_text)
    await client.send_message(entity=channel_id, message=event.message)


def test():
    
    try:

        client.start()
        client.run_until_disconnected()

    except ConnectionError: #catches the ConnectionError and starts the connections process again

        print('ConnectionError')
        test()

Upvotes: 3

Related Questions