I'm writing a Telegram bot on Python using the python-telegram-bot library. The bot's function is to look up POIs around a given location. I have a ConversationHandler with 8 states, and I need to pass some data between those functions, such as the address and coordinates of the place, as well as the search radius. However if I use global variables the bot doesn't work properly when used by multiple people simultaneously. What are the alternatives of introducing global variables?
I have approximately the following code:
# ...
def start(update, context):
context.bot.send_photo(update.message.chat_id, "...", caption="Hello")
return 1
def location(update, context):
global lat, lon, address
address = update.message.text # here i get a variable that i have to use later
lon, lat = get_coordinates(address).split()
keyboard = [
... # an InlineKeyboard
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text("...", reply_markup=reply_markup)
return 2
# ... some other functions ...
def radius(update, context):
global r
r = float(update.message.text) # here i also get a variable that i'll need later
keyboard = [
... # another keyboard
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text("...",
reply_markup=reply_markup)
return 4
def category(update, context):
global lat, lon, r
query = update.callback_query
query.answer()
keyboard = [...]
categories_dict = {
...
}
subcategories = find_subcategories(categories_dict[query.data], lat, lon, r) # here i need to use the variables
...
# ... some other similar functions where i also need those values ...
def main():
updater = Updater(TOKEN)
dp = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
# ... handler states ...
},
fallbacks=[CommandHandler('stop', stop)]
)
dp.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()