N
N
Nika9802022-01-03 20:37:00
Python
Nika980, 2022-01-03 20:37:00

How to track users of a telegram bot written in python and where to get their Id?

Earlier I already asked something similar, my question was not entirely clear. In general, I don’t know who launched my bot written in Python, I read somewhere that in order to send out a newsletter to all users of the bot, you need to know the id of everyone, but I don’t know who launched my bot and how to see their id. I would like to know where it is entered / where it is stored / how to withdraw

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2022-01-04
@Vindicar

It was already answered above that you need to register users yourself. I will describe one way how to do it.
I'm assuming the DBMS used is Sqlite , although this could be adapted to others.
We need a user table like this:

import time
import sqlite

connection = sqlite3.connect('bot.db')
cursor = connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS users ( -- всё что после -- комментарий SQL
    id TEXT PRIMARY KEY, -- идентификатор пользователя, он же первичный ключ таблицы
    first_use REAL, -- метка времени, когда пользователь впервые обратился к боту
    last_use REAL -- метка времени, когда пользователь последний раз обратился к боту
)""")
cursor.close()

The fact that we made id the primary key ensures that only one row of the table will correspond to one user.
Then, before executing each command, you need to update this table - add a row if it does not exist, or update the last_use field if it exists. Luckily, there is a syntax to do this in a single request.
def ensure_user_stats(user_id):
    "Эта функция обновляет таблицу users, и должна вызываться в начале обработки каждой команды."
    global connection
    cursor = connection.cursor()
    now = time.time()
    # пытаемся добавить строку с указанным id, и фиксируем текущее время в полях first_use и last_use 
    # если возникает конфликт в поле id (такое id уже есть),
    # то мы обновляем в этой записи поле last_use на текущее время, а остальное не трогаем
    cursor.execute("""INSERT INTO users (id, first_use, last_use) VALUES (?, ?, ?)
    ON CONFLICT (id) DO UPDATE SET last_use = excluded.last_use""", (user_id, now, now))
    cursor.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question