写电报机器人时,我如何避免使用全局变量

发布于 2025-01-27 07:25:28 字数 1908 浏览 5 评论 0原文

我正在使用Python-Telegram-Bot库在Python上写电报机器人。该机器人的功能是在给定位置查找POI。我有一个与8个状态的对话人,我需要在这些功能之间(例如地址和坐标)以及搜索半径之间传递一些数据。但是,如果我使用全局变量,当多个人同时使用时,机器人无法正常工作。引入全球变量的替代方法是什么?

我大约有以下代码:


# ...


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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无声静候 2025-02-03 07:25:28

python-telegram-bot库具有一个内置解决方案。请查看 Wiki页面有关更多信息。

如果该链接不起作用,我在github上找到了我认为在此页面


免责声明:我当前是python-telegram-bot-bot的维护者。

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.

如若梦似彩虹 2025-02-03 07:25:28

您可以通过键使用数据存储。

一个简单的解决方案是使用全局dict。但是,可以更好地避免使用全局var,因为您可能会偶然地从某个地方更改此var,甚至不明白为什么代码会做一些奇怪的事情。
可能是您应该使用一些db,例如redis。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文