Connection error cannot send requests while disconnected telethon

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(targe...

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 !?

Содержание

  1. «Cannot send requests while disconnected» error when trying to download all media from Channel #958
  2. Comments
  3. [QST] How to cek client status, connect or disconnect. #3763
  4. Comments
  5. Forums
  6. Telethon ConnectionError
  7. ConnectionError: Cannot send requests while disconnected about telethon CLOSED
  8. Related Issues (20)
  9. Recommend Projects
  10. React
  11. Vue.js
  12. Typescript
  13. TensorFlow
  14. Django
  15. Laravel
  16. Recommend Topics
  17. javascript
  18. server
  19. Machine learning
  20. Visualization
  21. Recommend Org
  22. Facebook
  23. Microsoft
  24. ConnectionError: Not connected #1187
  25. Comments

«Cannot send requests while disconnected» error when trying to download all media from Channel #958

I try to write code to download all messages and media from specific channel. Getting messages without downloading media works fine. But with file download it is failed usually earlier than on 10 iteration. I use Python 3.6, Telethon 1.2.

The text was updated successfully, but these errors were encountered:

Could you enable logging.INFO and tell me if there are «Exporting authorization for data center» messages?

This log is for successful execution of «client.download_media(message, file=’download/’)»:

This log is for failed execution of «client.download_media(message, file=’download/’)»:

INFO:Received response without parent request

That is #658 once again, in this case File(type=FileJpeg(), mtime=1534442352, bytes=b») .

Anyway, back to your issue, it’s clear to see that in the first case the first attempt works, while in the second case, it fails (yet connects in the second attempt).

I fail to understand how your log connects and disconnects when the code flow doesn’t go like that.

Seems to have fixed it.

I’m experiencing the same issue under similar circumstances: «Cannot send requests while disconnected» when mass-downloading media from channels.

Also, I’m sometimes seeing this error (not sure if they are connected, but still):

No idea how I’m going to debug though.

Also this sequence of events seems to happen quite often:

utils.getFile is my app method, its job is to ether call client.download_file , or get channel post ( channels.GetMessagesRequest ), extract file_reference and then call client.download_file .

same here on version 1.16.2
any way to fix it?

is sync run account, and banned. but sync is connect. not disconnect

Could you post the full traceback with the error under the latest version ( pip3 install -U https://github.com/LonamiWebs/Telethon/archive/master.zip —user )? Having a traceback where the lines match with the code is very valuable and would help me introduce bogus errors to see if I can get the same behaviour.

@dmitrdv with Telethon==1.19.5 everything works well
try code bellow:

instead define/connect client outside def and call def.

Closing as this was reported a fairly long time ago and the cause is probably some connection issue.

Источник

[QST] How to cek client status, connect or disconnect. #3763

I make a bot with bunch of order. few weeks ago success, but yesterday my script not work anymore. error in connect and disconnect status.

previously I do this:

previously, it’s works.

but then today. suddenly error database is locked (means telethon client status is still connect).

ok, I read the documentation and from other source to close connection after get some data.

still not works, client still connect, and the database is locked.

OK, now I try to different approach. I try to make client always connect. I make like this:

but then, a few minutes later error. «cannot Send requests while disconnected».

Is there a way to know the connection status of the client, so if we still connected, I by pass the script to make a connection order to avoid database locked error.

while it disconnected, I can told the script to make a connection first before getting data to avoid error (cannot Send requests while disconnected).

now I try do this, set client in global, and try to call client.connect every time want get data.

client = TelegramClient(session_path,api_id,api_hash,
device_model=model,
system_version=sys_ver,
app_version=app_ver)

but I not satisfied because it make my bot so slow in responding

The text was updated successfully, but these errors were encountered:

Источник

Forums

Telethon ConnectionError

Hi. I am testing a small script that works with telegram api through python module ‘Telethon’. Here is the code:

When i launch it on my PC it works correct, but when i try to run it on the Pythonanywhere server it fails with an error:

I got this error before, and then i found this article: http://help.pythonanywhere.com/pages/403ForbiddenError/ so I connected through proxy, but nothing changed. It is strange because I found this in the whitelist:

Hope you will help me to solve this problem. Thank you.

Are you sure that you are actually running the code that configures the connection to use the proxy?

As described here https://docs.telethon.dev/en/latest/modules/client.html#telethon-client If «connection» is not MTProxy, proxy argument for TelegramClient» meant to store function parameters for PySocks, like (type, ‘hostname’, port). And as also described there, by defaullt connection is «telethon.network.connection.tcpfull.ConnectionTcpFull.». Correct me if I am wrong.

P.S. I have just checked the same code from my PC using free http proxy from the internet. It connected.

I see that MTProtoSender can use a number of different transports. Make sure that it is using the HTTP transport and not one of the others.

Sadly, but I can not make it work with HTTP connection even from my local pc. I did not know that free accounts supports only HTTP connection, it was not mention on help page. Thank you for response.

by the way, perhaps try to follow some of the instructions from here to make it work from your local pc?

Thank you for reply, but this is instruction about how to create telegram bot using teletop, and i want to create telegram client with telethon.

In that case, you’ll have to rely on the telethon documentation to get it working.

you should use something like python-telegram-bot, pytelegrambotapi etc which uses http api. telethon uses mtProto over tcp which might not be supported through pythonanywhere

Yeah i understand, but the problem is, that i want to create a little script, that will act as a user, not bot. Anyway thank you for reply, if I find the solution, i will share it here.

hi! Maxu360, what about your question? did you find solution? i have a problem like this..

hi! vikadashyan , Maxu360 , did you find out how to solve the problem with telethon ?

Update 2020-01-12 For some reason Telegram has stopped accepting wildcard HTTPS certificates for bots, so unfortunately this tutorial will no longer work on a PythonAnywhere free account. For the webhooks part of the tutorial to work, you will have to get a paying account with a custom domain. Thanks to fivechar for letting us know in the comments.

so it seems, there is no free way.

That only applies if you’re using a webhook-based system for your bot — if it’s a script that connects outwards to Telegram, and runs in a console, then it should still work.

One caveat: consoles do get reset from time to time as part of system maintenance, so your bot would stop working when that happened and you would have to restart it. Paid accounts can set up bots as always-on tasks, which would allow you to avoid that.

thx for caveat, but I cant even connect to telegramm api. neither through ‘proxy.server:3128 nor my proxy

Which library are you using?

[edit: I see you’ve posted on another forum thread, so I’ll pick it up there]

as signed it tilte of topic — I am trying to set up Telethon library. thx for help

why doesn’t the code come from telethon telegrams on your hosting?

Источник

ConnectionError: Cannot send requests while disconnected about telethon CLOSED

  • after event.delete() — enet handler continues to work . what am I doing wrong ? HOT 1
  • Telegram Topics — Replying in General chat doesn’t dork HOT 4
  • All sessions crushed HOT 1
  • RuntimeError(f’ is bound to a different event loop’)
  • Make the path of the session file configurable HOT 2
  • event.answer(url) not working when handled with bot.add_event_handler HOT 3
  • When failing to complete login, telegram just refuses to send messages HOT 1
  • Shouldn’t be a special exception for sellable usernames? HOT 1
  • forward_messages The views count is inaccurate. HOT 1
  • i cant received my code in the other app HOT 2
  • Current rate limits. HOT 1
  • events.new.message add wait timeout with client.disconnect() HOT 1
  • Coudn`t find Constructor ID HOT 1
  • Auto log out from account after run script HOT 3
  • DeprecationWarning: There is no current event loop HOT 3
  • WARNING:telethon.client.updates: Getting difference for channel updates * caused SessionRevokedError HOT 6
  • How to use telethon with a self hosted local bot api server
  • Disconnect and raise a proper error on session revoked HOT 1
  • Fatal error handling updates (this is a bug in Telethon, please report it) HOT 5
  • The key is not registered in the system HOT 5

Recommend Projects

React

A declarative, efficient, and flexible JavaScript library for building user interfaces.

Vue.js

🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

Typescript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

TensorFlow

An Open Source Machine Learning Framework for Everyone

Django

The Web framework for perfectionists with deadlines.

Laravel

A PHP framework for web artisans

Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

javascript

JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

Some thing interesting about web. New door for the world.

server

A server is a program made to process requests and deliver data to clients.

Machine learning

Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

Visualization

Some thing interesting about visualization, use data art

Some thing interesting about game, make everyone happy.

Recommend Org

Facebook

We are working to build community through open source technology. NB: members must have two-factor auth.

Microsoft

Open source projects and samples from Microsoft.

Источник

ConnectionError: Not connected #1187

api_id = 123456
api_hash = ‘xxxxxxxxxxxxxxxx’

with TelegramClient(‘testApp’, api_id, api_hash) as client:
client.send_message(‘me’, ‘Hello, myself!’)

The text was updated successfully, but these errors were encountered:

how do i solve this problem?

Please enable logging as explained in the documentation and show the output with that code.

can I continue this conversation?
so my code mostly took from documentation:

`import logging
from decouple import config
from telethon.sync import TelegramClient

api_id = config(‘APP_API_ID’, cast=int)
api_hash = config(‘APP_API_HASH’)
logging.basicConfig(level=logging.DEBUG)

with TelegramClient(‘anon’, api_id, api_hash) as client:
# Getting information about yourself
me = client.get_me()`

and this is the output:

DEBUG:asyncio:Using selector: KqueueSelector
INFO:telethon.network.mtprotosender:Connecting to 149.154.167.51:443/TcpFull.
DEBUG:telethon.network.mtprotosender:Connection attempt 1.
DEBUG:telethon.network.mtprotosender:Connection success!
DEBUG:telethon.network.mtprotosender:New auth_key attempt 1.
INFO:telethon.network.connection.connection:The server closed the connection
WARNING:telethon.network.connection.connection:Unhandled on disconnect: [Errno 54] Connection reset by peer
Traceback (most recent call last):
File «/Users/denisvanyushkin/OneDrive/Programming/Projects/informer/tg_client.py», line 12, in
with TelegramClient(‘anon’, api_id, api_hash) as client:
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/helpers.py», line 122, in _sync_enter
return loop.run_until_complete(self.aenter())
File «/anaconda3/lib/python3.7/asyncio/base_events.py», line 584, in run_until_complete
return future.result()
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/client/auth.py», line 631, in aenter
return await self.start()
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/client/auth.py», line 141, in _start
await self.connect()
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/client/telegrambaseclient.py», line 412, in connect
proxy=self._proxy
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/network/mtprotosender.py», line 122, in connect
await self._connect()
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/network/mtprotosender.py», line 218, in _connect
await authenticator.do_authentication(plain)
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/network/authenticator.py», line 31, in do_authentication
res_pq = await sender.send(ReqPqMultiRequest(nonce))
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/network/mtprotoplainsender.py», line 36, in send
body = await self._connection.recv()
File «/Users/denisvanyushkin/python/informer/lib/python3.7/site-packages/telethon/network/connection/connection.py», line 142, in recv
raise ConnectionError(‘Not connected’)
ConnectionError: Not connected

is it authentication problem?

@Lonami hello, could you please comment?
should I open a new issue?

Does it happen consistently? Is your country limited?

This is the only result I get
By limited you mean Telegram blocking by state? No, it is available in my country

What version are you using?

It is strange, because it’s working for me and probably everyone else or there would be more reports. Telegram shouldn’t be closing the connection so early and I don’t know if reconnecting will help.

I just tried to put this code to DO VPS and it’s worked

So problem in my Mac, please advice what should I check?

The log says INFO:telethon.network.connection.connection:The server closed the connection , but it doesn’t say when it happened (i.e. has it sent/received any data at all before this happened?) which would be helpful to know, so if you’re willing to investigate that (maybe add a breakpoint on that log line so you can inspect the stack back up), it would be nice.

So it is happened on one of iteration at base_events.py, line 539.
I am really happy to help, but I’m not sure what to do — I’m quite new at programming

asyncio way of dealing with sockets probably won’t make debugging this easier, due to how it works. It may not be a suitable task for a new comer like you, and that’s fine.

OK, so if I can help you somehow — just let me know

Closing due to inactivity. Might be related to the more recent #1376 so discussion should probably happen there.

Источник

username = "BitShibaToken"
min_id = 0
limit = 100000
from telethon import TelegramClient
import traceback
api_id = MYID
api_hash = MYHASH
client = TelegramClient('search.session', api_id, api_hash)
client_list = []
client_list.append(client)
async def msg(client):
    search = 'address'
    messages = client.iter_messages(username, min_id=min_id, reverse=True, limit=limit, search=search)
    print(messages)
    try:
        async for M in messages:
            print(M)
    except:
        traceback.print_exc()
if __name__ == '__main__':
    client.loop.run_until_complete(msg(client))
...
Traceback (most recent call last):
  File "t.py", line 16, in msg
    async for M in messages:
  File "/root/.miniconda3/envs/python38/lib/python3.8/site-packages/telethon/requestiter.py", line 58, in __anext__
    if await self._init(**self.kwargs):
  File "/root/.miniconda3/envs/python38/lib/python3.8/site-packages/telethon/client/messages.py", line 27, in _init
    self.entity = await self.client.get_input_entity(entity)
  File "/root/.miniconda3/envs/python38/lib/python3.8/site-packages/telethon/client/users.py", line 437, in get_input_entity
    await self._get_entity_from_string(peer))
  File "/root/.miniconda3/envs/python38/lib/python3.8/site-packages/telethon/client/users.py", line 553, in _get_entity_from_string
    result = await self(
  File "/root/.miniconda3/envs/python38/lib/python3.8/site-packages/telethon/client/users.py", line 30, in __call__
    return await self._call(self._sender, request, ordered=ordered)
  File "/root/.miniconda3/envs/python38/lib/python3.8/site-packages/telethon/client/users.py", line 63, in _call
    future = sender.send(request, ordered=ordered)
  File "/root/.miniconda3/envs/python38/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 172, in send
    raise ConnectionError('Cannot send requests while disconnected')
ConnectionError: Cannot send requests while disconnected

While others have had similar problems before, mine is different.


0

1

https://github.com/Seavegen/tg_leave_chats_and_delete_dialog/
Мне нужно с телеги почистить чаты, нашел данный скрипт, но тут ошибка

python unsuber.py
/home/kali/Desktop/unsuber.py:73: DeprecationWarning: There is no current event loop
  loop = asyncio.get_event_loop()
/home/kali/Desktop/unsuber.py:23: RuntimeWarning: coroutine 'DialogMethods.get_dialogs' was never awaited
  async for dialog in client.get_dialogs():
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "/home/kali/Desktop/unsuber.py", line 74, in <module>
    loop.run_until_complete(main())
  File "/usr/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
    return future.result()
  File "/home/kali/Desktop/unsuber.py", line 67, in main
    leave_groups = await leave_all_groups()
  File "/home/kali/Desktop/unsuber.py", line 33, in leave_all_groups
    me = await client.get_me()
  File "/home/kali/.local/lib/python3.10/site-packages/telethon/client/users.py", line 161, in get_me
    me = (await self(
  File "/home/kali/.local/lib/python3.10/site-packages/telethon/client/users.py", line 30, in __call__
    return await self._call(self._sender, request, ordered=ordered)
  File "/home/kali/.local/lib/python3.10/site-packages/telethon/client/users.py", line 63, in _call
    future = sender.send(request, ordered=ordered)
  File "/home/kali/.local/lib/python3.10/site-packages/telethon/network/mtprotosender.py", line 172, in send
    raise ConnectionError('Cannot send requests while disconnected')
ConnectionError: Cannot send requests while disconnected

Что не так?

I use telethon in python3.9. I want to delete all channels and chats. If anything, this is not my code, so please explain in as much detail as possible what is wrong.

code:

import telethon
import asyncio
from telethon.tl.functions.channels import LeaveChannelRequest
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
from telethon import TelegramClient


async def auth_client():
    api_id = 16193575
    api_hash = "ec2558b0281653bfcd5144ae6371faf5"
    client = TelegramClient('main_session', api_id, api_hash)
    return client


async def delete_all_dialogs():
    client = await auth_client()
    count = 0
    await client.start()
    try:
        async for dialog in client.get_dialogs():
            count += 1
            leave = await client.delete_dialog(dialog.id, revoke=True)
            print(f"{count} - {leave}")
    except:
        pass


async def leave_all_groups():
    client = await auth_client()
    me = await client.get_me()
    print(me)
    chats = []
    last_date = None
    chunk_size = 200
    groups = []

    result = await client(GetDialogsRequest(
        offset_date=last_date,
        offset_id=0,
        offset_peer=InputPeerEmpty(),
        limit=chunk_size,
        hash=0
    ))
    chats.extend(result.chats)

    for chat in chats:
        try:
            if chat == True:
                groups.append(chat)
        except:
            continue

    leave_chat = []
    for all_groups in groups:
        if all_groups.username != None:
            leave_chat.append(all_groups.username)
    for leave_chats in range(len(leave_chat)):
        result = await client(LeaveChannelRequest(channel=leave_chat[leave_chats]))
        print(f'{result.id}, {result.username} - аккаунт вышел из группы...')


async def main() -> None:
    delete_dialog = await delete_all_dialogs()
    leave_groups = await leave_all_groups()
    tasks = [delete_dialog, leave_groups]
    await asyncio.gather(*tasks)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

But I got the error: raise ConnectionError(‘Cannot send requests while disconnected’)
ConnectionError: Cannot send requests while disconnected

Hi. I am testing a small script that works with telegram api through python module ‘Telethon’. Here is the code:

from telethon import TelegramClient, events, sync
import socks
import os


def main():
    TELEGRAM_API_ID = os.environ['API_ID']
    TELEGRAM_API_HASH = os.environ['API_HASH']
    if os.environ.get('PYTHONANYWHERE_DOMAIN'):
        pythonanywhere_proxy = (socks.HTTP, 'proxy.server', 3128)
        print('Connecting through proxy')
        telegram_client = TelegramClient('testing_session', TELEGRAM_API_ID, TELEGRAM_API_HASH, 
                                         proxy=pythonanywhere_proxy)
    else:
        telegram_client = TelegramClient('testing_session', TELEGRAM_API_ID, TELEGRAM_API_HASH)
    telegram_client.start(force_sms=True)


if __name__ == '__main__':
    main()

When i launch it on my PC it works correct, but when i try to run it on the Pythonanywhere server it fails with an error:

$ python3.8 test.py
Connecting through proxy
Traceback (most recent call last):
  File "test.py", line 19, in <module>
    main()
  File "test.py", line 15, in main
    telegram_client.start(force_sms=True)
  File "/home/Maxu360/.local/lib/python3.8/site-packages/telethon/client/auth.py", line 132, in start
    else self.loop.run_until_complete(coro)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
    return future.result()
  File "/home/Maxu360/.local/lib/python3.8/site-packages/telethon/client/auth.py", line 139, in _start
    await self.connect()
  File "/home/Maxu360/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py", line 439, in connect
    if not await self._sender.connect(self._connection(
  File "/home/Maxu360/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 125, in connect
    await self._connect()
  File "/home/Maxu360/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 250, in _connect
    raise ConnectionError('Connection to Telegram failed {} time(s)'.format(self._retries))
ConnectionError: Connection to Telegram failed 5 time(s)

I got this error before, and then i found this article: http://help.pythonanywhere.com/pages/403ForbiddenError/ so I connected through proxy, but nothing changed. It is strange because I found this in the whitelist:

...
api.telegram.org
...
core.telegram.org
...

Hope you will help me to solve this problem.
Thank you.

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

icanary

Error: Cannot send requests while disconnected. You need to call .connect()

My app work fine, but sometimes it fall down with error:

Error: Cannot send requests while disconnected. You need to call .connect(), which begin run in endless cycle

then script die with another error:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

so my question is:

what is the bug with this:

Error: Cannot send requests while disconnected. You need to call .connect() ?

Why this sometimes run in endless cycle and never end? This definitely need to be fixed.

This bug was in version 2.5.* and now in 2.6.13 it has too.

Full error look like this:

Error: Cannot send requests while disconnected. You need to call .connect()
    at MTProtoSender.send (/code/node_modules/telegram/network/MTProtoSender.js:197:19)
    at Object.invoke (/code/node_modules/telegram/client/users.js:31:36)
    at async TelegramClient.getDC (/code/node_modules/telegram/client/TelegramClient.js:1120:28)
    at async TelegramClient._connectSender (/code/node_modules/telegram/client/telegramBaseClient.js:200:20)
    at async TelegramClient._borrowExportedSender (/code/node_modules/telegram/client/telegramBaseClient.js:243:22)

p.s.: right before this error it show this:

Error: Disconnect 
 at /code/node_modules/telegram/extensions/MessagePacker.js:106:33 
 at Array.forEach (<anonymous>) 
 at MessagePacker.rejectAll (/code/node_modules/telegram/extensions/MessagePacker.js:105:29) 
 at MTProtoSender._disconnect (/code/node_modules/telegram/network/MTProtoSender.js:247:25) 
 at MTProtoSender.disconnect (/code/node_modules/telegram/network/MTProtoSender.js:168:20) 
 at MTProtoSender._reconnect (/code/node_modules/telegram/network/MTProtoSender.js:728:24) 
 at /code/node_modules/telegram/network/MTProtoSender.js:721:22

Thanks.

painor

Are you sure it’s not a network issue? maybe your internet got disconnected and the library was trying to reconnect forever?

wind-hx

Are you sure it’s not a network issue? maybe your internet got disconnected and the library was trying to reconnect forever?

I am sure there is no problem with the network, after a while there will be a lot of timeouts, Connect 20 accounts, 15 will have timeout, and the remaining 5 are normal. I don’t think it has anything to do with the network.

#302

wind-hx

Are you sure it’s not a network issue? maybe your internet got disconnected and the library was trying to reconnect forever?

I think it should be a bug that caused the infinite loop, but my development environment cannot be reproduced. This error has always existed in the production environment, causing the cpu to be full.

painor

if I can’t reproduce the issue I really can’t solve it :(

icanary

Are you sure it’s not a network issue? maybe your internet got disconnected and the library was trying to reconnect forever?

even if reason was internet this need to be fixed. Problems with internet should not crash the app

icanary

what i know for current moment:

i see in my logs this: screenshot

so here, after client init (TelegramClient), connected (connect) and successfully logged in (checkAuthorization), i try to get info about some channel (inside my custom getInfo method).

right after that i set 20 sec sleep, you can see it in screenshot(i do this to not get flood errors)

then i try to download photo of channel (inside my custom channelBuild method)

so, somewhere around this time, i get errors Disconnect and Timeout and then app fall in infinite loop. And crash.

=======

intersting fact: when i restart app and try to connect client via same user session, now i was NOT logged in.
So maybe something happened to the user session during these operations. Some minutes later the same session again start workin. Without any changes in it.

=======

Whatever it was, the library should not crash an app. It should deal with any variants of events during execution

icanary

maybe we can together find out the bug if you tell us, what exactly mean each of this peaces of code:

Error: Cannot send requests while disconnected. You need to call .connect()

  • at MTProtoSender.send (/code/node_modules/telegram/network/MTProtoSender.js:197:19)
  • at Object.invoke (/code/node_modules/telegram/client/users.js:31:36)
  • at async TelegramClient.getDC (/code/node_modules/telegram/client/TelegramClient.js:1120:28)
  • at async TelegramClient._connectSender (/code/node_modules/telegram/client/telegramBaseClient.js:200:20)
  • at async TelegramClient._borrowExportedSender (/code/node_modules/telegram/client/telegramBaseClient.js:243

what is going on in this lines? and why this can fall in repeatable situation?

painor

when you download a file from a different DC you need to create a new connection.

That’s what line does. It tries to create a new connection in the new DC but for some reason it fails for you. it waits 1 second between each fails and tries again.

icanary

when you download a file from a different DC you need to create a new connection.

That’s what line does. It tries to create a new connection in the new DC but for some reason it fails for you. it waits 1 second between each fails and tries again.

but it don’t wait 1 sec, it fall in infinite loop every .001 ml-sec. Look at screenshot, there is three calls with time:

  1. 09:03:42.134
  2. 09:03:42.134
  3. 09:03:42.135

and so on, while not crash an app with node.js error:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

painor

yes, clearly there is an issue somewhere in the library’s code.
how many connections do you have open btw.?
Also do you have any specific attributes when creating a new TelegramClient ?

icanary

it start like this:

const client = new TelegramClient(session, this.api_id, this.api_hash, {
    connectionRetries: 2,
    requestRetries: 2,
    autoReconnect: false,
    proxy: {
        ip: data.proxy.ip,
        port: parseInt(String(data.proxy.port)),
        username: data.proxy.login,
        password: data.proxy.password,
        socksType: 5,
        MTProxy: false
    },
    baseLogger: new Logger(LogLevel.ERROR)
})

await client.connect()

for now it can have 2-10 parallel connections.

painor

    connectionRetries: 2,
    requestRetries: 2,
    autoReconnect: false,

can you put theses to 5 and true and see if the error stays?

icanary

done. Now we need to wait

karpotkin

    connectionRetries: 2,
    requestRetries: 2,
    autoReconnect: false,

can you put theses to 5 and true and see if the error stays?

I have a similar situation when downloading a photo. These options don’t help.

Screenshot 2022-04-22 at 12 23 01

Screenshot 2022-04-22 at 12 25 38

If you wait a bit (until the connection is made) and try to download the file again, then everything is fine

icanary

yes, no difference on init parameters.
error arrive again, see this screenshot

maybe it exists in destroy method.. so anyway, bug is out there, need to be finded…

icanary

yes, clearly there is an issue somewhere in the library’s code. how many connections do you have open btw.? Also do you have any specific attributes when creating a new TelegramClient ?

hi, did you try something to find error? can’t use this library with this bug ( crash 1-2 times per day

Dima564

experienced this issue too

painor

I’ve pushed a potential fix to the latest version, can you try it out? I’ve been trying to reproduce the issue but I’m not able to.

icanary

I’ve pushed a potential fix to the latest version, can you try it out? I’ve been trying to reproduce the issue but I’m not able to.

can you give link to that fix?

karpotkin

I’ve pushed a potential fix to the latest version, can you try it out? I’ve been trying to reproduce the issue but I’m not able to.

can you give link to that fix?

last commit to the master

Понравилась статья? Поделить с друзьями:
  • Configure error configure could not find required x11 libraries aborting
  • Configure error cannot run c compiled programs
  • Connection error 87 check how to fix
  • Connection error 809 bright vpn
  • Connection error 595 no route to host