在编写Telegram bot时如何避免使用全局变量?



我正在使用Python - Telegram -bot库在Python上编写一个Telegram bot。bot的功能是查找给定位置周围的poi。我有一个具有8个状态的ConversationHandler,我需要在这些函数之间传递一些数据,比如地址和地点坐标,以及搜索半径。但是,如果我使用全局变量,机器人不能正常工作时,由多人同时使用。引入全局变量的替代方案是什么?

我有大约如下代码:


# ...

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

python-telegram-bot库有一个内置的解决方案。请查看此wiki页面获取更多信息。

如果这个链接不起作用,我在github上找到了我认为在这个页面上是一样的


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

可以按键存储。

一个简单的解决方案是使用全局字典。但是最好避免使用全局变量,因为您可能会偶然地从某个地方更改这个变量,并且您甚至不会理解为什么您的代码会做一些奇怪的事情。也许你应该使用一些数据库,如Redis。

最新更新