Статистика канала telegram python

Getting Telegram channel statistics using api and python

In some groups in Telegram, interesting and informative statistics are available, which can be viewed not only from a smartphone, but also simple actions with api. And if there are a lot of channels, then in general a very useful thing.

We’ll need

Take a short and exciting journey with TDLib.

  • Login at https://my.telegram.org. Go to “API development tools” and fill out the form (three fields: application name, platform and description)
  • Get api_id and api_hashthey are needed for authorization.
  • Read scary warnings that for using api for flooding and other cheats, your number will be banned forever.

So, TDLib, cross-platform, works with all languages (python too), written in C. Telegram itself kindly helps with the installation of the library linkyou can choose the language, system, and all commands will be written to you.

They immediately offer to consider solutions from third parties and there is a link to specifically alexander-akhmetov/python-telegram. He, so he.

Immediately get the statistics (well, almost)

Import everything you need and log in according to the instructions

import json from telegram.client import Telegram import plotly.graph_objects as go tg = Telegram( api_id='api_id', api_hash="api_hash", phone="+31611111111", # you can pass 'bot_token' instead database_encryption_key='changekey123', ) tg.login() # if this is the first run, library needs to preload all chats # otherwise the message will not be sent result = tg.get_chats() result.wait()

After completing line 11, Telegram will send a code that must be entered. Then you need to get all the chats (14-15), otherwise the miracle will not happen.

Читайте также:  Php создать определенную дату

Further, everything is very simple, the library has an excellent call_method function, which calls everything that is needed from TDLib, and we need to make sure that statistics are available to the group.

params = < 'supergroup_id': 12324890 #id группы (без -100) >result = tg.call_method('getSupergroupFullInfo', params, block=True) if result.update['can_get_statistics']: print('Можно продолжать') else: print("что-то пошло не так")

The library has its own function for getting information about the group, tg.get_supergroup_full_info(-100231243245), but if something goes wrong, None is returned and it’s hard to understand what’s wrong when calling tg.call_method(‘getSupergroupFullInfo’, params, block =True), you can specify block=True and the error will be shown.

params = < 'supergroup_id': -10012324890 >result = tg.call_method('getSupergroupFullInfo', params, block=True) >>Telegram error: > 

In this case, writes that there is no such group.

In general, if there is a cherished flag can_get_statistics==True, we can finally move on to the main thing, call the getChatStatistics method. There are only two options, chat id, and a dark or light theme.

params = < 'chat_id': -10012324890, #тут надо -100 'is_dark': True >stat_resp = tg.call_method('getChatStatistics', params, block=True) stat = stat_resp.update

In response, we get json with all the statistics and enjoy the result.

A bit of visualization

For example, you can visualize the result using plotly

# загружаем данные диаграммы в json member_count_graph=json.loads(stat['member_count_graph']['json_data']) # переводим unix timestamp в обычное время data_x = [ datetime.fromtimestamp(x / 1000).strftime("%m.%d") for x in graph["columns"][0][1:] ] #создаём визуализацию пользователей fig = go.Figure() fig.add_trace(go.Scatter(x=data_x, y=member_count_graph['columns'][1])) fig.show()

Thanks everyone, I hope it’s helpful. So far, this has not been launched into production, so I can’t say how stable and confident everything works.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Telegram Channel Statistic Generator

License

petrinm/tgstats

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Telegram Channel Statistic Generator

Simple Python script to dump Telegram logs and generate html/png statistics.

  1. Dependencies libevent-dev, libssl-dev. (TODO)
  2. Download and compile telegram-cli. Use the test branch!
git clone --recursive -b test https://github.com/vysheng/tg.git tg-test && cd tg-test ./configure --disable-liblua make 

1½) Install Python dependencies.. etc

sudo apt-get install python3-matplotlib pip3 install pytg etc. 
./bin/telegram-cli --json -P 4458 

If the dump script is terminated it stores it’s current offset to «name_offset» file and the script tries always to continue from the last position. Remove the offset file when you need to start from the beginning or use

Note: When executed the first time initdb is required.

Kill the script with CTRL+C when it starts to complain about empty responses.

Kill the scripts with CTRL+C after message id collisions start to occur.

Источник

Аналитика для Telegram-ботов, написанных на Python

На данный момент бум на создание телеграмм-ботов начал сходить, но тема их создания не теряет актуальности. Написано множество библиотек для облегчение взаимодействия с Telegram Bot API, но после создания бота я так и не нашёл скрипта(библиотеки) для получения статистики бота. Поэтому решил написать скрипт для всех ботов на Python. Статистику будем получать, логируя действия пользователей и обрабатывая логи в удобный вид.

Требования для среды

Для использования скрипта нужно установить следующие библиотеки:

pip install datetime pip install pandas

Как внедрить аналитику в своего бота?

Скачайте с репозитория py-скрипт под свою ОС и data.csv файл. Разместите их в папке, где лежит ваш бот.

После подключения используемых вами библиотек в файле с телом бота добавьте строчку:

После команд бота добавьте:

Если вы используете библиотеку telebot, то это должно выглядеть следующим образом:

Также, чтобы получать статистику прямо из бота, нужно добавить в message_handler(content_types=[‘text’]):

if message.text[:(длина ключевого слова)] == '': st = message.text.split(' ') if 'txt' in st or 'тхт' in st: tg_analytic.analysis(st,message.chat.id) with open('%s.txt' %message.chat.id ,'r',encoding='UTF-8') as file: bot.send_document(message.chat.id,file) tg_analytic.remove(message.chat.id) else: messages = tg_analytic.analysis(st,message.chat.id) bot.send_message(message.chat.id, messages)

Ключевое слово нужно придумать и вписать для того, чтобы только вы могли просматривать статистику вашего бота. В репозитории хранится также телеграм-бот с уже внедрённой аналитикой, чтобы вы могли ознакомиться как подключить её на примере.

Какие команды использовать для получение статистики?

К примеру ключевое слово будет «статистика»:

 if message.text[:10] == 'статистика' or message.text[:10] == 'Cтатистика': st = message.text.split(' ') if 'txt' in st or 'тхт' in st: tg_analytic.analysis(st,message.chat.id) with open('%s.txt' %message.chat.id ,'r',encoding='UTF-8') as file: bot.send_document(message.chat.id,file) tg_analytic.remove(message.chat.id) else: messages = tg_analytic.analysis(st,message.chat.id) bot.send_message(message.chat.id, messages) 

* — Есть команды: «пользователи», «команды» и «тхт». Можно использовать одновременно. «Пользователи» даёт статистику по людям за необходимое вам количество дней. «Команды» даёт статистику по командам за необходимое вам количество дней. При указание txt, вы получите файл, в ином случае ответ в телеграмм.

Пример использования команд

Cтатистика 2 пользователи команды

Статистика 2 пользователи команды тхт

Из чего состоит скрипт?

В целом, если вас не интересует работа скрипта, то уже на этом этапе можете закончить чтение статьи и начать внедрение в своего бота.

Первая часть скрипта — это логирование действий пользователей. Я принял решение сохранять только дату, id пользователя и используемую им команду:

def statistics(user_id, command): data = datetime.datetime.today().strftime("%Y-%m-%d") with open('data.csv', 'a', newline="", encoding='UTF-8') as fil: wr = csv.writer(fil, delimiter=';') wr.writerow([data, user_id, command])

Вторая часть — это обработка данных по запросу и вывод необходимой статистики. Мы считываем данные из csv в Pandas группируем по пользователям и командам:

season = int(bid[1]) #Считывание данных в Dataframe df = pd.read_csv('data.csv', delimiter=';', encoding='utf8') #Получение количества всех пользователей и дней number_of_users = len(df['id'].unique()) number_of_days = len(df['data'].unique()) #Узнаём о количестве пользователей в опредёленные дни df_user = df.groupby(['data', 'id']).count().reset_index().groupby('data').count().reset_index() list_of_dates_in_df_user = list(df_user['data']) list_of_number_of_user_in_df_user = list(df_user['id']) list_of_dates_in_df_user = list_of_dates_in_df_user[-season:] list_of_number_of_user_in_df_user = list_of_number_of_user_in_df_user[-season:] #Узнаем о количестве использованых команд по дням df_command = df.groupby(['data', 'command']).count().reset_index() unique_commands = df['command'].unique() commands_in_each_day = [] list_of_dates_in_df_command = list(df_command['data']) list_of_number_of_user_in_df_command = list(df_command['id']) list_of_name_of_command_in_df_command = list(df_command['command']) commands_in_this_day = dict() for i in range(len(list_of_dates_in_df_command)): commands_in_this_day[list_of_name_of_command_in_df_command[i]] = list_of_number_of_user_in_df_command[i] if i + 1 >= len(list_of_dates_in_df_command) or list_of_dates_in_df_command[i] != list_of_dates_in_df_command[i + 1]: commands_in_each_day.append(commands_in_this_day) commands_in_this_day = dict() commands_in_each_day = commands_in_each_day[-season:] 

Ответ пользователю составляется на основе данных из предыдущего шага:

 message_to_user = 'Статистика использования бота за %s %s: \n' % (season, day_type.get(season, 'дней')) message_to_user += 'Всего статистика собрана за %s %s: \n' % (number_of_days, day_type.get(season, 'дней')) if season > number_of_days: season = number_of_days message_to_user += 'Указанное вами количество дней больше,чем имеется\n' \ 'Будет выведена статистика за максимальное возможное время\n' if 'пользователи' in bid: message_to_user += 'За всё время бота использовало: ' + '%s' % number_of_users \ + ' %s ' % users_type.get(number_of_users, 'пользователей') + '\n' \ 'Пользователей за последние %s %s: \n' % (season, day_type.get(season, 'дней')) for days, number, comm_day in zip(list_of_dates_in_df_user, list_of_number_of_user_in_df_user, commands_in_each_day): message_to_user += 'Дата:%s Количество:%d Из них новых:%s\n' % (days, number, comm_day.get('/start', 0)) if 'команды' in bid: message_to_user += 'Статистика команд за последние %s %s: \n' % (season,day_type.get(season, 'дней')) for days, commands in zip(list_of_dates_in_df_user, commands_in_each_day): message_to_user += 'Дата:%s\n' % days for i in unique_commands: if i in commands: message_to_user += '%s - %s раз\n' % (i, commands.get(i)) else: message_to_user += '%s - 0 раз\n' % i 

В конце, после составления ответного сообщения, мы проверяем запрос пользователя на наличее команды «тхт», чтобы решить в каком формате ответить:

if 'txt' in bid or 'тхт' in bid: with open('%s.txt' % user_id, 'w', encoding='UTF-8') as fil: fil.write(message_to_user) fil.close() else: return message_to_user 

Заключение

Скрипт оттестирован и работает в нормальном режиме.

Ключевое слово: «статистика».

Источник

Оцените статью