为什么我的全局变量在更新后仍然相同



我正在使用python创建一个电报机器人,但我无法更新回调函数中的全局变量,请帮助

我尝试在回调函数中使用全局 FLAG 更新变量,但变量仍然相同

FLAG = 0
def start_all(bot,update):
global FLAG
chat_id = update.message.chat_id
FLAG = 0
sell = telegram.KeyboardButton(text="buy")
buy = telegram.KeyboardButton(text="sell")
custom_keyboard =[[ sell, buy ]]
reply_markup = telegram.ReplyKeyboardMarkup(
custom_keyboard)
bot.send_message(chat_id=chat_id,
text="Thank you",
reply_markup=reply_markup
)

command= update.effective_message.text 


if command == "buy":
buy = Buy()
FLAG = 1
buy.start(bot,update)
elif command == "sell":
sell = Sell()
FLAG = 2
sell.start(bot,update)
else:
#help
pass
def main():
updater = Updater('')
dp = updater.dispatcher
dp.add_handler(CommandHandler('test',test))
dp.add_handler(CommandHandler('start',start_all))
if FLAG == 1:
buy = Buy()
dp.add_handler(MessageHandler(Filters.location, 
buy.start))
elif FLAG == 2:
sell = Sell()
dp.add_handler(MessageHandler(Filters.location, sell.insert_user_to_database)) 
elif FLAG == 0:
dp.add_handler(MessageHandler(Filters.text, start_all)) 

else:
pass

我预计当我单击买入时 FLAG 将是 1,当我点击卖出并检查我是否在 main 函数中单击买入或卖出并相应地处理过滤器时,FLAG 将是 1

我很确定这里的 IF 语句不正确。电报update.message.text不是字符串,因此评估将始终失败并转到pass

尝试将其更改为:

command = str(update.message.text)

编辑:

此外,在我看来,您应该使用这样的查询结构:

def start(update, context):
keyboard = [[InlineKeyboardButton("BUY", callback_data='buy'),
InlineKeyboardButton("SELL", callback_data='sell')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('WANT TO BUY OR SELL?', reply_markup=reply_markup)
updater.dispatcher.add_handler(CommandHandler('start', start))
def flag(update, context):
query = update.callback_query
command = str(update.callback_query.data)
if command == 'buy':
FLAG = 1
#do stuff
elif command == 'sell':
FLAG = 2
#do stuff
else:
pass
updater.dispatcher.add_handler(CallbackQueryHandler(flag))

相关内容

  • 没有找到相关文章

最新更新