aiokilogram


Nameaiokilogram JSON
Version 0.1.3 PyPI version JSON
download
home_pagehttps://github.com/altvod/aiokilogram
SummaryConvenience tools and wrappers for aiogram
upload_time2023-02-01 23:03:47
maintainer
docs_urlNone
authorGrigory Statsenko
requires_python>=3.9
license
keywords telegram aiogram
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # aiokilogram

Convenience tools and wrappers for `aiogram`,
the asynchronous Telegram Bot API framework.


## Installation

```bash
pip install aiokilogram
```


## Basic Examples

### Class-Based Command Handlers

The `aiokilogram` toolkit is centered around the notion of class-based
command handlers. Basically this means that you can group several commands
as methods in a class and assign them to message and callback patterns
at class level.

A simplistic bit will look something like this:

```python
import asyncio
import os
from aiokilogram.bot import KiloBot
from aiokilogram.settings import BaseGlobalSettings
from aiokilogram.handler import CommandHandler
from aiokilogram.registration import register_message_handler

class TestCommandHandler(CommandHandler):
    @register_message_handler(commands={'hello'})
    async def test_handler(self, event) -> None:
        await self.send_text(user_id=event.from_user.id, text=f'This is a test reply')

def run_bot():
    bot = KiloBot(
        global_settings=BaseGlobalSettings(tg_bot_token=os.environ['TG_BOT_TOKEN']),
        handler_classes=[TestCommandHandler],
    )
    asyncio.run(bot.run())

if __name__ == '__main__':
    run_bot()
```

For more info you can take a look at a [boilerplate bot with buttons](boilerplate/button.py)
and [simple boilerplate bot](boilerplate/simple.py)

Set the `TG_BOT_TOKEN` env variable to run them.


### Action Buttons

The package also provides a simplified mechanism of using buttons and 
binding handlers to their callbacks.
This is useful when you want your buttons to contain a combination of
several parameters and don't want to implement their serialization,
deserialization and callback bindings each time.

The idea is simple.

1. Define an action (a `CallbackAction` subclass) using a combination of fields:
```python
from enum import Enum
from aiokilogram.action import CallbackAction, StringActionField, EnumActionField

class ActionType(Enum):
    show_recipe = 'show_recipe'
    like_recipe = 'like_recipe'

class SingleRecipeAction(CallbackAction):
    action_type = EnumActionField(enum_cls=ActionType)
    recipe_title = StringActionField()
```

2. Create a page containing action buttons:
```python
from aiokilogram.page import ActionMessageButton, MessagePage, MessageBody, MessageKeyboard

page = MessagePage(
    body=MessageBody(text='Main Recipe Menu'),
    keyboard=MessageKeyboard(buttons=[
        ActionMessageButton(
            text='Button Text',
            action=SingleRecipeAction(
                action_type=ActionType.show_recipe,
                recipe_title='Fantastic Menemen',
            ),
        ),
        # ...
    ])
)
```

3. Send it as a response to some command in your handler class:
```python
    await self.send_message_page(user_id=event.from_user.id, page=page)
```

4. Define and register a handler method for this action where you deserialize the 
   action parameters and somehow use them in your logic:
```python
class MyHandler(CommandHandler):
    @register_callback_query_handler(action=SingleRecipeAction)
    async def do_single_recipe_action(self, query: types.CallbackQuery) -> None:
        action = SingleRecipeAction.deserialize(query.data)
        if 'soup' in action.recipe_title.lower():
            do_soup_stuff()  # whatever
        # ...
```
or you can be more precise and limit the binding to specific values
of the action's fields:
```python
    @register_callback_query_handler(
        action=SingleRecipeAction.when(action_type=ActionType.like_recipe),
    )
```


See [boilerplate bot with buttons](boilerplate/button.py)

Set the `TG_BOT_TOKEN` env variable to run it.


### Error handling

Generic error (exception) handling in bots can be implemented via `ErrorHandler`s
at class or method level.

First, define an error handler:

```python
from aiokilogram.errors import DefaultErrorHandler

class MyErrorHandler(DefaultErrorHandler):
    def make_message(self, err: Exception):
        # Any custom logic can go here.
        # This method can return either a `str`, a `MessagePage` or `None`.
        # In case of `None` no message is sent and the exception is re-raised.
        return 'This is my error message'
```

Then add it either to the message handler class:

```python
class MyCommandHandler(CommandHandler):
    error_handler = MyErrorHandler()
```

to handle errors in all methods registered via the
`register_message_handler` and `register_callback_query_handler` decorators.

Or you can do it at method-level:

```python
    @register_message_handler(commands={'my_command'}, error_handler=MyErrorHandler())
    async def my_command_handler(self, event: types.Message) -> None:
        pass  # do whatever you do...
```

See [boilerplate bot with error handling](boilerplate/errors.py)

Set the `TG_BOT_TOKEN` env variable to run it.


## Links

Homepage on GitHub: https://github.com/altvod/aiokilogram

Project's page on PyPi: https://pypi.org/project/aiokilogram/

`aiogram`'s homepage on GitHub: https://github.com/aiogram/aiogram

Telegram Bot API: https://core.telegram.org/bots/api

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/altvod/aiokilogram",
    "name": "aiokilogram",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": "",
    "keywords": "telegram,aiogram",
    "author": "Grigory Statsenko",
    "author_email": "grisha100@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/ee/32/becb3c0d5a6c0039fac376a1f3ca9f28078a717abf62e7276aa0edf8db06/aiokilogram-0.1.3.tar.gz",
    "platform": null,
    "description": "# aiokilogram\n\nConvenience tools and wrappers for `aiogram`,\nthe asynchronous Telegram Bot API framework.\n\n\n## Installation\n\n```bash\npip install aiokilogram\n```\n\n\n## Basic Examples\n\n### Class-Based Command Handlers\n\nThe `aiokilogram` toolkit is centered around the notion of class-based\ncommand handlers. Basically this means that you can group several commands\nas methods in a class and assign them to message and callback patterns\nat class level.\n\nA simplistic bit will look something like this:\n\n```python\nimport asyncio\nimport os\nfrom aiokilogram.bot import KiloBot\nfrom aiokilogram.settings import BaseGlobalSettings\nfrom aiokilogram.handler import CommandHandler\nfrom aiokilogram.registration import register_message_handler\n\nclass TestCommandHandler(CommandHandler):\n    @register_message_handler(commands={'hello'})\n    async def test_handler(self, event) -> None:\n        await self.send_text(user_id=event.from_user.id, text=f'This is a test reply')\n\ndef run_bot():\n    bot = KiloBot(\n        global_settings=BaseGlobalSettings(tg_bot_token=os.environ['TG_BOT_TOKEN']),\n        handler_classes=[TestCommandHandler],\n    )\n    asyncio.run(bot.run())\n\nif __name__ == '__main__':\n    run_bot()\n```\n\nFor more info you can take a look at a [boilerplate bot with buttons](boilerplate/button.py)\nand [simple boilerplate bot](boilerplate/simple.py)\n\nSet the `TG_BOT_TOKEN` env variable to run them.\n\n\n### Action Buttons\n\nThe package also provides a simplified mechanism of using buttons and \nbinding handlers to their callbacks.\nThis is useful when you want your buttons to contain a combination of\nseveral parameters and don't want to implement their serialization,\ndeserialization and callback bindings each time.\n\nThe idea is simple.\n\n1. Define an action (a `CallbackAction` subclass) using a combination of fields:\n```python\nfrom enum import Enum\nfrom aiokilogram.action import CallbackAction, StringActionField, EnumActionField\n\nclass ActionType(Enum):\n    show_recipe = 'show_recipe'\n    like_recipe = 'like_recipe'\n\nclass SingleRecipeAction(CallbackAction):\n    action_type = EnumActionField(enum_cls=ActionType)\n    recipe_title = StringActionField()\n```\n\n2. Create a page containing action buttons:\n```python\nfrom aiokilogram.page import ActionMessageButton, MessagePage, MessageBody, MessageKeyboard\n\npage = MessagePage(\n    body=MessageBody(text='Main Recipe Menu'),\n    keyboard=MessageKeyboard(buttons=[\n        ActionMessageButton(\n            text='Button Text',\n            action=SingleRecipeAction(\n                action_type=ActionType.show_recipe,\n                recipe_title='Fantastic Menemen',\n            ),\n        ),\n        # ...\n    ])\n)\n```\n\n3. Send it as a response to some command in your handler class:\n```python\n    await self.send_message_page(user_id=event.from_user.id, page=page)\n```\n\n4. Define and register a handler method for this action where you deserialize the \n   action parameters and somehow use them in your logic:\n```python\nclass MyHandler(CommandHandler):\n    @register_callback_query_handler(action=SingleRecipeAction)\n    async def do_single_recipe_action(self, query: types.CallbackQuery) -> None:\n        action = SingleRecipeAction.deserialize(query.data)\n        if 'soup' in action.recipe_title.lower():\n            do_soup_stuff()  # whatever\n        # ...\n```\nor you can be more precise and limit the binding to specific values\nof the action's fields:\n```python\n    @register_callback_query_handler(\n        action=SingleRecipeAction.when(action_type=ActionType.like_recipe),\n    )\n```\n\n\nSee [boilerplate bot with buttons](boilerplate/button.py)\n\nSet the `TG_BOT_TOKEN` env variable to run it.\n\n\n### Error handling\n\nGeneric error (exception) handling in bots can be implemented via `ErrorHandler`s\nat class or method level.\n\nFirst, define an error handler:\n\n```python\nfrom aiokilogram.errors import DefaultErrorHandler\n\nclass MyErrorHandler(DefaultErrorHandler):\n    def make_message(self, err: Exception):\n        # Any custom logic can go here.\n        # This method can return either a `str`, a `MessagePage` or `None`.\n        # In case of `None` no message is sent and the exception is re-raised.\n        return 'This is my error message'\n```\n\nThen add it either to the message handler class:\n\n```python\nclass MyCommandHandler(CommandHandler):\n    error_handler = MyErrorHandler()\n```\n\nto handle errors in all methods registered via the\n`register_message_handler` and `register_callback_query_handler` decorators.\n\nOr you can do it at method-level:\n\n```python\n    @register_message_handler(commands={'my_command'}, error_handler=MyErrorHandler())\n    async def my_command_handler(self, event: types.Message) -> None:\n        pass  # do whatever you do...\n```\n\nSee [boilerplate bot with error handling](boilerplate/errors.py)\n\nSet the `TG_BOT_TOKEN` env variable to run it.\n\n\n## Links\n\nHomepage on GitHub: https://github.com/altvod/aiokilogram\n\nProject's page on PyPi: https://pypi.org/project/aiokilogram/\n\n`aiogram`'s homepage on GitHub: https://github.com/aiogram/aiogram\n\nTelegram Bot API: https://core.telegram.org/bots/api\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Convenience tools and wrappers for aiogram",
    "version": "0.1.3",
    "split_keywords": [
        "telegram",
        "aiogram"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f53ec013280c759ed7a3e51e608f14c4674e4ddb4c7e19a584f54c49b32a3c11",
                "md5": "5d04d6095acdafcc4059e3f0585ef1ec",
                "sha256": "e79a1cf0def0e6a972c8a32ce782e3ca6d46744e82fc2ff77ba959d2f3d10da9"
            },
            "downloads": -1,
            "filename": "aiokilogram-0.1.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5d04d6095acdafcc4059e3f0585ef1ec",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 13055,
            "upload_time": "2023-02-01T23:03:45",
            "upload_time_iso_8601": "2023-02-01T23:03:45.411534Z",
            "url": "https://files.pythonhosted.org/packages/f5/3e/c013280c759ed7a3e51e608f14c4674e4ddb4c7e19a584f54c49b32a3c11/aiokilogram-0.1.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ee32becb3c0d5a6c0039fac376a1f3ca9f28078a717abf62e7276aa0edf8db06",
                "md5": "8dc81e44c19be7b0c618f277e7c66fbf",
                "sha256": "333591235bde5c88dad8044862cf8a8aceb8c5702fc1fdfd87bac0da8decf7a7"
            },
            "downloads": -1,
            "filename": "aiokilogram-0.1.3.tar.gz",
            "has_sig": false,
            "md5_digest": "8dc81e44c19be7b0c618f277e7c66fbf",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 11849,
            "upload_time": "2023-02-01T23:03:47",
            "upload_time_iso_8601": "2023-02-01T23:03:47.647600Z",
            "url": "https://files.pythonhosted.org/packages/ee/32/becb3c0d5a6c0039fac376a1f3ca9f28078a717abf62e7276aa0edf8db06/aiokilogram-0.1.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-02-01 23:03:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "altvod",
    "github_project": "aiokilogram",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "aiokilogram"
}
        
Elapsed time: 0.03645s