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 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(
    phone="+31611111111",  # you can pass 'bot_token' instead
# if this is the first run, library needs to preload all chats
# otherwise the message will not be sent
result = tg.get_chats()

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.

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('Можно продолжать')
    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: {'@type': 'error', 'code': 400, 'message': 'Supergroup not found', '@extra': {'request_id': 'fd88892cac814b4c834973d80004d09a'}}

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

# переводим 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]))

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.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *