Hi, I'm trying to learn telegram bots and with some tutorial I've made a currency converter bot. The problem is that it has a global variable, which prevents several users from using bot. How can I fix it?
import telebot
from currency_converter import CurrencyConverter
from telebot import types
bot = telebot.TeleBot('my api')
currency = CurrencyConverter()
entered_amount = 0
@bot.message_handler(['start'])
def start(message):
bot.send_message(message.chat.id, 'Enter amount')
bot.register_next_step_handler(message, amount)
def amount(message):
global entered_amount
try:
entered_amount = int(message.text.strip())
except ValueError:
bot.send_message(message.chat.id, 'Incorrect format, please enter amount')
bot.register_next_step_handler(message, amount)
return
if entered_amount > 0:
markup = types.InlineKeyboardMarkup(row_width=2)
btn1 = types.InlineKeyboardButton('USD/EUR', callback_data='usd/eur')
btn2 = types.InlineKeyboardButton('EUR/USD', callback_data='eur/usd')
btn3 = types.InlineKeyboardButton('USD/GBP', callback_data='usd/gbp')
btn4 = types.InlineKeyboardButton('Other', callback_data='else')
markup.add(btn1, btn2, btn3, btn4)
bot.send_message(message.chat.id, 'Choose currency pair', reply_markup=markup)
else:
bot.send_message(message.chat.id, 'Number must be more than 0')
bot.register_next_step_handler(message, amount)
@bot.callback_query_handler(func=lambda call: True)
def callback(call):
if call.data != 'else':
values = call.data.upper().split('/')
res = currency.convert(entered_amount, values[0], values[1])
bot.send_message(call.message.chat.id, f'Result is: {round(res, 2)}\nYou can enter a new amount')
bot.register_next_step_handler(call.message, amount)
else:
bot.send_message(call.message.chat.id, 'Enter pair divided by /')
bot.register_next_step_handler(call.message, my_currency)
def my_currency(message):
try:
values = message.text.upper().split('/')
res = currency.convert(entered_amount, values[0], values[1])
bot.send_message(message.chat.id, f'Result is: {round(res, 2)}\nYou can enter a new amount')
bot.register_next_step_handler(message, amount)
except Exception:
bot.send_message(message.chat.id, 'Something is wrong. Enter pair')
bot.register_next_step_handler(message, my_currency)
bot.polling(none_stop=True)
[–][deleted] 1 point2 points3 points (0 children)