Advertisement
disk6969

load_bot_dialogs

Jul 9th, 2024 (edited)
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.02 KB | None | 0 0
  1. from telethon import TelegramClient
  2. from telethon.tl import types
  3. from telethon.tl.functions.updates import GetDifferenceRequest
  4. import argparse
  5.  
  6. def dict_from_state(state):
  7.     return {'pts': state.pts, 'qts': state.qts, 'date': state.date}
  8.  
  9. async def search_pts(state, found_pts):
  10.     while found_pts['bottom']  <= found_pts['top']:
  11.         state['pts'] = (found_pts['bottom'] + found_pts['top']) // 2
  12.         try:
  13.             response = await client(GetDifferenceRequest(**state))
  14.         except: response = None
  15.         if not response or isinstance(response, types.updates.DifferenceTooLong):
  16.             found_pts['bottom'] = state['pts'] + 1
  17.         else:
  18.             found_pts['top'] = state['pts'] - 1
  19.     state['pts'] = found_pts['bottom']
  20.     return state, found_pts
  21.  
  22.  
  23. async def cache_all_bot_chats(state, total_pts):
  24.     found_pts = {'bottom': 0, 'top': 0}
  25.     state, found_pts = await search_pts(state, found_pts)
  26.  
  27.     while True:
  28.         try:
  29.             response = await client(GetDifferenceRequest(**state))
  30.             if isinstance(response, types.updates.DifferenceEmpty):
  31.                 break
  32.             elif isinstance(response, types.updates.Difference):
  33.                 state = dict_from_state(response.state)
  34.             elif isinstance(response, types.updates.DifferenceSlice):
  35.                 state = dict_from_state(response.intermediate_state)
  36.             elif isinstance(response, types.updates.DifferenceTooLong):
  37.                 bottom = state['pts']
  38.                 top = response.pts
  39.                 state, found_pts = await search_pts(bottom, found_pts)
  40.         except Exception as e:
  41.             return print(f'Error getting difference: {type(e)}: {e}')
  42.         print(f'Fetching peers {(state["pts"] / total_pts) * 100:0.2f}%', flush=True, end='\r')
  43.     print('\nFinished')
  44.     return True
  45.  
  46. async def get_bot_dialog_ids() -> list[int]:
  47.     success = await cache_all_bot_chats(
  48.         {'qts': 1, 'pts': 1, 'date': 1, 'pts_total_limit': 2**31 - 1}
  49.     , client._message_box.session_state()[0]['pts'])
  50.     if success:
  51.         client.session.save()
  52.         return [
  53.             en[0]
  54.             for en in client.session._cursor()
  55.             .execute('SELECT id FROM entities')
  56.             .fetchall()
  57.         ]
  58.  
  59. async def main(client):
  60.     old_count = client.session._cursor().execute('SELECT COUNT(*) FROM entities').fetchone()[0]
  61.     print('current peer count in session:', old_count)
  62.     chats = await get_bot_dialog_ids()
  63.     if chats:
  64.         print('Total new cached chats:', len(chats) - old_count)
  65.         print('Users:', len([u for u in chats if u > 0]))
  66.         print('Chats:', len([c for c in chats if c < 0]))
  67.     else:
  68.         print('Failed')
  69.  
  70. parser = argparse.ArgumentParser()
  71. parser.add_argument("session", help="path to .session file of bot")
  72. parser.add_argument("api_id", type=int)
  73. parser.add_argument("api_hash")
  74. args = parser.parse_args()
  75.  
  76. client = TelegramClient(args.session, args.api_id, args.api_hash).start()
  77. client.loop.run_until_complete(main(client))
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement