Telegram bot on aiogram + Google Analytics 4

Hello reader! I want to talk about how I managed to tie Google analytics to the Telegram bot on aiogram.

As an example, python + aiogram will be used, but interaction with the analytics api through regular http requests is described here. So the article is relevant for any language.

A bit of theory

The fact is that Google announced the closure of Universal Analytics and full transition on Google Analytics 4. Googling it became clear that there is very little information about the new analytics, but in principle there is no information about its work with python.

The first problem is related to the fact that Google analytics is designed to track sites by embedding the tracker in the frontend or application with the SDK.

The bot is located at t.me/BSC_TokenExplorer_Bot (It allows you to check the balance of a crypto wallet in the BSC network, but this is not about that now). It can be added as a “site”, but embedding an analytics counter just won’t work, since telegram itself is the frontend, and we only write the backend and interact through the Telegram bot API.

Obviously, due to this circumstance, standard methods for collecting analytics are not suitable for us. And also any libraries that python is so famous for are obsolete due to the transition to a new version.

The Measurement Protocol API comes to the rescue. This feature is still in beta, but Google promises not to make significant changes at this stage, however, there are restrictionswhich are planned to be fixed by the time of release.

It is worth noting here that the Measurement Protocol existed before, but it has changed significantly, and now there are two versions of the documentation, here is the actual.

Let’s move on to the code

In order to fix the event, we need to send the following data:

{
    'client_id': уникальный_айди_пользователя,
  	'events': [{
        'name': название_события,
     }],
}

To this host:

f'https://www.google-analytics.com/mp/collect?measurement_id={MEASUREMENT_ID}&api_secret={API_SECRET}'

Where:

  • MEASUREMENT_ID – data stream identifier (G-code)

  • API_SECRET – The value of the secret key to be created in the Measurement Protocol API tab.

Thus, it was possible to collect data on button clicks:

But the following problem arose: there are no records of the number of active users. The solution was to manually send the interaction time parameter in each event.

'engagement_time_msec': '1'

Since we cannot collect any data about geography, it was decided to send the language code that is set for users in the telegram client as a separate parameter. This data can be pulled from the message object.

'language': код_языка

Since the bot was written in aiogram, which in turn took aiohttp as the basis, we will use it to send analytics. The final code looks like this:

from aiohttp import ClientSession

from data.config import MEASUREMENT_ID, API_SECRET


async def send_analytics(user_id, user_lang_code, action_name):
    """
    Send record to Google Analytics
    """
    params = {
        'client_id': str(user_id),
        'user_id': str(user_id),
        'events': [{
            'name': action_name,
            'params': {
                'language': user_lang_code,
                'engagement_time_msec': '1',
            }
        }],
    }
    async with ClientSession() as session:
        await session.post(
                f'https://www.google-analytics.com/'
                f'mp/collect?measurement_id={MEASUREMENT_ID}&api_secret={API_SECRET}',
                json=params)

We call the function in all handlers that we want to track, as follows:

    await send_analytics(user_id=message.from_user.id,
                         user_lang_code=message.from_user.language_code,
                         action_name="get_balance")

Similar Posts

Leave a Reply

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