How to store sessions of a telegram bot user in my db

7.1k views Asked by At

I wanna code a telegram bot, so when I gonna receive messages from a user I should know about last message he/she sent to me and in which step does he/she located. So I should store sessions of the user (I understood this when I searched) but I don't know what exactly should I do?

I know I need a table in a db that stores UserId, ChatId but I don't know these:

  1. How to make a root for steps and store them in db (I mean how do I understand where the user is located now)

  2. What are other columns that I need to store as a session?

  3. How many messages should I store in the database? And do I need one row for each message?

2

There are 2 answers

0
Majeed Askari On

you can create a db with these columns.

UserID, ChatID, State, Name, Age, Gender ...

on each incoming update you will check if user exists on you db then check the user's State and respond appropriately and update the state at the end.

1
91DarioDev On

If you just have to store session in your database you don't need to store messages. Maybe you could want to store also messages but it's not necessarily related.

Let's assume you have a "preferences" menu in your bot where the user can write his input. You ask for the name, age, gender etc. How do your know when the user writes the input of it's about the name or the gender etc?

You save sessions in your db. When the bot receives the message you check in what session the user is in to run the right function.

An easy solution could be a sql database. The primary key column is the telegram user ID ( you additionally can add a chat id column if it's intended to work both in private and group chats) and a "session" column TEXT where you log user steps. The session column can be NULL by default. If the bot expects the gender (because the user issued /gender command) you can update the column "session" with the word "gender" so when the message arrives you know how to handle it checking the gender column of that user id and as soon as you runned the right function, you update to NULL again the column "session".