async def get_data(**kwargs): return { "name": "Tishka17", "extended": False, } def is_tishka17(data: Dict, widget: Whenable, manager: DialogManager): return data.get("name") == "Tishka17" window = Window( Multi( Const("Hello"), Format("{name}", when="extended"), sep=" " ), Group( Row( Button(Const("Wait"), id="wait"), Button(Const("Ignore"), id="ignore"), when="extended", ), Button(Const("Admin mode"), id="nothing", when=is_tishka17), ), state=MySG.main, getter=get_data, )
from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram_dialog import Window from aiogram_dialog.widgets.kbd import Button from aiogram_dialog.widgets.text import Const class MySG(StatesGroup): main = State() main_window = Window( Const("Hello, unknown person"), # just a constant text Button(Const("Useless button"), id="nothing"), # button with text and id MySG.main, # state is used to identify window between dialogs )
# name input dialog class Bg(StatesGroup): progress = State() async def get_bg_data(dialog_manager: DialogManager, **kwargs): return {"progress": dialog_manager.context.data("progress", 0)} bg_dialog = Dialog( Window( Multi( Const("Your click is processing, please wait..."), Progress("progress", 10), ), state=Bg.progress, getter=get_bg_data, ), ) # main dialog class MainSG(StatesGroup): main = State() async def start_bg(c: CallbackQuery, button: Button, manager: DialogManager): await manager.start(Bg.progress) asyncio.create_task(background(c, manager.bg()))
from aiogram_dialog import Dialog, Window from aiogram_dialog.widgets.kbd import Row, SwitchTo, Next, Back from aiogram_dialog.widgets.text import Const class DialogSG(StatesGroup): first = State() second = State() third = State() dialog = Dialog( Window( Const("First"), SwitchTo(Const("To second"), id="sec", state=DialogSG.second), state=DialogSG.first, ), Window( Const("Second"), Row( Back(), Next(), ), state=DialogSG.second, ), Window( Const("Third"), Back(), state=DialogSG.third, )
manager.context.set_data("name", m.text) await dialog.next(manager) async def get_name_data(dialog_manager: DialogManager, **kwargs): return {"name": dialog_manager.context.data("name", None)} async def on_finish(c: CallbackQuery, button: Button, manager: DialogManager): await manager.done({"name": manager.context.data("name")}) name_dialog = Dialog( Window( Const("What is your name?"), Cancel(), MessageInput(name_handler), state=NameSG.input, ), Window(Format("Your name is `{name}`, it is correct?"), Row(Back(Const("No")), Button(Const("Yes"), id="yes", on_click=on_finish)), state=NameSG.confirm, getter=get_name_data)) # main dialog class MainSG(StatesGroup): main = State() async def process_result(result: Any, manager: DialogManager):
itemgetter(0), items, ) dialog1 = Dialog( Window( Const("Hello, {name}!"), Format("Hello, {name}!\n", when=lambda data, w, m: data["age"] > 18), Format("Now: {now}"), Progress("progress", 10), Progress("progress2", 10, filled="🟩"), Group( Button(Format("{name}"), "b1"), Button(Const("Is it Fun?"), "b2", on_click=fun), Checkbox(Const("Yes"), Const("No"), "check"), width=100, ), select, radio, multiselect, Button(Format("{now}"), "b3"), Row(Button(Progress("progress", 5), "b3"), Button(Progress("progress2", 5, filled="🟩"), "b4")), Next(), MessageInput(input_fun), getter=get_data, state=Register.hello, ), Window( Const("Выберите время начала"), Group(*[ Button(Const(f"{h % 24:2}:{m:02}"), f"{h}_{m}") for h in range(20, 26) for m in range(0, 60, 15)
itemgetter(0), items, multiple=True ) dialog1 = Dialog(Window( Multi( Const("Hello, {name}!"), Format("Hello, {name}!", when=lambda data, w, m: data["age"] > 18), sep="\n\n", ), Group( Group( Button(Format("{name}"), "b1"), Button(Const("Is it Fun?"), "b2", on_click=fun), Checkbox(Const("Yes"), Const("No"), "check"), keep_rows=False ), select, multiselect, Button(Const("3. {name}"), "b3"), Next(), ), getter=get_data, state=Register.hello, on_message=input_fun, ), Window(Const("Выберите время начала"), Group( Group(*[ Button(Const(f"{h % 24:2}:{m:02}"), f"{h}:{m}") for h in range(20, 26) for m in range(0, 60, 15)
multi = Multiselect( Format("✓ {item[0]}"), # E.g `✓ Apple` Format("{item[0]}"), id="check", item_id_getter=operator.itemgetter(1), items="fruits", ) dialog = Dialog( Window( Format("Clicked: {counter}\n\n{stack}\n\n{context}\n\n{now}"), Button(Const("Click me!"), id="btn1", on_click=on_click), multi, Cancel(), MessageInput(name_handler), # Inputs work only in default stack! state=DialogSG.greeting, getter=get_data, ), ) 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) # register handler which resets stack and start dialogs on /start command registry.register_start_handler(DialogSG.greeting)
if m.content_type['PHOTO']: print("оп у нас тут фоточка образовалась") await manager.start(Broadcast.broadcast_image, m.photo[0].file_id, reset_stack=False) else: await m.answer(text="Прикрепите фотографию") broadcast = Dialog( Window( Format("<b>Следующие роли получат рассылку:</b>" "\n• {selected}"), types_kbd, Group(Button(Const("Отмена"), id="Cancel", on_click=on_finish), Next(Const("Далее")), width=2, keep_rows=False), getter=get_data, state=Broadcast.broadcast_type, ), Window( Format("<b>Следующие роли получат рассылку:</b>" "\n• {selected}" "\n\n<b>Текст рассылаемого сообщения:</b>" "\n{text}" "\n\n<i>Поддерживается встроенное в Telegram форматирование!" "\nМаксимальное кол-во символов: 4096</i>"), Url(Const("Про форматирование"), Const("https://lifehacker.ru/formatirovanie-teksta-v-telegram/")), Button(Const("Отмена"), id="Cancel", on_click=on_finish),
async def to_second(c: CallbackQuery, button: Button, manager: DialogManager): await manager.dialog().switch_to(DialogSG.second, manager) async def go_back(c: CallbackQuery, button: Button, manager: DialogManager): await manager.dialog().back(manager) async def go_next(c: CallbackQuery, button: Button, manager: DialogManager): await manager.dialog().next(manager) dialog = Dialog( Window( Const("First"), Button(Const("To second"), id="sec", on_click=to_second), state=DialogSG.first, ), Window( Const("Second"), Row( Button(Const("Back"), id="back2", on_click=go_back), Button(Const("Next"), id="next2", on_click=go_next), ), state=DialogSG.second, ), Window( Const("Third"), Button(Const("Back"), id="back3", on_click=go_back), state=DialogSG.third, ))
from aiogram.types import ParseMode from aiogram_dialog import Window from aiogram_dialog.widgets.text import Jinja class DialogSG(StatesGroup): ANIMALS = State() # let's assume this is our window data getter async def get_data(**kwargs): return { "title": "Animals list", "animals": ["cat", "dog", "my brother's tortoise"] } html_text = Jinja(""" <b>{{title}}</b> {% for animal in animals %} * <a href="https://yandex.ru/search/?text={{ animal }}">{{ animal|capitalize }}</a> {% end for %} """) window = Window( html_text, parse_mode=ParseMode.HTML, # do not forget to set parse mode state=DialogSG.ANIMALS )
from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram_dialog import Window, Dialog from aiogram_dialog.widgets.kbd import Button from aiogram_dialog.widgets.text import Const, Format class MySG(StatesGroup): main = State() async def get_data(**kwargs): return { "name": "Tishka17", } dialog = Dialog( Window( Format("Hello, {name}!"), Button(Const("Useless button"), id="nothing"), MySG.main, getter=get_data, # here we set our data getter ) )
class RenderSG(StatesGroup): first = State() second = State() last = State() async def on_input(m: Message, dialog: Dialog, manager: DialogManager): manager.current_context().dialog_data["name"] = m.text await dialog.next(manager) # rendering tool cannot detect this call dialog = Dialog( Window( Const("1. First"), Next(), state=RenderSG.first, ), Window( Const("2. Second"), Back(), MessageInput(on_input), state=RenderSG.second, preview_add_transitions=[Next()], # this is a hint for rendering tool ), Window( Const("3. Last"), Back(), state=RenderSG.last, ), )
# TODO это костыль await manager.done() from aiogram_dialog.data import DialogContext DialogContext(manager.proxy, "", None).last_message_id = None city_window = Window( text=text.Const("Let's start.\nChoose city"), kbd=kbd.Group(kbd.Group( kbd.Radio( checked_text=text.Format("✅ {item}"), unchecked_text=text.Format("{item}"), items=db.get_cities_list(), item_id_getter=lambda x: x, id="city_select", on_state_changed=set_selected_city, ), keep_rows=False, width=2, ), kbd.Next( when=lambda d, w, m: m.dialog().find("city_select").get_checked(m) is not None, ), ), state=PosterCreation.city, ) area_choice_window = Window( text=text.Format( "Chosen city: {city_name}\n" "Would you like to specify city area?" ),
async def on_finish(c: CallbackQuery, button: Button, manager: DialogManager): await c.message.answer("Thank you. To start again click /start") await manager.done() async def on_age_changed(c: ChatEvent, item_id: str, select: Select, manager: DialogManager): manager.context.set_data("age", item_id) await manager.dialog().next(manager) dialog = Dialog( Window( text=Const("Greetings! Please, introduce yourself:"), kbd=None, state=DialogSG.greeting, on_message=name_handler, ), Window( text=Format("{name}! How old are you?"), kbd=Select( Format("{item}"), items=["0-12", "12-18", "18-25", "25-40", "40+"], item_id_getter=lambda x: x, id="w_age", on_click=on_age_changed, ), state=DialogSG.age, getter=get_data, ), Window(
from aiogram_dialog import Window, Dialog, DialogRegistry, DialogManager, StartMode from aiogram_dialog.widgets.kbd import Button from aiogram_dialog.widgets.text import Const storage = MemoryStorage() bot = Bot(token='BOT TOKEN HERE') dp = Dispatcher(bot, storage=storage) registry = DialogRegistry(dp) class MySG(StatesGroup): main = State() main_window = Window( Const("Hello, unknown person"), Button(Const("Useless button"), id="nothing"), state=MySG.main, ) dialog = Dialog(main_window) registry.register(dialog) @dp.message_handler(commands=["start"]) async def start(m: Message, dialog_manager: DialogManager): await dialog_manager.start(MySG.main, mode=StartMode.RESET_STACK) if __name__ == '__main__': executor.start_polling(dp, skip_updates=True)
class RenderSG(StatesGroup): first = State() second = State() last = State() async def on_input(m: Message, dialog: Dialog, manager: DialogManager): manager.current_context().dialog_data["name"] = m.text await dialog.next(manager) dialog = Dialog( Window( Const("1. First"), Next(), state=RenderSG.first, ), Window( Const("2. Second"), Back(), MessageInput(on_input), state=RenderSG.second, ), Window( Const("3. Last"), Back(), state=RenderSG.last, ), )