Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
3 tasks done
alimp5 opened this issue Feb 14, 2024 · 2 comments
Open
3 tasks done

Comments

@alimp5
Copy link

alimp5 commented Feb 14, 2024

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

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

Lonami commented Feb 17, 2024

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:

updates, users, chats = self._message_box.apply_difference(diff, self._mb_entity_cache)

which is only reached if get_difference returns data:

get_diff = self._message_box.get_difference()
if get_diff:

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

def get_difference(self):
for entry in (ENTRY_ACCOUNT, ENTRY_SECRET):
if entry in self.getting_diff_for:

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

account = ENTRY_ACCOUNT in self.getting_diff_for
secret = ENTRY_SECRET in self.getting_diff_for
if not account and not secret:
raise RuntimeError('Should not be applying the difference when neither account or secret was diff was active')

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.

@alimp5 alimp5 closed this as completed Feb 22, 2024
@alimp5
Copy link
Author

alimp5 commented Feb 22, 2024

@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 alimp5 reopened this Feb 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants