简体   繁体   中英

How to implement the simultaneous use of the Telegram bot by multiple users?

Learning to write bots in Python. For example, I chose a bot exchanger for the exmo exchange. When I turn to the bot alone, everything works fine, but when from several accounts at the same time, the bot confuses the variables and gives incorrect data, help, who can) This is my code(sorry for my bad English I'm Russian, but in our forums nobody can help me): '''

class MyBot:
    def __init__(self, bot,keyboard1, keyboard2, keyboard3,summa_code,summa_payment):
        self.bot=bot
        self.keyboard1=keyboard1
        self.keyboard1.row('EXMO')
        self.keyboard2=keyboard2
        self.keyboard2.row('Да',' Нет')
        self.keyboard3=keyboard3
        self.keyboard3.row('Я ОПЛАТИЛ')
        self.summa_code=summa_code
        self.summa_payment=summa_payment

'''
'''
import config
import mail
import exmo_exchange
import telebot
from telebot import types
from random import randint
from class_bot import *
        
summa_code=0
summa_payment=''
mybot_1=MyBot(telebot.TeleBot(config.token),telebot.types.ReplyKeyboardMarkup(True),telebot.types.ReplyKeyboardMarkup(True), telebot.types.ReplyKeyboardMarkup(True),summa_code,summa_payment)           

@mybot_1.bot.message_handler(commands=['start'])
def start_messages(message):
    msg=mybot_1.bot.send_message(message.chat.id, 'Привет, что хотите обменять?: ',reply_markup=mybot_1.keyboard1)

@mybot_1.bot.message_handler(content_types=["text"])
def send_text(message):
    try:
        if message.text.lower()=='exmo':
            msg=mybot_1.bot.send_message(message.chat.id,'Введите сумму в EXMO')
        elif message.text.lower()=='btc':
            msg=mybot_1.bot.send_message(message.chat.id,'Введите сумму в BTC')
        mybot_1.bot.register_next_step_handler(msg, send_digit)
    except Exception as e:
        mybot_1.bot.reply_to(message,'Чтобы начать сначала нажмите "/start"')


def send_digit (message):
    summ=message.text
    if summ.isdigit():
        **mybot_1.summa_code=int(summ)**
        summ2=int(summ)*1.10
        summ3=int(summ2)+randint(-3,+9)
        **mybot_1.summa_payment=str(summ3)**
        answer=str(summ3)+' рублей на карту'
        msg=mybot_1.bot.send_message(message.chat.id,answer)
        msg=mybot_1.bot.send_message(message.chat.id,' Готов?',reply_markup=mybot_1.keyboard2)
        mybot_1.bot.register_next_step_handler(msg, send_number)
    else:
        msg=mybot_1.bot.send_message(message.chat.id,'Вы ввели некорректные данные. Чтобы начать сначала, нажмите "/start"')
        mybot_1.bot.register_next_step_handler(msg, start_messages)
        

def send_number (message):
    if message.text.lower()=='да':
        number='5555 5555 5555 5555'
        answer='Переведите на номер карты "Тинькофф ": '+number+''' указанную выше сумму.
            После оплаты нажмите ОДИН РАЗ "Я ОПЛАТИЛ" и ждите получения кода.
            Как только средства поступят, бот выдаст код. Не нужно жать кнопку несколько раз.
            ПЕРЕВОДИТЕ ТОЧНО ТУ СУММУ, ЧТО УКАЗАНА БОТОМ, ИНАЧЕ ВОЗНИКНУТ СЛОЖНОСТИ С ВЫДАЧЕЙ КОДА'''
        msg=mybot_1.bot.send_message(message.chat.id, answer,reply_markup=mybot_1.keyboard3 )
        mybot_1.bot.register_next_step_handler(msg, send_code)
    else:
        msg=mybot_1.bot.send_message(message.chat.id, 'Чтобы начать сначала нажмите "/start" ')
        mybot_1.bot.register_next_step_handler(msg, start_messages)
        

def send_code(message):
    if message.text.lower()=='я оплатил':
        user_id=message.from_user.id
        name_of_user=message.from_user.username
        excode_to_send=mail.email_check(**mybot_1.summa_code,mybot_1.summa_payment**)
        msg=mybot_1.bot.send_message(message.chat.id,excode_to_send)
        
mybot_1.bot.polling()

'''

It seems like I have found a solution. I also faced with this problem. First thing I did is OOP.

  1. Created class User.
  2. Added methods and attributes to the class.

I also used Google Sheets API as a database. So when new user send /start command program creates new object, then add it to the database. When existed user send /start command program just find him in database and copy to the object. But if you launch this it won't work with several users. Cause every time it just replaces user attributes and you can't work with previous user. To fix it I've created dictionary. Key is chat_id of user, value is User object. Simple code looks like this:

import telebot
    users = {}
    bot = telebot.TeleBot(token, parse_mode=None) #Bot initialiaze
    
    class User:
        def __init__(self, chat_id, first_name, last_name):
            self.chat_id = chat_id
            self.first_name = first_name
            self.last_name = last_name
            
    @bot.message_handler(commands=['start'])
    def greetings(message):
        users["{0}".format(message.chat.id)] = User(message.chat.id, message.from_user.first_name, message.from_user.last_name)
    
    @bot.message_handler(content_types = ['text']
    def simple_response(message):
        bot.send_message(users["{0}".format(message.chat.id)], text = users["{0}".format(message.chat.id)].first_name + ": " + message.text)
        
    if __name__ == '__main__':
        bot.polling()

As you can see it's always finds key equal to message.chat.id, once it found you get user with exactly his data, because value of this key is User object. Hope I answered your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM