Telethon icon indicating copy to clipboard operation
Telethon copied to clipboard

Fatal error handling updates (this is a bug in Telethon v1.34.0, please report it)

Open alimp5 opened this issue 1 year ago • 3 comments

Code that causes the issue

    def init_run (self):
            telegram_info = "a db query ...................................."
            mobile   = telegram_info[0]
            api_id   = telegram_info[1]
            api_hash = telegram_info[2]
            string_session = telegram_info[3]
            self.client    = ""
            try:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                #unique_uuid = shortuuid.ShortUUID().random(length=10)
                #self.client = TelegramClient (mobile, api_id, api_hash, loop=loop)
                self.client  = TelegramClient (StringSession(string_session), api_id, api_hash, loop=loop, auto_reconnect=True, connection_retries=sys.maxsize, retry_delay=10, timeout=10)
                self.client.connect()
            except:
                print ("[!] Unknown telegram error:\n", traceback.format_exc())
                self.close_session()
                sys.exit(1)


    def close_session (self):
        try:
            self.client.disconnect()
        except:
            pass 



    def send_telegram_msg (self):
        try:
            self.client.connect()
            conn = pymysql.connect(.....................................,)
            with conn.cursor() as cursor:
                cursor.execute(f"SELECT id, msg_data FROM ea_app_telegrammessage WHERE is_done='0';")
                all_msgs = cursor.fetchall()
                conn.commit()
                if len(all_msgs) > 0:
                    print (f'[+] We found {len(all_msgs)} new messages in database.')
                else:
                    print (f'[+] No new messages found in database.')
                for msg in all_msgs:
                    pk_id    = msg[0]
                    msg_data = msg[1]
                    if self.client.is_connected():
                        self.client.send_message("me", msg_data)
                        ## make aware datetime:
                        updated_at = dt.now()  ##.replace(tzinfo=pytz.timezone('Asia/Tehran')).strftime(r'%Y-%m-%d %H:%M:%S.%f')
                        cursor.execute(f"UPDATE ea_app_telegrammessage  SET  is_done='1', updated_at='{updated_at}'  WHERE id='{pk_id}';")
                        conn.commit()
                    else:
                        if self.try_counter == 5:
                            print ("[!] Script failed.")
                            sys.exit(1)
                        time.sleep(10)
                        self.try_counter += 1
                        self.close_session()
                        self.init_run()
                        continue
        except:
            print ("[!!] Connection issue. Try again after 10 seconds...")
            print ("[!!] Telethon error:\n", traceback.format_exc())
            if self.try_counter == 5:
                print ("[!!] Script failed.")
                sys.exit(2)
            time.sleep(10)
            self.close_session()
            self.__init__()
            return self.send_telegram_msg()

if __name__ == "__main__":
    os_type = platform.system().lower()
    if "win" in os_type:
        os.system ("cls")
    else:
        os.system ("clear")
    try:
        tmp_obj = TELEGRAM_CLASS()
        i = 0
        while True:
            time.sleep(5)
            tmp_obj.send_telegram_msg()
            print (f"[+] Script launched {i} times.")
            i += 1
    except KeyboardInterrupt:
        print (f"[+] Script stopped [ctrl + c].")
        sys.exit(0)
    except:
        print ("[!!] Unknown Error:\n", traceback.format_exc())
        sys.exit(1)

Expected behavior

i upgraded telethon to newest version to fix error below. but i encountered with new exceptions :DDDDD

Automatic reconnection failed 5 time(s)
[+] No new messages found in database.
[+] Script launched 4167 times.
Future exception was never retrieved
future: <Future finished exception=ConnectionError('Connection to Telegram failed 5 time(s)')>
ConnectionError: Connection to Telegram failed 5 time(s)

Actual behavior

i got a new exception error after upgrading to latest version.

Traceback

Fatal error handling updates (this is a bug in Telethon v1.34.0, please report it)
Traceback (most recent call last):
  File "telethon\client\updates.py", line 342, in _update_loop
  File "telethon\_updates\messagebox.py", line 668, in apply_difference
RuntimeError: Should not be applying the difference when neither account or secret was diff was active
[+] No new messages found in database.
[+] Script launched 1084 times.
Unhandled error while receiving data
Traceback (most recent call last):
  File "telethon\network\mtprotosender.py", line 507, in _recv_loop
AttributeError: 'NoneType' object has no attribute 'recv'
Task exception was never retrieved
future: <Task finished name='Task-1429' coro=<MTProtoSender._reconnect() done, defined at telethon\network\mtprotosender.py:348> exception=AttributeError("'NoneType' object has no attribute 'disconnect'")>
Traceback (most recent call last):
  File "telethon\network\mtprotosender.py", line 353, in _reconnect
AttributeError: 'NoneType' object has no attribute 'disconnect'
Server closed the connection: 0 bytes read on a total of 8 expected bytes

Telethon version

1.34

Python version

3.8.10 + 3.9.10

Operating system (including distribution name and version)

Windows 2016 - 64 bit

Other details

No response

Checklist

  • [X] The error is in the library's code, and not in my own.
  • [X] I have searched for this issue before posting it and there isn't an open duplicate.
  • [X] I ran pip install -U https://github.com/LonamiWebs/Telethon/archive/v1.zip and triggered the bug in the latest version.

alimp5 avatar Feb 14 '24 09:02 alimp5

Have you modified the library in any way? From your logs:

Traceback (most recent call last):
  File "telethon\client\updates.py", line 342, in _update_loop
  File "telethon\_updates\messagebox.py", line 668, in apply_difference
RuntimeError: Should not be applying the difference when neither account or secret was diff was active

It fails here:

https://github.com/LonamiWebs/Telethon/blob/319db57ccb97177b376eb7947fbd3cf4def9fe72/telethon/client/updates.py#L342

which is only reached if get_difference returns data:

https://github.com/LonamiWebs/Telethon/blob/319db57ccb97177b376eb7947fbd3cf4def9fe72/telethon/client/updates.py#L304-L305

and get_difference only returns data if it is fetching the difference:

https://github.com/LonamiWebs/Telethon/blob/319db57ccb97177b376eb7947fbd3cf4def9fe72/telethon/_updates/messagebox.py#L615-L617

but apply_difference only fails if you were not fetching the difference:

https://github.com/LonamiWebs/Telethon/blob/319db57ccb97177b376eb7947fbd3cf4def9fe72/telethon/_updates/messagebox.py#L664-L668

So what gives? Some other task must've modified self.getting_diff_for. Which otherwise only happens on error or after successfully applying the difference.

Lonami avatar Feb 17 '24 10:02 Lonami

@Lonami no changes applied by me on source code of library.

today i got new error/exception:


[+] No new messages found in database.
[+] Script launched 4553 times.
[+] No new messages found in database.
[+] Script launched 4554 times.
Fatal error handling updates (this is a bug in Telethon v1.34.0, please report it)
Traceback (most recent call last):
  File "telethon\_updates\messagebox.py", line 381, in end_get_diff
KeyError: 1915344203

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "telethon\client\updates.py", line 440, in _update_loop
  File "telethon\_updates\messagebox.py", line 792, in apply_channel_difference
  File "telethon\_updates\messagebox.py", line 383, in end_get_diff
RuntimeError: Called end_get_diff on an entry which was not getting diff for
[+] No new messages found in database.
[+] Script launched 4555 times.
Unhandled error while receiving data
Traceback (most recent call last):
  File "telethon\network\mtprotosender.py", line 507, in _recv_loop
AttributeError: 'NoneType' object has no attribute 'recv'
Task exception was never retrieved
future: <Task finished name='Task-6411' coro=<MTProtoSender._reconnect() done, defined at telethon\network\mtprotosender.py:348> exception=AttributeError("'NoneType' object has no attribute 'disconnect'")>
Traceback (most recent call last):
  File "telethon\network\mtprotosender.py", line 353, in _reconnect
AttributeError: 'NoneType' object has no attribute 'disconnect'
Server closed the connection: 0 bytes read on a total of 8 expected bytes

alimp5 avatar Feb 22 '24 06:02 alimp5