I’m facing an issue with the following code:
import asyncio
import random
import traceback
from telethon import TelegramClient, events
from telethon.sessions import StringSession
from config import API_HASH, BOT_TOKEN, API_ID, USER_ID
from models.account import Account
from utils.font import r, lb, gr
turn_on: bool = True
if turn_on:
client: TelegramClient = TelegramClient(StringSession(), API_ID, API_HASH).start(bot_token=BOT_TOKEN)
class TelegramBotManager:
def __init__(self, app):
self.app = app
self.allowed_channels: list[int] = [-1002398585765, -1002465829598, -1002447758138, -1002366258122, -1002289676072]
async def start_polling(self, managers):
if turn_on:
print('Bot started...')
@client.on(events.NewMessage(chats=self.allowed_channels))
async def handle_channel_messages(event):
#! Тут створюється таск.
print('New message in the channel detected.')
await self.process_message(self.app.accounts, event)
await client.run_until_disconnected()
async def process_message(self, accounts: list[Account], event):
message_id = f'{event.message.id}'
channel_id = f'{event.message.peer_id.channel_id}'
added_views = 0
for account in accounts:
# Random cooldown between 70% and 130% from mean time between views
total_time_in_hours = 1
total_time_in_seconds = total_time_in_hours * 3600
delay_between_views = total_time_in_seconds / len(accounts)
random_delay = random.uniform(0.7 * delay_between_views, 1.3 * delay_between_views)
await asyncio.sleep(random_delay)
try:
if not account.client.is_connected():
await account.client.connect()
except Exception as e:
print(f'{r}ERROR: {e}')
except BaseException as e:
print(f"{r}Unknown error occurred: {e}")
traceback.print_exc()
finally:
if account.client.is_connected():
await account.client.disconnect()
It’s throwing these errors:
> Unknown error occurred:
File "D:\PycharmProjects\UTF\models\account.py", line 30, in connect
await self.client.connect()
File "C:\Users\super\AppData\Local\Programs\Python\Python313\Lib\site-packages\telethon\client\telegrambaseclient.py", line 596, in connect
await self._sender.send(functions.InvokeWithLayerRequest(LAYER, req))
asyncio.exceptions.CancelledError
> Unhandled error while receiving data
Traceback (most recent call last):
File "C:\Users\super\AppData\Local\Programs\Python\Python313\Lib\site-packages\telethon\network\mtprotosender.py", line 507, in _recv_loop
body = await self._connection.recv()
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'recv'
Task exception was never retrieved
future: <Task finished name='Task-129' coro=<MTProtoSender._reconnect() done, defined at C:\Users\super\AppData\Local\Programs\Python\Python313\Lib\site-packages\telethon\network\mtprotosender.py:348> exception=AttributeError("'NoneType' object has no attribute 'disconnect'")>
Traceback (most recent call last):
File "C:\Users\super\AppData\Local\Programs\Python\Python313\Lib\site-packages\telethon\network\mtprotosender.py", line 353, in _reconnect
await self._connection.disconnect()
^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'disconnect'
> Task was destroyed but it is pending!
task: <Task pending name='Task-54' coro=<Connection._send_loop() done, defined at C:\Users\super\AppData\Local\Programs\Python\Python313\Lib\site-packages\telethon\network\connection\connection.py:310> wait_for=<Future cancelled>>
Exception ignored in: <coroutine object Connection._recv_loop at 0x00000216E4ADAEA0>
RuntimeError: coroutine ignored GeneratorExit
To give more context, I’m posting multiple posts across several channels, and after that, this error occurs. Has anyone experienced something similar or knows how to solve it? Any help would be greatly appreciated. Thanks in advance!
I did a lot of things, but neither exception handling nor the delay between requests helps. The error is most likely related to the telegram API limits, but I can't handle it in any way in the asynchronous code, and the Task created by the event handler is destroyed.