Package: aiokilogram
aiokilogramConvenience tools and wrappers foraiogram,
the asynchronous Telegram Bot API framework.InstallationpipinstallaiokilogramBasic ExamplesClass-Based Command HandlersTheaiokilogramtoolkit 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:importasyncioimportosfromaiokilogram.botimportKiloBotfromaiokilogram.settingsimportBaseGlobalSettingsfromaiokilogram.handlerimportCommandHandlerfromaiokilogram.registrationimportregister_message_handlerclassTestCommandHandler(CommandHandler):@register_message_handler(commands={'hello'})asyncdeftest_handler(self,event)->None:awaitself.send_text(user_id=event.from_user.id,text=f'This is a test reply')defrun_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 aboilerplate bot with buttonsandsimple boilerplate botSet theTG_BOT_TOKENenv variable to run them.Action ButtonsThe 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.Define an action (aCallbackActionsubclass) using a combination of fields:fromenumimportEnumfromaiokilogram.actionimportCallbackAction,StringActionField,EnumActionFieldclassActionType(Enum):show_recipe='show_recipe'like_recipe='like_recipe'classSingleRecipeAction(CallbackAction):action_type=EnumActionField(enum_cls=ActionType)recipe_title=StringActionField()Create a page containing action buttons:fromaiokilogram.pageimportActionMessageButton,MessagePage,MessageBody,MessageKeyboardpage=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',),),# ...]))Send it as a response to some command in your handler class:awaitself.send_message_page(user_id=event.from_user.id,page=page)Define and register a handler method for this action where you deserialize the
action parameters and somehow use them in your logic:classMyHandler(CommandHandler):@register_callback_query_handler(action=SingleRecipeAction)asyncdefdo_single_recipe_action(self,query:types.CallbackQuery)->None:action=SingleRecipeAction.deserialize(query.data)if'soup'inaction.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:@register_callback_query_handler(action=SingleRecipeAction.when(action_type=ActionType.like_recipe),)Seeboilerplate bot with buttonsSet theTG_BOT_TOKENenv variable to run it.Error handlingGeneric error (exception) handling in bots can be implemented viaErrorHandlers
at class or method level.First, define an error handler:fromaiokilogram.errorsimportDefaultErrorHandlerclassMyErrorHandler(DefaultErrorHandler):defmake_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:classMyCommandHandler(CommandHandler):error_handler=MyErrorHandler()to handle errors in all methods registered via theregister_message_handlerandregister_callback_query_handlerdecorators.Or you can do it at method-level:@register_message_handler(commands={'my_command'},error_handler=MyErrorHandler())asyncdefmy_command_handler(self,event:types.Message)->None:pass# do whatever you do...Seeboilerplate bot with error handlingSet theTG_BOT_TOKENenv variable to run it.LinksHomepage on GitHub:https://github.com/altvod/aiokilogramProject's page on PyPi:https://pypi.org/project/aiokilogram/aiogram's homepage on GitHub:https://github.com/aiogram/aiogramTelegram Bot API:https://core.telegram.org/bots/api