te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>python - Telethon event_handler throws error while clients is connecting - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Telethon event_handler throws error while clients is connecting - Stack Overflow

programmeradmin3浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论