Skip to content

Commit

Permalink
Туториал (#8)
Browse files Browse the repository at this point in the history
* Начало туториала

* Ещё чуть туториала

* Туториал по методам, фильтрам, мидлварям, fsm и di

* Туториал доделан

Переименовал файлы доки в cebab-case, указал конкретные members в автогенерации

* Изменения pre-commit хука

* Проверка на корректность документации и туториала, небольшие правки + изменение цветы главных заголовков.

---------

Co-authored-by: Erkut <ZloyBarcyk@yandex.ru>
  • Loading branch information
K1rL3s and ZloyKobra committed Feb 1, 2024
1 parent d2816c8 commit 408eaeb
Show file tree
Hide file tree
Showing 173 changed files with 1,760 additions and 401 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
- Роутеры (Blueprints)
- Машина состояний (Finite State Machine)
- Мидлвари (для входящих событий и вызовов API)
- Использует мощные [магические фильтры](https://github.com/aiogram/magic-filter)
- Мощные [магические фильтры](https://github.com/aiogram/magic-filter)


### Важно!
Expand Down
2 changes: 1 addition & 1 deletion aliceio/types/directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class Directives(MutableAliceObject):
Директивы.
[Source 1](https://yandex.ru/dev/dialogs/alice/doc/response-audio-player.html)
[Source 2](https://yandex.ru/dev/dialogs/alice/doc/response-start-account-linking.html_
[Source 2](https://yandex.ru/dev/dialogs/alice/doc/response-start-account-linking.html)
""" # noqa: E501

audio_player: Optional[AudioPlayerDirective] = None
Expand Down
2 changes: 1 addition & 1 deletion aliceio/types/media_button.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class MediaButton(MutableAliceObject):
"""
Кнопка на изображении для :class:`ImageGallery` и :class:[`ItemsList`]
Кнопка на изображении для :class:`ImageGallery` и :class:`ItemsList`
[Source 1](https://yandex.ru/dev/dialogs/alice/doc/response-card-imagegallery.html#response-card-imagegallery__items-button-desc)
[Source 2](https://yandex.ru/dev/dialogs/alice/doc/response-card-itemslist.html#response-card-itemslist__items-button-desc)
Expand Down
2 changes: 1 addition & 1 deletion aliceio/types/space_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class SpaceStatus(AliceObject):
"""
Оставшееся место в байтах для изображений и звуков.
[Source]https://yandex.ru/dev/dialogs/alice/doc/resource-upload.html#http-images-load__quota
[Source](https://yandex.ru/dev/dialogs/alice/doc/resource-upload.html#http-images-load__quota)
""" # noqa: E501

images: PreQuota
Expand Down
4 changes: 2 additions & 2 deletions aliceio/types/uploaded_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ class UploadedImage(AliceObject):
""" # noqa: E501

id: str
size: int
origUrl: Optional[str] = None
# origUrl будет None если изображение загружено через файл, то есть не через url.
size: int
createdAt: str

if TYPE_CHECKING:
orig_url: ClassVar[Optional[str]]
created_at: ClassVar[Optional[str]]
created_at: ClassVar[str]

def __init__(
__pydantic_self__,
Expand Down
11 changes: 11 additions & 0 deletions docs/_css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ html {
}
}

.md-nav__item--section>.md-nav>.md-nav__list>.md-nav__item>.md-nav__link{
color: var(--md-typeset-a-color) !important;
}

@media screen and (max-width:76.1875em) {
[data-md-color-scheme="slate"] .md-nav--primary .md-nav__title {
background-color: var(--vkbottle-bg-darker);
Expand All @@ -92,3 +96,10 @@ html {
.injected {
display: none;
}

.md-typeset h1 {
color: var(--md-default-fg-color--light);
font-size: 2em;
line-height: 1.3;
margin: 1em 0 0.5em
}
Binary file added docs/_static/middleware_dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/_static/middleware_light.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
17 changes: 17 additions & 0 deletions docs/aliceio/client/skill.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
::: aliceio.client.skill.Skill
handler: python
options:
members:
- id
- skill_id
- token
- oauth_token
- __init__
- __call__
- context
- upload_image
- get_images
- delete_image
- upload_sound
- get_sounds
- delete_sound
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
5 changes: 5 additions & 0 deletions docs/dispatcher/flags.md → docs/aliceio/dispatcher/flags.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,8 @@
handler: python
options:
members: true


## Источники

* [aiogram](https://docs.aiogram.dev/en/dev-3.x/dispatcher/flags.html)
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,3 @@
options:
merge_init_into_class: true
members: true

File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
::: aliceio.dispatcher.middlewares.response_convert
::: aliceio.dispatcher.middlewares.response_convert.ResponseConvertMiddleware
handler: python
options:
members:
Expand Down
File renamed without changes.
77 changes: 77 additions & 0 deletions docs/aliceio/dispatcher/router.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
::: aliceio.dispatcher.router.Router
handler: python
options:
merge_init_into_class: false
members:
- __init__
- include_router
- include_routers


## Наблюдатели

!!! warning "Важно"
Все хэндлеры всегда должны быть асинхронными. Имя функции-обработчика не имеет значения.
Имя аргумента события также не важно, но рекомендуется не перекрывать имя контекстными данными, поскольку функция не может принимать два аргумента с одинаковым именем.

Вот список всех доступных наблюдателей и примеры регистрации хэндлеров.

В этих примерах используется только регистрация через декоратор, но вы всегда можете использовать метод `<router>.<event_type>.register(...)`

### Сообщение (SimpleUtterance)
```python
@router.message()
async def message_handler(message: Message) -> Any: pass
```

### Нажатие на кнопку
```python
@router.button_pressed()
async def button_pressed_handler(button: ButtonPressed) -> Any: pass
```

### Аудиоплеер
```python
@router.audio_player()
async def audio_player_handler(audio_player: AudioPlayer) -> Any: pass
```


### Покупка
```python
@router.purchase()
async def purchase_handler(purchase: Purchase) -> Any: pass
```

### Показ шоу
```python
@router.show_pull()
async def show_pull_handler(pull: ShowPull) -> Any: pass
```

## Вложенные роутеры

Событие будет распространять по роутерам и хэндлерам согласно порядку их добавления.

!!! warning "Важно"
Роутеры могут быть включены в другие роутеры с некоторыми ограничениями:

1. Роутер не может подключить сам себя
2. Роутеры не могут составлять цикл (р1 содержит р2, р2 содержит р3, р3 содерит р1)

## Update
```python
@dispatcher.update()
async def update_handler(update: Update) -> Any: pass
```

!!! warning "Предупреждение"
Только диспетчер может обрабатывать события с типом `Update`.

!!! note "Примечание"
В диспетчере уже есть обработчик этого типа событий, поэтому вы можете использовать его для обработки всех обновлений, которые не обработались другими хэндлерами.


## Источники

* [aiogram](https://docs.aiogram.dev/en/dev-3.x/dispatcher/router.html)
6 changes: 4 additions & 2 deletions docs/enums/all_enums.md → docs/aliceio/enums/all-enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
::: aliceio.enums.base.ValuesEnum
handler: python
options:
members: true
members:
- values

<br/>

::: aliceio.enums.base.StrEnum
handler: python
options:
members: true
members:
- __str__

<br/>

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
86 changes: 86 additions & 0 deletions docs/aliceio/filters/magic-filter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Магический фильтр

!!! note "Примечание"
В aliceio есть небольшая надстройка над магическим фильтром.
Если импортировать его из [magic-filter](https://pypi.org/project/magic-filter/), то метод `.as_()` не будет доступен (о нём в главе про DI).

`MagicFilter` можно вызвать как функцию, он поддерживает некоторые действия и запоминает цепочку атрибутов и действий, которые следует проверить.

Это означает, что вы можете связать методы получения атрибутов в цепочку, описать простые проверки данных, а затем вызвать полученный объект, передав один объект в качестве аргумента.
Например, можно создать цепочку атрибутов `F.foo.bar.baz`, затем добавить действие `F.foo.bar.baz == 'spam'`, а затем вызвать полученный объект `(F.foo.bar.baz == 'spam').resolve(obj)`

### Возможные действия

Магический фильтр поддерживает некоторые логические операции над атрбитуами объекта.

#### Существует ли
```python
F.text # эквивалент `lambda message: message.text`
```

#### Входит ли в коллекцию
```python
F.from_user.id.in_({42, 1000, 123123}) # lambda event: event.from_user.id in {42, 1000, 123123}
F.event_type.in_({'foo', 'bar', 'baz'}) # lambda update: update.event_type in {'foo', 'bar', 'baz'}
```

#### Содержит ли
```python
F.text.contains('foo') # lambda message: 'foo' in message.text
```

#### Regexp
```python
F.text.regexp(r'Hello, .+') # lambda message: re.match(r'Hello, .+', message.text)
```

#### Свои функции

Принимает любой вызываемый объект. Объект будет вызван когда фильтр проверяет результат.
```python
F.chat.func(lambda chat: chat.id == -42) # lambda message: (lambda chat: chat.id == -42)(message.chat)
```

#### Инверсия
Любая доступная операция может быть инвертирована с помощью оператора `~`
```python
~(F.text == 'spam') # lambda message: message.text != 'spam'
~F.text.startswith('spam') # lambda message: not message.text.startswith('spam')
```

#### Комбинация
Все операции могут быть скомбинированы с помощью `&`и `|`
```python
(F.from_user.id == 42) & (F.text == 'admin')
F.text.startswith('a') | F.text.endswith('b')
(F.from_user.id.in_({42, 777, 911})) & (F.text.startswith('!') | F.text.startswith('/')) & F.text.contains('ban')
```

#### Строковые методы
Могут быть использованы только с строковыми атрибутами
```python
F.text.startswith('foo') # lambda message: message.text.startswith('foo')
F.text.endswith('bar') # lambda message: message.text.startswith('bar')
F.text.lower() == 'test' # lambda message: message.text.lower() == 'test'
F.text.upper().in_({'FOO', 'BAR'}) # lambda message: message.text.upper() in {'FOO', 'BAR'}
F.text.len() == 5 # lambda message: len(message.text) == 5
```

### Использование в aliceio
```python
@router.message(F.text == "привет")
@router.button_pressed(F.payload["yes"])
...
```

::: aliceio.utils.magic_filter.MagicFilter
handler: python
options:
members: true

<br/>

::: aliceio.utils.magic_filter.AsFilterResultOperation
handler: python
options:
members: true
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
::: aliceio.types.alice_event.AliceEvent
handler: python
options:
members: true
members:
- user
- from_user
- session
19 changes: 19 additions & 0 deletions docs/aliceio/types/alice-request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
::: aliceio.types.alice_request.AliceRequest
handler: python
options:
members:
- type
- payload
- command
- original_utterance
- markup
- nlu
- error
- purchase_request_id
- purchase_token
- order_id
- purchase_timestamp
- purchase_payload
- signed_data
- signature
- show_type
10 changes: 10 additions & 0 deletions docs/aliceio/types/alice-response.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
::: aliceio.types.alice_response.AliceResponse
handler: python
options:
members:
- response
- session_state
- user_state_update
- application_state
- analytics
- version
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
::: aliceio.types.analytic_event.AnalyticEvent
handler: python
options:
members: true
members:
- name
- value
3 changes: 2 additions & 1 deletion docs/types/analytics.md → docs/aliceio/types/analytics.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
::: aliceio.types.analytics.Analytics
handler: python
options:
members: true
members:
- events
5 changes: 4 additions & 1 deletion docs/types/api_state.md → docs/aliceio/types/api-state.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ ApplicationState = StateDict
::: aliceio.types.api_state.ApiState
handler: python
options:
members: true
members:
- user
- session
- application
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
::: aliceio.types.application.Application
handler: python
options:
members: true
members:
- application_id
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
::: aliceio.types.audio_player_directive.AudioPlayerDirective
handler: python
options:
members: true
members:
- action
- item

<br/>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
::: aliceio.types.audio_player_error.AudioPlayerError
handler: python
options:
members: true
members:
- message
- type
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
::: aliceio.types.audio_player_item.AudioPlayerItem
handler: python
options:
members: true
members:
- stream
- metadata
Loading

0 comments on commit 408eaeb

Please sign in to comment.