如何将按钮值传递到变量



晚上好,你能告诉我如何从按钮传递变量值吗?我试着实现这样的东西,但不幸的是我做不到。这个问题还有其他解决办法吗?

代码:

variable = 0
@dp.callback_query_handler(text="buy ticket")
async def buyit(query: CallbackQuery):
keycheck = InlineKeyboardMarkup(row_width=2).add(
InlineKeyboardButton(text="Privacy", url="http://2.pdf"),
InlineKeyboardButton(text="Offer", url="http://1.pdf"),
InlineKeyboardButton(text="Yes", callback_data="check:1"),
InlineKeyboardButton(text="No", callback_data="check:2"),
)
await query.message.edit_text("Before you buy a ticket, please read the privacy policy and the public offer", reply_markup=keycheck)
global variable
variable = int(query.data.split(":")[1])
if variable == 1:
print(1)
elif variable ==2:
print(2)

例如,如果您想在下一个函数中处理这些变量,您可以将callback_query处理程序与text_contains筛选器一起使用:

@dp.callback_query_handler(text="buy ticket")
async def buyit(query: types.CallbackQuery):
keycheck = InlineKeyboardMarkup(row_width=2).add(
InlineKeyboardButton(text="Privacy", url="http://2.pdf"),
InlineKeyboardButton(text="Offer", url="http://1.pdf"),
InlineKeyboardButton(text="Yes", callback_data="check:1"),
InlineKeyboardButton(text="No", callback_data="check:2"),
)
await query.message.edit_text("Before you buy a ticket, please read the privacy policy and the public offer", reply_markup=keycheck)

@dp.callback_query_handler(text_contains='check:')
async def callback_contains_check(query: types.CallbackQuery):
variable = int(query.data[6:])
if variable == 1:
print(1)
elif variable ==2:
print(2)

或者你可以使用aiogram的回调数据工厂(对我来说看起来更好(:

from aiogram.utils.callback_data import CallbackData

check_cb = CallbackData('check','value')  # check:<value>

@dp.callback_query_handler(text="buy ticket")
async def buyit(query: types.CallbackQuery):
keycheck = InlineKeyboardMarkup(row_width=2).add(
InlineKeyboardButton(text="Privacy", url="http://2.pdf"),
InlineKeyboardButton(text="Offer", url="http://1.pdf"),
InlineKeyboardButton(text="Yes", callback_data=check_cb.new(val="1")), # check is prefix, value is 1 same as next
InlineKeyboardButton(text="No", callback_data="check:2"), # check is prefix, value is 2
)
await query.message.edit_text("Before you buy a ticket, please read the privacy policy and the public offer", reply_markup=keycheck)


@dp.callback_query_handler(check_cb.filter())
async def check_callback_filter(query: types.CallbackQuery, callback_data: dict): 
# callback_data - dictionary for check_cb lools like: 
# {'@': 'check', 'val': '1'} , you could get values by keys
variable = int(callback_data.get('val'))
if variable == 1:
print(1)
elif variable ==2:
print(2)

回调数据工厂允许您拥有不同的回调数据,并在不同的处理程序中对其进行筛选。

示例:

  • 投票:向上:1或投票:向下:1
  • 购买:苹果:1
  • 检查:2
  • 等等

vote_cb = CallbackData('vote','action','qty') # vote is prefix
InlineKeyboardButton(text="👍", callback_data=vote_cb.new(action="up", qty="1")
@dp.callback_query_handler(vote_cb.filter(action='up')) # filter by action

相关内容

  • 没有找到相关文章

最新更新