-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtg_reactions_count.py
104 lines (83 loc) · 4.57 KB
/
tg_reactions_count.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# -*- coding: utf-8 -*-
import openpyxl
from pyrogram import Client
from datetime import datetime, timedelta
api_id = ''
api_hash = ''
# Задаем параметры непосредственно в коде
months_period = 3 # Количество месяцев для сохранения постов
first_post_id = 1
last_post_id = 240
channel = "@javaprogbook"
# Вычисляем дату, начиная с которой нужно сохранять посты
start_date = datetime.now() - timedelta(days=30*months_period)
# Создаем новую книгу Excel
workbook = openpyxl.Workbook()
sheet = workbook.active
# Заполняем заголовки столбцов
sheet['A1'] = 'Канал'
sheet['B1'] = 'Ссылка на пост'
sheet['C1'] = 'Количество просмотров'
sheet['D1'] = 'Количество репостов'
sheet['E1'] = 'Сумма реакций'
sheet['F1'] = 'Дата публикации'
# Счетчик строк и столбцов
row = 2
column = 7 # Столбцы с эмодзи начинаются с седьмого столбца
# Словарь для хранения всех возможных реакций
all_reactions = {}
with Client("my_account", api_id, api_hash) as client:
for message_id in range(first_post_id, last_post_id + 1):
print('ID поста: ', message_id)
try:
message = client.get_messages(chat_id=channel, message_ids=message_id)
# Проверяем дату поста
if message.date < start_date:
print(f"Пропускаем пост {message_id} (старше {months_period} месяцев)")
continue
# Проверяем количество просмотров
views = message.views if message.views is not None else 0
if views == 0:
print(f"Пропускаем пост {message_id} (нет просмотров)")
continue # Пропускаем этот пост и переходим к следующему
# Заполняем первый столбец названием канала
sheet.cell(row=row, column=1, value=channel)
# Заполняем второй столбец ссылкой на пост
post_link = f"https://t.me/{channel[1:]}/{message_id}"
sheet.cell(row=row, column=2).hyperlink = post_link
sheet.cell(row=row, column=2).value = post_link
sheet.cell(row=row, column=2).style = "Hyperlink"
# Заполняем третий столбец количеством просмотров
sheet.cell(row=row, column=3, value=views)
# Заполняем четвертый столбец количеством репостов
forwards = message.forwards if message.forwards is not None else 0
sheet.cell(row=row, column=4, value=forwards)
# Проверяем, есть ли реакции на сообщение
total_reactions = 0
if message.reactions:
for reaction in message.reactions.reactions:
emoji = reaction.emoji
count = reaction.count
total_reactions += count
if emoji not in all_reactions:
all_reactions[emoji] = column
sheet.cell(row=1, column=column, value=emoji)
column += 1
sheet.cell(row=row, column=all_reactions[emoji], value=count)
# Записываем сумму реакций в пятый столбец
sheet.cell(row=row, column=5, value=total_reactions)
# Записываем дату публикации в шестой столбец
date = message.date.strftime("%Y-%m-%d %H:%M:%S")
sheet.cell(row=row, column=6, value=date)
row += 1
except Exception as e:
print(f"Error getting message {message_id}: ", e)
# Заполняем нулями отсутствующие реакции
for r in range(2, row):
for c in range(7, column):
if sheet.cell(row=r, column=c).value is None:
sheet.cell(row=r, column=c, value=0)
# Сохраняем книгу Excel
xlsx_name = f"{channel[1:]}_telegram_stats_{months_period}months.xlsx"
workbook.save(xlsx_name)
print(f"Данные сохранены в файл: {xlsx_name}")