Advertisement
akupriyanovhse

grabbing tg + GS

Mar 1st, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. from telethon import TelegramClient
  2. from my_config import api_id, api_hash, phone_number, gs_url
  3. import json, gspread
  4.  
  5. # Настройки
  6.  
  7. posts_to_get = 100
  8.  
  9. channels_to_review = ['https://t.me/rusbrief'] # Через запятую, еслм надо, это список
  10.  
  11. creds = 'amedia-415820-d9db0852c5c9.json'
  12.  
  13.  
  14. client = TelegramClient('anon', api_id, api_hash)
  15.  
  16.  
  17. async def main(posts_to_get, channels_to_review):
  18.  
  19.     k=0
  20.  
  21.     out_lst = []
  22.  
  23.     for channel in channels_to_review:
  24.  
  25.         async for message in client.iter_messages(channel):
  26.  
  27.             emotions_dict = {}
  28.  
  29.             if message.reactions is not None:
  30.                 for r in message.reactions.results:
  31.                     emotions_dict[r.reaction.emoticon] = r.count
  32.  
  33.             out_lst.append([str(message.date.strftime('%Y-%m-%d %H:%M:%S')),
  34.                             f'{channel}/{message.id}',
  35.                             message.raw_text,
  36.                             json.dumps(emotions_dict, ensure_ascii=False)])
  37.  
  38.  
  39.             if k > posts_to_get: break
  40.             else: k += 1
  41.  
  42.  
  43.  
  44.  
  45.  
  46.     gc = gspread.service_account(filename=creds)
  47.  
  48.     sh = gc.open_by_url(gs_url)
  49.  
  50.     worksheet = sh.worksheet("Лист1")
  51.  
  52.     # Проверка, если ли такой пост уже в базе. Если есть, удаляем из списка на добавление
  53.     all_values_in_gs = worksheet.get_all_values()
  54.  
  55.     existing_rows = []
  56.  
  57.     if len(all_values_in_gs) > 1:
  58.         existing_rows = set([x[1] for x in all_values_in_gs])
  59.  
  60.     out_lst = [x for x in out_lst if x[1] not in existing_rows]
  61.  
  62.     worksheet.append_rows(out_lst, table_range='A1')
  63.  
  64.  
  65. with client:
  66.     client.start(phone_number)
  67.     client.loop.run_until_complete(main(posts_to_get, channels_to_review))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement