How to create a multi-user telegram bot using PyTelegramBotAPI?

Using the PyTelegramBotAPI library, I encountered the fact that the bot I wrote, to put it mildly, does not work very well – when several people used the bot at the same time, the messages overlapped, the wrong data was recorded, and in general some kind of bacchanalia took place.

I want to note that I am just starting my journey and in this article I could accidentally write some nonsense, please do not judge strictly, if anything – correct me)

So, I suggest looking at a code example:

import telebot

bot = telebot.TeleBot('токен')
 возможные состояния пользователя
@bot.message_handler(commands=['start'])
def hello_message(message):
    id1 = message.from_user.id
    bot.send_message(message.chat.id, f'Ваш id {id1}')

Here we can see a small piece of code. The person writes the command /start and we give him his id.

In general, this piece will most likely work without problems, but if this is just a part of the project where we need to remember the id and pass it on to other functions, we will see problems.

Which?

Let's imagine a situation: two users plus or minus press /start at the same time. First, the code is executed for the first user and its id is written, and the same happens with the second user. The second user's id is the last one written to the id1 variable, and yes, the most important thing is that it will be available and will intersect with other users! Functions are available for interaction for all users equally, and if one user from our first function, considered in the example, goes to the next one, where his id will be passed, and then the second user goes to this function, the id of the second user will ultimately be written! This is terrible…)

How can this disease be corrected?

I spent five hours trying to figure out how to fix this, and you know, it turned out to be pretty simple. Here's the new, updated code:

import telebot
import random
bot = telebot.TeleBot('')
states = {}  # словарь для хранения состояний пользователей

START = range(1)  # возможные состояния пользователя
@bot.message_handler(commands=['start'])
def hello_message(message):
    secret = 0
    states[secret] = START
    secret = random.randint(1,49494985894939494944)
    states[secret] = START
    id1 = message.from_user.id
    bot.send_message(message.chat.id, f'Ваш id {id}')

What do we see here?

I added so-called state lines to this code. START = range(1) – these are all possible user states – there can be as many as you like, depending on the functionality of your bot, and they need to be placed in each function. Initially, a dictionary of states was created, it was created outside of all functions. In the first function, at the very beginning, we need to create any variable (in our case, secret), and in this variable we need to write a random value that should not be repeated, then pass this variable further to other functions and similarly write states at the beginning of each function[secret] = (here is the user state). I use the random module to generate a random value. Now, when entering the function, each user will generate their own, say, identification key, and another user will not be able to access this function.

Yes, secret = 0
states[secret] = START
secret = random.randint(1.49494985894939494944)
states[secret] = START

it looks strange, probably, you can do without the first two lines, but for some reason, probably just in case, I did it this way

In general, now nothing will intersect, after entering each function, each user will generate their own key, which will then be transferred to other functions using the register_next_step_handler() method, thus, our bot received a multi-user mode:)

Thank you for your attention) I hope this will help someone)

Similar Posts

Leave a Reply

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