Answer the question
In order to leave comments, you need to log in
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
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()
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 questionAsk a Question
731 491 924 answers to any question