LonamiWebs / Telethon

Pure Python 3 MTProto API Telegram client library, for bots too!
https://docs.telethon.dev
MIT License
9.77k stars 1.39k forks source link

ConnectionError: Cannot send requests while disconnected ? #1376

Closed alirezaimi closed 3 years ago

alirezaimi commented 4 years ago

Hi I have problem with this kind of implementing telethon and can't find out why ?!

...
def create_telethon_session(self):
    target_phone = self.phones[self.phone_index]
    with TelegramClient(target_phone + "-x", self.api_id, self.api_hash) as client:
        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(target_phone)
            client.sign_in(target_phone, input("Enter the code: "))

        logging.info(f">> create_telethon_session client : {client}")
        return client

def delete_messages(self):
    target_group = "@XXX"

    # client = self.create_telethon_session()
    logging.info(f">> delete_messages client: {client}")

    while True:
        logging.info(">> get 1000 messages for deleting ...")
        messages=client.get_messages(target_group, limit=1000)
        logging.info(f">> messages.total: {messages.total}")
        if messages.total > 1:
            logging.info(">> deleting ...")
            for i in messages:
                # logging.info(f">> {i.id} deleted .")
                client.delete_messages(target_group, i.id)
        elif messages.total <= 1:
            break
...

getting this error :

[INFO] (MainThread) -(2020-01-22 10:19:18,496)- >> get 1000 messages for deleting ...
Traceback (most recent call last):
  File "gpmanautoads.py", line 374, in <module>
    a.autosend_caller()
  File "gpmanautoads.py", line 362, in autosend_caller
    self.nightmode()
  File "gpmanautoads.py", line 120, in nightmode
    self.delete_messages()
  File "gpmanautoads.py", line 104, in delete_messages
    messages=client.get_messages(target_group, limit=1000)
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/sync.py", line 39, in syncified
    return loop.run_until_complete(coro)
  File "/usr/lib/python3.7/asyncio/base_events.py", line 583, in run_until_complete
    return future.result()
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/client/messages.py", line 531, in get_messages
    return await it.collect()
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/requestiter.py", line 114, in collect
    async for message in self:
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/requestiter.py", line 58, in __anext__
    if await self._init(**self.kwargs):
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/client/messages.py", line 25, in _init
    self.entity = await self.client.get_input_entity(entity)
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/client/users.py", line 404, in get_input_entity
    await self._get_entity_from_string(peer))
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/client/users.py", line 517, in _get_entity_from_string
    functions.contacts.ResolveUsernameRequest(username))
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/client/users.py", line 53, in __call__
    future = self._sender.send(request, ordered=ordered)
  File "/home/ali/git_proj/imiTelGroupManBot/venv/lib/python3.7/site-packages/telethon/network/mtprotosender.py", line 169, in send
    raise ConnectionError('Cannot send requests while disconnected')
ConnectionError: Cannot send requests while disconnected

why !?

byaka commented 4 years ago

Hm, today i have same error. What is this?

UPD: After restart problem gone.

tiantian1645 commented 4 years ago

Yesterday same issue +1 UTC+8 2020-02-19 18:25:52.518

4myr commented 4 years ago

i have this problem too when i run my script, it crashes after a few minutes and i have to log in again!

Lonami commented 3 years ago

Possibly related: #958.

The code in the original post uses with client and returns the value (which exits with, which calls disconnect).

The library should be automatically reconnecting on disconnection for the specified retry amount when creating the instance. This shows up in the logs. If it still fails after retrying, then it should raise, and it's up to the user to catch that.

If it's getting disconnected and not raising or logging, then that's a different bug, which I would appreciate a small code snippet for along with clear reproduction steps in a new issue.

Closing this one for the above reasons.

alirezaimi commented 3 years ago

HI !!!! after 1 year and almost half(!!!!) i forgot the problem at all !! Thanks !!

CJSparrow commented 3 years ago

2021: raise ConnectionError('Cannot send requests while disconnected') ConnectionError: Cannot send requests while disconnected

alcarazolabs commented 2 years ago

what's the solution?

CJSparrow commented 2 years ago

2021: `raise ConnectionError('Cannot send requests while disconnected')

ConnectionError: Cannot send requests while disconnected`

Btw stay connected to not get the error :D

2704jakob commented 2 years ago

To resolve the ConnectionError: Cannot send requests while disconnected Error, you need:

async def main():
        await client.##any possible parameter here. 

and

with client:
    client.loop.run_until_complete(main())

An example script:

from telethon import TelegramClient

api_id = 'your api id'
api_hash = 'your api hash'

client = TelegramClient('anon', api_id, api_hash)
async def main():
        await client.send_message('me', 'Hello, myself!')
with client:
    client.loop.run_until_complete(main())

Edit: using client. outside a function that gets looped by client.loop.run_until_complete() will also result in ConnectionError: Cannot send requests while disconnected

ewwink commented 7 months ago

I'm have same issue, solved using code below .start() first, use await then wrap your code inside async function

import asyncio
from telethon import TelegramClient

api_id = 'your api id'
api_hash = 'your api hash'

async def main():
    client = TelegramClient('session', api_id, api_hash)
    await client.start()
    await client.send_message('me', 'Hello, myself!')

asyncio.run(main())