Skip to content

Instantly share code, notes, and snippets.

@Tishka17
Last active October 5, 2023 10:07
Show Gist options
  • Save Tishka17/741e353080bfba6d6d105dc68fbb0b17 to your computer and use it in GitHub Desktop.
Save Tishka17/741e353080bfba6d6d105dc68fbb0b17 to your computer and use it in GitHub Desktop.
aiogram-dialog Confirmation Dialog with StatesGroup generation
import asyncio
import logging
import operator
from typing import Any, Tuple, List
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher.filters.state import (
StatesGroup, State, StatesGroupMeta,
)
from magic_filter import F
from aiogram_dialog import Dialog, DialogManager, Window, DialogRegistry, Data
from aiogram_dialog.widgets.kbd import Select, Start
from aiogram_dialog.widgets.text import Format, Const, Text
# library code
async def _on_select(event, select, manager: DialogManager, data):
await manager.done(data)
def confirmation_dialog_state(states_group_name: str) -> State:
sg = StatesGroupMeta(
states_group_name,
(StatesGroup,),
{
"alert": State(),
}
)
return sg.alert
def confirmation_dialog(
text: Text, items: List[Tuple[str, str]], state: State,
) -> Dialog:
sg = confirm_state.get_root()
return Dialog(
Window(
text,
Format("{start_data[text]}", when=F["start_data"]["text"]),
Select(
text=Format("{item[0]}"),
id="s",
items=items,
item_id_getter=operator.itemgetter(1),
on_click=_on_select,
),
state=state,
),
)
# main code
confirm_state = confirmation_dialog_state("confirm")
confirm = confirmation_dialog(
text=Const("Are you sure?"),
items=[("Yes", "1"), ("No", "0")],
state=confirm_state,
)
class MainSG(StatesGroup):
main = State()
async def process_result(start_data: Data, result: Any,
manager: DialogManager):
if start_data["id"] == "delete":
if result == "1":
print("Delete it!!!")
await manager.done()
main_menu = Dialog(
Window(
Format("Hello"),
Start(Const("Delete"), id="delete", state=confirm_state,
data={"id": "delete"}),
state=MainSG.main,
),
on_process_result=process_result,
)
API_TOKEN = "PLACE YOUR TOKEN HERE"
async def main():
# real main
logging.basicConfig(level=logging.INFO)
storage = MemoryStorage()
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot, storage=storage)
registry = DialogRegistry(dp)
registry.register_start_handler(MainSG.main)
registry.register(confirm)
registry.register(main_menu)
await dp.start_polling()
if __name__ == '__main__':
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment