Telegram accounts get banned when using Telethon

Question:

After the start of the bans of accounts connected to my project, I changed the system for receiving new messages in the telegram account. Previously, I implemented it through a handler, now it is possible to connect several accounts, performing actions with unread messages on each one in turn. Code:

async def start_wtf_blyat():
global client, current_session_account
while True:
    for cl in clients:
        current_session_account = cl[0]
        client = cl[1]
        print(f'Choosing {current_session_account.session_name}')

        if current_session_account.start_time is not None:
            if current_session_account.start_time > dt.datetime.utcnow():
                print(
                    f"{current_session_account.session_name}: {current_session_account.start_time.strftime('%d.%m.%Y %H:%M:%S')} > {dt.datetime.utcnow().strftime('%d.%m.%Y %H:%M:%S')}")
                s_d = (current_session_account.start_time - dt.datetime.utcnow().replace(
                    microsecond=0)) * random.randrange(
                    1, 3)
                print(f'{current_session_account.session_name} needs to sleep {s_d.seconds} seconds')
                await asyncio.sleep(s_d.seconds)
                print(f'{current_session_account.session_name}: Sleep complete!')
        current_session_account.start_time = dt.datetime.utcnow().replace(microsecond=0)

        current_session_account.activate()

        async with client:
            print(f'Starting {current_session_account.session_name}')
            await check_news()

        print(
            f'{current_session_account.session_name}: Work complete! END: {current_session_account.end_time.strftime("%d.%m.%Y %H:%M:%S")}')

Then the necessary messages are selected in the check_news():

async def check_news():
global current_session_account, ME
ME = await client.get_me()

await asyncio.sleep(random.randrange(1, 5, 1))
# try:
x = [[d.unread_count, d.entity.id, d.title] for d in await client.get_dialogs() if
     not getattr(d.entity, 'is_private', False) and type(d.entity) == Channel
     and d.unread_count != 0 and d.entity.id in INPUT_CHANNELS_IDS]

if not x:
    rnd_sleep = random.randrange(180, 300)
    print(f'{current_session_account.session_name}: No channels, sleep for {rnd_sleep} seconds')

    end_time = dt.datetime.utcnow().replace(microsecond=0)

    start_time = current_session_account.start_time

    if start_time is not None:
        if start_time < end_time:
            delta = end_time - start_time + dt.timedelta(seconds=rnd_sleep)
    else:
        delta = dt.timedelta(seconds=rnd_sleep)

    print(f'{current_session_account.session_name} START: {start_time.strftime("%d.%m.%Y %H:%M:%S")}, '
          f'END: {end_time.strftime("%d.%m.%Y %H:%M:%S")}, '
          f'DELTA: {delta}, '
          f'NEXT START {(end_time + delta).strftime("%d.%m.%Y %H:%M:%S")}')

    current_session_account.set_times(delta)
    current_session_account.deactivate()
    return

for da in x:
    print(f'{current_session_account.session_name}: {x.index(da) + 1} of {len(x)}')

    await asyncio.sleep(random.randrange(1, 5, 1))

    async for msg in client.iter_messages(da[1], limit=da[0]):
        await asyncio.sleep(random.randrange(3, 5, 1))
        await msg.mark_read()

        if msg.text is None:
            continue

        comm_result_true = await Magic.detect_commercial(msg.text)
        antiplagiat_result = await antiplagiat(msg)

        if not comm_result_true and antiplagiat_result:
            await send_this_post(msg, da[1])
        else:
            print(f'{current_session_account.session_name}: Commercial or plagiat!')

# finally:

end_time = dt.datetime.utcnow().replace(microsecond=0)

start_time = current_session_account.start_time

if start_time is not None:
    if start_time < end_time:
        delta = end_time - start_time + dt.timedelta(seconds=1)
else:
    delta = dt.timedelta(seconds=2)

print(f'{current_session_account.session_name} START: {start_time.strftime("%d.%m.%Y %H:%M:%S")}, '
      f'END: {end_time.strftime("%d.%m.%Y %H:%M:%S")}, '
      f'DELTA: {delta}, '
      f'NEXT START {(end_time + delta).strftime("%d.%m.%Y %H:%M:%S")}')

current_session_account.set_times(delta)
current_session_account.deactivate()

return

Finally, the message is processed, the media is downloaded, if any, the text is saved. And other actions are no longer related to the telegram api.

async def send_this_post(msg, result):
chan = db.get_input_channel(result)
if db.using_ai(chan[1]):
    check = await Magic.detect_theme(msg.text)
    if check:
        msg_category = CAT_DEF[f'{check}']
    else:
        return
else:
    msg_category = db.get_category_by_input_channel_name(chan[1])

print(f'Theme - {msg_category}')

test = await MSG(msg_cat=msg_category, txt=msg.text, title=chan[2], username=chan[1], datetime=msg.date)
await test.create_media(msg)
await test.create_voice()
await test.create_translates()

await send_to_users_test(test)
return

Everything starts as follows:

if __name__ == '__main__':
    logging.warning('IZVESTNIK STARTED.')
    loop = asyncio.get_event_loop()
    bot.start(bot_token=settings.bot_TOKEN)
    logging.warning(f'BOT {settings.bot_username} just launched.')

    loop.create_task(usr_periods_activity())
    loop.create_task(usr_msg_queue_activity())
    loop.create_task(start_wtf_blyat())
    bot.loop.run_forever()

In fact, all that each account does is receive unread messages, download media, mark them as read, but even the launch of 8 accounts resulted in the ban of each of them for 3 days, either in general without an error, or with an Account deactivated/deleted error (Caused get_dialogs request).

Although many users of the telegram application do many times more actions. Recently rereading the documentation, I came across this:
Text from documentation.
Perhaps the reason is that I am from Russia, and I use Russian SIM cards to register accounts, but a friend from England bought SIM cards for me there several times, but they also received a ban. The project release is located on the WDM server, the ip is also Russian, maybe that’s the problem?

Asked By: Maxim Titov

||

Answers:

The solution of this issue is just write an "impulse" activity script against pooling script. Also use SIM cards from another country for telegram accounts and proxy.

Answered By: Maxim Titov

I also recommend to use different version

pip install Telethon==1.1

this version can’t ban your account

Answered By: user20889751
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.