Skip to content

kamihi.bot ⚓︎

Bot module for Kamihi.

This module provides the primary interface for the Kamihi framework, allowing for the creation and management of Telegram bots.

License

MIT

Modules:

Name Description
action

Action helper class.

bot

Bot module for Kamihi.

models

Database models for the bot module.

utils

Utilities and constants for the bot module.

Classes:

Name Description
Action

Action class for Kamihi bot.

Bot

Bot class for Kamihi.

Action ⚓︎

Action(
    name: str,
    commands: list[str],
    description: str,
    func: Callable,
)

Action class for Kamihi bot.

This class provides helpers for defining actions, their commands and their handlers.

Attributes:

Name Type Description
name str

The name of the action.

commands list[str]

List of commands associated.

description str

Description of the action.

Initialize the Action class.

Parameters:

Name Type Description Default

name ⚓︎

str

The name of the action.

required

commands ⚓︎

list[str]

List of commands associated.

required

description ⚓︎

str

Description of the action.

required

func ⚓︎

Callable

The function to be executed when the action is called.

required

Methods:

Name Description
clean_up

Clean up the action from the database.

is_valid

Check if the action is valid.

save_to_db

Save the action to the database.

Source code in src/kamihi/bot/action.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def __init__(self, name: str, commands: list[str], description: str, func: Callable) -> None:
    """
    Initialize the Action class.

    Args:
        name (str): The name of the action.
        commands (list[str]): List of commands associated.
        description (str): Description of the action.
        func (Callable): The function to be executed when the action is called.

    """
    self.name = name
    self.commands = commands
    self.description = description

    self._func = func
    self._logger = logger.bind(action=self.name)

    self._validate_commands()
    self._validate_function()

    if self.is_valid():
        self._db_object = self.save_to_db()
        self._logger.debug("Successfully registered")
    else:
        self._db_object = None
        self._logger.warning("Failed to register")

handler property ⚓︎

handler: AuthHandler

Construct a CommandHandler for the action.

clean_up classmethod ⚓︎

clean_up(keep: list[str]) -> None

Clean up the action from the database.

Source code in src/kamihi/bot/action.py
145
146
147
148
@classmethod
def clean_up(cls, keep: list[str]) -> None:
    """Clean up the action from the database."""
    RegisteredAction.objects(name__nin=keep).delete()

is_valid ⚓︎

is_valid() -> bool

Check if the action is valid.

Source code in src/kamihi/bot/action.py
134
135
136
def is_valid(self) -> bool:
    """Check if the action is valid."""
    return self._valid

save_to_db ⚓︎

save_to_db() -> RegisteredAction

Save the action to the database.

Source code in src/kamihi/bot/action.py
138
139
140
141
142
143
def save_to_db(self) -> RegisteredAction:
    """Save the action to the database."""
    return RegisteredAction.objects(name=self.name).upsert_one(
        name=self.name,
        description=self.description,
    )

Bot ⚓︎

Bot(settings: KamihiSettings)

Bot class for Kamihi.

The framework already provides a bot instance, which can be accessed using the bot variable. This instance is already configured with default settings and can be used to start the bot. The managed instance is preferable to using the Bot class directly, as it ensures that the bot is properly configured and managed by the framework.

Attributes:

Name Type Description
settings KamihiSettings

The settings for the bot.

templates Templates

The templates loaded by the bot.

Initialize the Bot class.

Parameters:

Name Type Description Default

settings ⚓︎

KamihiSettings

The settings for the bot.

required

Methods:

Name Description
action

Register an action with the bot.

start

Start the bot.

user_class

Set the user model for the bot.

Source code in src/kamihi/bot/bot.py
65
66
67
68
69
70
71
72
73
74
75
76
def __init__(self, settings: KamihiSettings) -> None:
    """
    Initialize the Bot class.

    Args:
        settings: The settings for the bot.

    """
    self.settings = settings

    # Connects to the database
    connect(self.settings.db)

action ⚓︎

action(
    *commands: str, description: str = None
) -> partial[Action]

Register an action with the bot.

This method overloads the bot.action method so the decorator can be used with or without parentheses.

Parameters:

Name Type Description Default

*commands ⚓︎

str

A list of command names. If not provided, the function name will be used.

()

description ⚓︎

str

A description of the action. This will be used in the help message.

None

Returns:

Name Type Description
Callable partial[Action]

The wrapped function.

Source code in src/kamihi/bot/bot.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
@dispatch([str])
def action(self, *commands: str, description: str = None) -> partial[Action]:
    """
    Register an action with the bot.

    This method overloads the `bot.action` method so the decorator can be used
    with or without parentheses.

    Args:
        *commands: A list of command names. If not provided, the function name will be used.
        description: A description of the action. This will be used in the help message.

    Returns:
        Callable: The wrapped function.

    """
    return functools.partial(self.action, *commands, description=description)

start ⚓︎

start() -> None

Start the bot.

Source code in src/kamihi/bot/bot.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def start(self) -> None:
    """Start the bot."""
    # Cleans up the database of actions that are not present in code
    Action.clean_up([action.name for action in self._actions])
    logger.debug("Removed actions not present in code from database")

    # Warns the user if there are no valid actions registered
    if not self._valid_actions:
        logger.warning("No valid actions were registered. The bot will not respond to any commands.")

    # Loads the Telegram client
    self._client = TelegramClient(self.settings, self._handlers)
    logger.trace("Initialized Telegram client")

    # Sets the command scopes for the bot
    self._client.register_run_once_job(self._reset_scopes, 1)
    self._client.register_run_once_job(self._set_scopes, 2)
    logger.trace("Initialized command scopes jobs")

    # Loads the web server
    self._web = KamihiWeb(
        self.settings.web,
        self.settings.db,
        {
            "after_create": [self._set_scopes],
            "after_edit": [self._set_scopes],
            "after_delete": [self._set_scopes],
        },
    )
    logger.trace("Initialized web server")
    self._web.start()

    # Loads the template engine
    self.templates = Templates(self.settings.autoreload_templates)
    logger.trace("Initialized templating engine")

    # Runs the client
    self._client.run()

    # When the client is stopped, stop the database connection
    disconnect()

user_class ⚓︎

user_class(cls: type[User]) -> None

Set the user model for the bot.

This method is used as a decorator to set the user model for the bot.

Parameters:

Name Type Description Default

cls ⚓︎

type[User]

The user class to set.

required
Source code in src/kamihi/bot/bot.py
125
126
127
128
129
130
131
132
133
134
135
def user_class(self, cls: type[User]) -> None:  # skipcq: PYL-R0201
    """
    Set the user model for the bot.

    This method is used as a decorator to set the user model for the bot.

    Args:
        cls: The user class to set.

    """
    User.set_model(cls)