From bcbed0a4c1a2f04de71a5dc0cbd894358bc41165 Mon Sep 17 00:00:00 2001 From: Aleksei Krugliak Date: Sun, 3 Apr 2022 14:49:14 +0400 Subject: [PATCH] Testing fabrics for inline keyboards --- handlers/users/__init__.py | 1 + handlers/users/add.py | 32 ++++++++-------- handlers/users/help.py | 3 +- handlers/users/test.py | 78 ++++++++++++++++++++++++++++++++++++++ utils/set_bot_commands.py | 2 +- 5 files changed, 97 insertions(+), 19 deletions(-) create mode 100644 handlers/users/test.py diff --git a/handlers/users/__init__.py b/handlers/users/__init__.py index b4d2505..be157c2 100644 --- a/handlers/users/__init__.py +++ b/handlers/users/__init__.py @@ -3,3 +3,4 @@ from . import start from . import echo from . import add from . import settings +from . import test diff --git a/handlers/users/add.py b/handlers/users/add.py index 4b8d3b3..b7dc837 100644 --- a/handlers/users/add.py +++ b/handlers/users/add.py @@ -1,6 +1,4 @@ from aiogram import types -from aiogram.dispatcher.filters.builtin import Command - from loader import dp @@ -8,18 +6,18 @@ from loader import dp async def bot_add(message: types.Message): await message.answer(f"This is ADD command, {message.from_user.username}!") - @dp.message_handler(state=None) # todo сделать стейты. сейчас это хэндлит все сообщения в любых состояниях! - async def bot_add_parse_message(message: types.Message): - words = message.text.split() - # Uncomment to see debug in console - # print('Split message:') - # i = 0 - # for each in words: - # print('[' + str(i) + ']: ' + '[' + each + ']') - # i += 1 - # print('[end]') - - if len(words) == 2: - await message.answer('[added] ' + words[0] + ' ' + words[1]) - else: - await message.answer("can't parse. wrong arguments!") + # @dp.message_handler(state=None) # todo сделать стейты. сейчас это хэндлит все сообщения в любых состояниях! + # async def bot_add_parse_message(message: types.Message): + # words = message.text.split() + # # Uncomment to see debug in console + # # print('Split message:') + # # i = 0 + # # for each in words: + # # print('[' + str(i) + ']: ' + '[' + each + ']') + # # i += 1 + # # print('[end]') + # + # if len(words) == 2: + # await message.answer('[added] ' + words[0] + ' ' + words[1]) + # else: + # await message.answer("can't parse. wrong arguments!") diff --git a/handlers/users/help.py b/handlers/users/help.py index 9a9bed2..10a1656 100644 --- a/handlers/users/help.py +++ b/handlers/users/help.py @@ -12,7 +12,8 @@ async def bot_help(message: types.Message): "/add - Add expense.", "/edit - Edit expense.", "/list - See my expenses.", - "/settings - Configure bot." + "/settings - Configure bot.", + "/test - Test command." ) await message.answer("\n".join(text)) diff --git a/handlers/users/test.py b/handlers/users/test.py new file mode 100644 index 0000000..7ca67b2 --- /dev/null +++ b/handlers/users/test.py @@ -0,0 +1,78 @@ +from aiogram import types + + +from loader import dp + + +@dp.message_handler(commands="test") +async def cmd_random(message: types.Message): + keyboard = types.InlineKeyboardMarkup() + keyboard.add(types.InlineKeyboardButton(text="Нажми меня", callback_data="random_value")) + keyboard.add(types.InlineKeyboardButton(text="Нажми меня 2", callback_data="random_value2")) + await message.answer("test reply 1-2-3", reply_markup=keyboard) + + +@dp.callback_query_handler(text="random_value") +async def send_random_value(call: types.CallbackQuery): + await call.message.answer('test reply 1') + # shows alert with 'Ok' button + await call.answer(text="Спасибо, что воспользовались ботом!", show_alert=True) + # или просто await call.answer() + + +@dp.callback_query_handler(text="random_value2") +async def send_random_value(call: types.CallbackQuery): + await call.message.answer('test reply 2') + await call.answer() + +######################################################################################## +from aiogram.utils.callback_data import CallbackData +from aiogram.utils.exceptions import MessageNotModified +from contextlib import suppress +# fabnum - префикс, action - название аргумента, которым будем передавать значение +callback_numbers = CallbackData("fabnum", "action") +# Здесь хранятся пользовательские данные. +# Т.к. это словарь в памяти, то при перезапуске он очистится +user_data = {} + + +def get_keyboard_fab(): + buttons = [ + types.InlineKeyboardButton(text="-1", callback_data=callback_numbers.new(action="decr")), + types.InlineKeyboardButton(text="+1", callback_data=callback_numbers.new(action="incr")), + types.InlineKeyboardButton(text="Подтвердить", callback_data=callback_numbers.new(action="finish")) + ] + keyboard = types.InlineKeyboardMarkup(row_width=2) + keyboard.add(*buttons) + return keyboard + + +async def update_num_text_fab(message: types.Message, new_value: int): + with suppress(MessageNotModified): + await message.edit_text(f"Укажите число: {new_value}", reply_markup=get_keyboard_fab()) + + +@dp.message_handler(commands="numbers_fab") +async def cmd_numbers(message: types.Message): + user_data[message.from_user.id] = 0 + await message.answer("Укажите число: 0", reply_markup=get_keyboard_fab()) + + +@dp.callback_query_handler(callback_numbers.filter(action=["incr", "decr"])) +async def callbacks_num_change_fab(call: types.CallbackQuery, callback_data: dict): + user_value = user_data.get(call.from_user.id, 0) + action = callback_data["action"] + if action == "incr": + user_data[call.from_user.id] = user_value + 1 + await update_num_text_fab(call.message, user_value + 1) + elif action == "decr": + user_data[call.from_user.id] = user_value - 1 + await update_num_text_fab(call.message, user_value - 1) + await call.answer() + + +@dp.callback_query_handler(callback_numbers.filter(action=["finish"])) +async def callbacks_num_finish_fab(call: types.CallbackQuery): + user_value = user_data.get(call.from_user.id, 0) + await call.message.edit_text(f"Итого: {user_value}") + await call.answer() diff --git a/utils/set_bot_commands.py b/utils/set_bot_commands.py index 6972b12..8d7763f 100644 --- a/utils/set_bot_commands.py +++ b/utils/set_bot_commands.py @@ -10,7 +10,7 @@ async def set_default_commands(dp): types.BotCommand("edit", "Edit expense."), types.BotCommand("list", "See my expenses."), types.BotCommand("settings", "Configure bot."), - # types.BotCommand("settings2", "Configure bot."), + types.BotCommand("test", "Test command."), # types.BotCommand("settings3", "Configure bot."), ] )