Base Handler

class bale.handlers.BaseHandler

Bases: object

This object shows a Base Handler. This is a base class for all update handlers. You can create custom handlers by inheriting from it.

Important

Follow the steps below to create a custom handler: 1. Create a subclass of bale.BaseHandler.

from bale.handlers import BaseHandler

class MyHandler(BaseHandler):
    pass

2. Create the method check_new_update() inside the class When processing updates, the check_new_update() method is called. This method must return either None or a tuple.

from bale.handlers import BaseHandler

class MyHandler(BaseHandler):
    def check_new_update(self, update: "Update") -> Optional[Tuple["Message"]]:
        target_message = update.message or update.edited_message
        if target_message:
            return (
                target_message,
            )

        return None
  1. Now, use that customized handler!

    ...
    bot = bale.Bot(token="YOUR_TOKEN_HERE")
    
    @bot.handle(MyHandler())
    async def my_custom_handler(message: Message) -> Message:
        return await message.reply("Hello World!")
    
async check_new_update(update)

This function determines whether the “update” should be covered by the handler or not.

Parameters:

update (bale.Update) – The update to be tested.

Returns:

  • If False or None is returned, the update should not be wrapped by the handler,

  • otherwise the handler is required to wrapp that update.

error(func)

A decorator to set the on_error function for a handler.

from bale import Update, Message
from bale.handlers import MessageHandler

...

@bot.handle(MessageHandler())
async def message_handler(message: Message):
    return await message.reply("Hello World!")

@message_handler.error
async def message_handler_error(update: Update, exc: Exception):
    if update.message:
        return
    return await update.message.reply("The handler encountered an error")
async handle_update(update, *args)

This function works if the handler is required to cover the new Update and calls the callback function.

Parameters:
  • update (bale.Update) – The update to be tested.

  • args – Additional objects, if given to this parameter, will be passed directly to the callback function.

set_callback(callback)

Register new handler callback. It will be called during the new Update process after confirming the check_new_update() function.

Parameters:

callback (Callable[[UT, ...], Coroutine[...]]) – The new callback function.