'How do I avoid using global variables when writing a Telegram bot
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()
Solution 1:[1]
the python-telegram-bot library has a built-in solution for exactly that. Please check out this wiki page for more info.
Disclaimer: I'm currently the maintainer of python-telegram-bot.
Solution 2:[2]
You can use data store by key.
A simple solution is to use global dict. However using global vars better avoided, since you may by chance change this var from somewhere and you won't even understand why your code do some strange stuff. May be you should use some DB e.g. Redis.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CallMeStag |
| Solution 2 | Gavriel Cohen |
