コード例 #1
0
ファイル: select.py プロジェクト: Tishka17/aiogram_dialog
from aiogram_dialog.widgets.text import Format


# let's assume this is our window data getter
async def get_data(**kwargs):
    fruits = [
        ("Apple", '1'),
        ("Pear", '2'),
        ("Orange", '3'),
        ("Banana", '4'),
    ]
    return {
        "fruits": fruits,
        "count": len(fruits),
    }


async def on_fruit_selected(c: ChatEvent, select: Select,
                            manager: DialogManager, item_id: str):
    print("Fruit selected: ", item_id)


fruits_kbd = Select(
    Format("{item[0]} ({pos}/{data[count]})"),  # E.g `✓ Apple (1/4)`
    id="s_fruits",
    item_id_getter=operator.itemgetter(
        1),  # each item is a tuple with id on a first position
    items="fruits",  # we will use items from window data at a key `fruits`
    on_click=on_fruit_selected,
)
コード例 #2
0

# let's assume this is our window data getter
async def get_data(**kwargs):
    return {"color": "red", "number": 42}


# This will produce text `Square`
text = Case(
    {
        "red": Const("Square"),
        "green": Const("Unicorn"),
        "blue": Const("Moon"),
    },
    selector="color",
)


# This one will produce text `42 is even!`
def parity_selector(data: Dict, case: Case, manager: DialogManager):
    return data["number"] % 2


text2 = Case(
    {
        0: Format("{number} is even!"),
        1: Const("It is Odd"),
    },
    selector=parity_selector,
)
コード例 #3
0
ファイル: whenable.py プロジェクト: fregat17/aiogram_dialog

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,
)
コード例 #4
0
    for i in range(1, count + 1):
        await asyncio.sleep(1)
        await manager.update({
            "progress": i * 100 / count,
            "progress2": min(100, i * 200 / count)
        })


async def input_fun(m: Message, dialog: Dialog, manager: DialogManager):
    print("input_fun")
    await manager.start(Sub.text, m.text)


items = [("One", 1), ("Two", 2), ("Three", 3), ("Four", 4)]
select = Select(
    Format("{item[0]}"),
    "select",
    itemgetter(0),
    items,
)
radio = Radio(
    Format("🔘 {item[0]}"), Format("◯ {item[0]}"),
    "radio",
    itemgetter(0),
    items,
)
multiselect = Multiselect(
    Format("✓ {item[0]}"), Format("{item[0]}"),
    "mselect",
    itemgetter(0),
    items,
コード例 #5
0
import operator

from aiogram_dialog.widgets.kbd import Multiselect
from aiogram_dialog.widgets.text import Format


# let's assume this is our window data getter
async def get_data(**kwargs):
    fruits = [
        ("Apple", '1'),
        ("Pear", '2'),
        ("Orange", '3'),
        ("Banana", '4'),
    ]
    return {
        "fruits": fruits,
        "count": len(fruits),
    }


fruits_kbd = Multiselect(
    Format("✓ {item[0]}"),  # E.g `✓ Apple`
    Format("{item[0]}"),
    id="m_fruits",
    item_id_getter=operator.itemgetter(1),
    items="fruits",
)
コード例 #6
0
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(
        text=Multi(
            Format("{name}! Thank you for your answers."),
            Const("Hope you are not smoking", when="can_smoke"),
            sep="\n\n",
コード例 #7
0
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):
    if result:
        manager.context.set_data("name", result["name"])
コード例 #8
0
from aiogram_dialog.widgets.text import Multi, Const, Format


# let's assume this is our window data getter
async def get_data(**kwargs):
    return {"name": "Tishka17"}


# This will produce text `Hello! And goodbye!`
text = Multi(
    Const("Hello!"),
    Const("And goodbye!"),
    sep=" ",
)

# This one will produce text `Hello, Tishka17, and goodbye {name}!`
text2 = Multi(
    Format("Hello, {name}"),
    Const("and goodbye {name}!"),
    sep=", ",
)

# This one will produce `01.02.2003T04:05:06`
text3 = Multi(
    Multi(Const("01"), Const("02"), Const("2003"), sep="."),
    Multi(Const("04"), Const("05"), Const("06"), sep=":"),
    sep="T"
)
コード例 #9
0
            text="Ваш текст превышает максимальное кол-во символов (4096)!")


async def broadcast_image(m: Message, dialog: Dialog, manager: DialogManager):
    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>"),
コード例 #10
0
ファイル: getter.py プロジェクト: prostmich/aiogram_dialog
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
    )
)
コード例 #11
0
ファイル: radio.py プロジェクト: prostmich/aiogram_dialog
import operator

from aiogram_dialog.widgets.kbd import Radio
from aiogram_dialog.widgets.text import Format


# let's assume this is our window data getter
async def get_data(**kwargs):
    fruits = [
        ("Apple", '1'),
        ("Pear", '2'),
        ("Orange", '3'),
        ("Banana", '4'),
    ]
    return {
        "fruits": fruits,
        "count": len(fruits),
    }


fruits_kbd = Radio(
    Format("🔘 {item[0]}"),  # E.g `🔘 Apple`
    Format("⚪️ {item[0]}"),
    id="r_fruits",
    item_id_getter=operator.itemgetter(1),
    items="fruits",
)
コード例 #12
0
ファイル: simple.py プロジェクト: drforse/aiogram_dialog
    await manager.done()


async def on_age_changed(c: CallbackQuery, item_id: str, select: Select, manager: DialogManager):
    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(
            checked_text=Format("✓ {item}"), unchecked_text=Format("{item}"),
            items=["0-12", "12-18", "18-25", "25-40", "40+"],
            item_id_getter=lambda x: x,
            min_selected=1,
            id="w_age",
            on_state_changed=on_age_changed,
        ),
        state=DialogSG.age,
        getter=get_data,
    ),
    Window(
        text=Multi(
            Format("{name}! Thank you for your answers."),
            Const("Hope you are not smoking", when="can_smoke"),
コード例 #13
0
            ("Banana", 4),
        ]
    }


async def name_handler(m: Message, dialog: Dialog, manager: DialogManager):
    await m.answer(f"Nice to meet you, {m.text}")


async def on_click(c: CallbackQuery, button: Button, manager: DialogManager):
    counter = manager.current_context().dialog_data.get("counter", 0)
    manager.current_context().dialog_data["counter"] = counter + 1


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,
コード例 #14
0
                        'customers', '🛍 Заказчики')
    }


async def get_text(dialog_manager: DialogManager, **kwargs):
    selected = await get_selected(dialog_manager)
    text = dialog_manager.current_intent().data
    return {
        "selected": selected["selected"],
        "text": text if text is not None else "Отправьте мне текст рассылки",
        "now": datetime.now().isoformat(),
    }


async def get_image(dialog_manager: DialogManager, **kwargs):
    image_id = dialog_manager.current_intent().data
    return {
        "image_id":
        image_id if image_id is not None else "Прикрепите фотографию"
    }


types_kbd = Multiselect(
    Format("✓ {item[0]}"),
    Format("{item[0]}"),
    id="m_types",
    item_id_getter=operator.itemgetter(1),
    min_selected=1,
    items="types",
)