Skip to content

Commit

Permalink
Merge pull request #370 from IvanKirpichnikov/update-examples
Browse files Browse the repository at this point in the history
#360 Update example
  • Loading branch information
Tishka17 authored Feb 8, 2024
2 parents 13e9a7d + d4a3e47 commit 770a116
Show file tree
Hide file tree
Showing 17 changed files with 153 additions and 95 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Each window consists of:


```python
from aiogram.filters.state import StatesGroup, State
from aiogram.fsm.state import StatesGroup, State
from aiogram_dialog.widgets.text import Format, Const
from aiogram_dialog.widgets.kbd import Button
from aiogram_dialog import Window
Expand All @@ -84,7 +84,7 @@ Window(
Window itself can do nothing, just prepares message. To use it you need dialog:

```python
from aiogram.filters.state import StatesGroup, State
from aiogram.fsm.state import StatesGroup, State
from aiogram_dialog import Dialog, Window


Expand Down Expand Up @@ -122,7 +122,7 @@ For example in `/start` command handler:
async def user_start(message: Message, dialog_manager: DialogManager):
await dialog_manager.start(MySG.first, mode=StartMode.RESET_STACK)

dp.message.register(user_start, F.text == "/start")
dp.message.register(user_start, CommandStart())
```

> **Info:** Always set `mode=StartMode.RESET_STACK` in your top level start command. Otherwise, dialogs are stacked just as they do
Expand Down
17 changes: 9 additions & 8 deletions example/custom_media_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
from io import BytesIO
from typing import Union


from aiogram import Bot, Dispatcher
from aiogram.filters import CommandStart
from aiogram.fsm.state import State, StatesGroup
from aiogram.types import BufferedInputFile, ContentType, InputFile, Message
from PIL import Image, ImageDraw, ImageFont


from aiogram_dialog import (
Dialog, DialogManager, setup_dialogs,
StartMode, Window,
Expand All @@ -20,15 +22,11 @@
from aiogram_dialog.widgets.media import StaticMedia
from aiogram_dialog.widgets.text import Const


src_dir = os.path.normpath(os.path.join(__file__, os.path.pardir))

API_TOKEN = os.getenv("BOT_TOKEN")


class DialogSG(StatesGroup):
custom = State()
custom2 = State()
normal = State()
CUSTOM_URL_PREFIX = "my://"


def draw(text) -> bytes:
Expand All @@ -50,12 +48,15 @@ def draw(text) -> bytes:
return io.read()


CUSTOM_URL_PREFIX = "my://"
class DialogSG(StatesGroup):
custom = State()
custom2 = State()
normal = State()


class CustomMessageManager(MessageManager):
async def get_media_source(
self, media: MediaAttachment, bot: Bot,
self, media: MediaAttachment, bot: Bot,
) -> Union[InputFile, str]:
if media.file_id:
return await super().get_media_source(media, bot)
Expand Down
16 changes: 12 additions & 4 deletions example/input_media_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@ class Medias(StatesGroup):
start = State()


async def on_input_photo(message: Message, widget: MessageInput,
dialog_manager: DialogManager):
async def on_input_photo(
message: Message,
widget: MessageInput,
dialog_manager: DialogManager,
):
dialog_manager.dialog_data.setdefault("photos", []).append(
(message.photo[-1].file_id, message.photo[-1].file_unique_id),
)
Expand Down Expand Up @@ -72,8 +75,13 @@ async def getter(dialog_manager: DialogManager, **kwargs) -> dict:
NumberedPager(scroll="pages", when=F["pages"] > 1),
width=8,
),
Button(Format("🗑️ Delete photo #{media_number}"), id="del",
on_click=on_delete, when="media_count"),
Button(
Format("🗑️ Delete photo #{media_number}"),
id="del",
on_click=on_delete,
when="media_count",
# Alternative F['media_count']
),
MessageInput(content_types=[ContentType.PHOTO], func=on_input_photo),
getter=getter,
state=Medias.start,
Expand Down
4 changes: 1 addition & 3 deletions example/launch_modes.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,7 @@ async def main():
storage = MemoryStorage()
bot = Bot(token=API_TOKEN)
dp = Dispatcher(storage=storage)
dp.include_router(banner)
dp.include_router(product)
dp.include_router(main_menu)
dp.include_routers(banner, product, main_menu)

dp.message.register(start, CommandStart())
setup_dialogs(dp)
Expand Down
6 changes: 4 additions & 2 deletions example/list_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
from aiogram.types import Message

from aiogram_dialog import (
Dialog, DialogManager, LaunchMode, setup_dialogs, StartMode, SubManager,
Dialog, DialogManager, LaunchMode,
setup_dialogs, StartMode, SubManager,
Window,
)
from aiogram_dialog.widgets.kbd import (
Checkbox, ListGroup, ManagedCheckbox, Radio, Row,
Checkbox, ListGroup,
ManagedCheckbox, Radio, Row,
)
from aiogram_dialog.widgets.text import Const, Format

Expand Down
10 changes: 7 additions & 3 deletions example/loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
from aiogram.types import CallbackQuery, Message

from aiogram_dialog import (
BaseDialogManager, Dialog, DialogManager, setup_dialogs, StartMode, Window,
BaseDialogManager, Dialog, DialogManager,
setup_dialogs, StartMode, Window,
)
from aiogram_dialog.widgets.kbd import Button
from aiogram_dialog.widgets.text import Const, Multi, Progress
Expand Down Expand Up @@ -46,8 +47,11 @@ class MainSG(StatesGroup):
main = State()


async def start_bg(callback: CallbackQuery, button: Button,
manager: DialogManager):
async def start_bg(
callback: CallbackQuery,
button: Button,
manager: DialogManager,
):
await manager.start(Bg.progress)
asyncio.create_task(background(callback, manager.bg()))

Expand Down
17 changes: 10 additions & 7 deletions example/mega/bot_dialogs/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
Calendar, CalendarScope, ManagedCalendar, SwitchTo,
)
from aiogram_dialog.widgets.kbd.calendar_kbd import (
CalendarDaysView, CalendarMonthView, CalendarScopeView, CalendarYearsView,
CalendarDaysView, CalendarMonthView,
CalendarScopeView, CalendarYearsView,
DATE_TEXT, TODAY_TEXT,
)
from aiogram_dialog.widgets.text import Const, Format, Text
Expand Down Expand Up @@ -77,17 +78,19 @@ def _init_views(self) -> Dict[CalendarScope, CalendarScopeView]:


async def on_date_clicked(
callback: ChatEvent, widget: ManagedCalendar,
manager: DialogManager,
selected_date: date, /,
callback: ChatEvent,
widget: ManagedCalendar,
manager: DialogManager,
selected_date: date, /,
):
await callback.answer(str(selected_date))


async def on_date_selected(
callback: ChatEvent, widget: ManagedCalendar,
manager: DialogManager,
clicked_date: date, /,
callback: ChatEvent,
widget: ManagedCalendar,
manager: DialogManager,
clicked_date: date, /,
):
selected = manager.dialog_data.setdefault(SELECTED_DAYS_KEY, [])
serial_date = clicked_date.isoformat()
Expand Down
5 changes: 3 additions & 2 deletions example/mega/bot_dialogs/counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ async def getter(dialog_manager: DialogManager, **kwargs):


async def on_text_click(
event: CallbackQuery, widget: ManagedCounter,
dialog_manager: DialogManager,
event: CallbackQuery,
widget: ManagedCounter,
dialog_manager: DialogManager,
) -> None:
await event.answer(f"Value: {widget.get_value()}")

Expand Down
4 changes: 1 addition & 3 deletions example/mega/bot_dialogs/mutltiwidget.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from aiogram_dialog import (
Dialog, Window,
)
from aiogram_dialog import Dialog, Window
from aiogram_dialog.widgets.kbd import Checkbox, Counter, Multiselect, Radio
from aiogram_dialog.widgets.text import Const, Format
from . import states
Expand Down
8 changes: 3 additions & 5 deletions example/mega/bot_dialogs/reply_buttons.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from aiogram_dialog import (
Dialog, Window,
)
from aiogram_dialog import Dialog, Window
from aiogram_dialog.widgets.kbd import (
Checkbox, Radio, RequestContact, RequestLocation, Row,
Checkbox, Radio, RequestContact,
RequestLocation, Row,
)
from aiogram_dialog.widgets.markup.reply_keyboard import ReplyKeyboardFactory
from aiogram_dialog.widgets.text import Const, Format
Expand All @@ -12,7 +11,6 @@
reply_kbd_dialog = Dialog(
Window(
Const("Reply keyboard with multiple widgets.\n"),

Row(
RequestContact(Const("👤 Send contact")),
RequestLocation(Const("📍 Send location")),
Expand Down
14 changes: 6 additions & 8 deletions example/mega/bot_dialogs/scrolls.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import calendar
from operator import itemgetter

from aiogram_dialog import (
Dialog, DialogManager, Window,
)
from aiogram_dialog import Dialog, DialogManager, Window
from aiogram_dialog.widgets.common import sync_scroll
from aiogram_dialog.widgets.kbd import (
CurrentPage, FirstPage, LastPage, Multiselect, NextPage, NumberedPager,
PrevPage, Row, ScrollingGroup, StubScroll, SwitchTo,
CurrentPage, FirstPage, LastPage,
Multiselect, NextPage, NumberedPager,
PrevPage, Row, ScrollingGroup,
StubScroll, SwitchTo,
)
from aiogram_dialog.widgets.media import StaticMedia
from aiogram_dialog.widgets.text import Const, Format, List, ScrollingText
Expand Down Expand Up @@ -215,9 +215,7 @@ async def paging_getter(dialog_manager: DialogManager, **_kwargs):
Format("Day by number is {day}"),
StaticMedia(path=Format("media/{current_page}.png")),
StubScroll(id=ID_STUB_SCROLL, pages="pages"),
NumberedPager(
scroll=ID_STUB_SCROLL,
),
NumberedPager(scroll=ID_STUB_SCROLL),
SCROLLS_MAIN_MENU_BUTTON,
state=states.Scrolls.STUB,
getter=paging_getter,
Expand Down
11 changes: 6 additions & 5 deletions example/mega/bot_dialogs/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

from aiogram_dialog import Dialog, DialogManager, Window
from aiogram_dialog.widgets.kbd import (
Column, Multiselect, Radio, Select, SwitchTo, Toggle,
Column, Multiselect, Radio,
Select, SwitchTo, Toggle,
)
from aiogram_dialog.widgets.text import Const, Format, List
from . import states
Expand Down Expand Up @@ -49,10 +50,10 @@ def fruit_id_getter(fruit: Fruit) -> str:


async def on_item_selected(
callback: CallbackQuery,
widget: Any,
manager: DialogManager,
selected_item: str,
callback: CallbackQuery,
widget: Any,
manager: DialogManager,
selected_item: str,
):
await callback.answer(selected_item)

Expand Down
21 changes: 11 additions & 10 deletions example/mega/bot_dialogs/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,23 @@
CHECKBOX_ID = "chk"
EMOJI_ID = "emoji"


async def data_getter(
dialog_manager: DialogManager, **_kwargs,
) -> Dict[str, Any]:
return {
"option": dialog_manager.find(CHECKBOX_ID).is_checked(),
"emoji": dialog_manager.find(EMOJI_ID).get_checked(),
}

main_window = Window(
HEADER,
Const("Step 1. Press Next"),
Next(),
MAIN_MENU_BUTTON,
state=states.Switch.MAIN,
)

input_window = Window(
HEADER,
Const("Step 2. Select options"),
Expand All @@ -38,16 +48,6 @@
state=states.Switch.INPUT,
)


async def data_getter(
dialog_manager: DialogManager, **_kwargs,
) -> Dict[str, Any]:
return {
"option": dialog_manager.find(CHECKBOX_ID).is_checked(),
"emoji": dialog_manager.find(EMOJI_ID).get_checked(),
}


last_window = Window(
HEADER,
Const("Step 3. Your data:"),
Expand All @@ -64,6 +64,7 @@ async def data_getter(
state=states.Switch.LAST,
getter=data_getter,
)

switch_dialog = Dialog(
main_window,
input_window,
Expand Down
18 changes: 13 additions & 5 deletions example/multistack.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
from aiogram.types import CallbackQuery, Message

from aiogram_dialog import (
Dialog, DialogManager, setup_dialogs, StartMode, Window,
Dialog, DialogManager,
setup_dialogs, StartMode, Window,
)
from aiogram_dialog.widgets.input import MessageInput
from aiogram_dialog.widgets.kbd import Button, Cancel, Multiselect, Start
Expand Down Expand Up @@ -47,8 +48,11 @@ async def name_handler(
await message.answer(f"Nice to meet you, {message.text}")


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

Expand All @@ -69,8 +73,12 @@ async def on_click(callback: CallbackQuery, button: Button,
Format("Last text: {last_text}\n"),
Format("{now}"),
Button(Const("Click me!"), id="btn1", on_click=on_click),
Start(Const("Start new stack"), id="s1",
mode=StartMode.NEW_STACK, state=DialogSG.greeting),
Start(
Const("Start new stack"),
mode=StartMode.NEW_STACK,
state=DialogSG.greeting,
id="s1",
),
multi,
Cancel(),
# Inputs work only in default stack
Expand Down
Loading

0 comments on commit 770a116

Please sign in to comment.