Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

like image 702
Dennis Avatar asked Apr 27 '26 19:04

Dennis


1 Answers

the python-telegram-bot library has a built-in solution for exactly that. Please check out this wiki page for more info.

If that link doesn't work, I found on github what I think is the same thing at this page


Disclaimer: I'm currently the maintainer of python-telegram-bot.

like image 50
CallMeStag Avatar answered Apr 29 '26 08:04

CallMeStag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!