The SDK provides a flexible command parsing and dispatch system.
Parses commands from messages by prefix or @-mention.
from bot_sdk import CommandParser
parser = CommandParser(
prefixes=("/", "!"),
*,
enable_mentions: bool = True,
mention_aliases: Iterable[str] | None = None,
specs: Iterable[CommandSpec] | None = None,
auto_help: bool = True,
translator: Callable[[str], str] | None = None,
)
Parameters
help command.lambda s: bot.tr(s)). Used to localize command descriptions, help text labels, and error messages.Example
parser = CommandParser(prefixes=("/", "!", "#"), enable_mentions=True)
CommandSpec.CommandInvocation | None.CommandInvocation (raises on errors; usage and error messages are localized if a translator is provided).CommandSpec | None: Lightweight lookup of which command would be invoked by raw text, without parsing arguments or raising errors. Used for early permission checks.user_level is provided, commands with min_level > user_level are hidden from the output.!help — list all commands (filtered by caller’s permission level)!help <command> — show detailed usage, argument descriptions, aliases, min_level (if set)Defines a command.
from bot_sdk import CommandSpec
CommandSpec(
name: str,
description: str = "",
args: list[CommandArgument] = [],
aliases: list[str] = [],
allow_extra: bool = False,
handler: Callable | None = None,
show_in_help: bool = True,
min_level: int | None = None,
)
CommandArgument.(invocation, message, bot).BaseBot before dispatch.ping → Pong!calculate a bstatus aliased to s, info, statecho words... with multiple=Truegreet [name]Defines an argument.
CommandArgument(
name: str,
type: type = str,
required: bool = True,
description: str = "",
multiple: bool = False,
)
str | int | float | bool.Argument description is surfaced in !help <command> detailed output.
Boolean parsing accepts: true/1/yes/y/on and false/0/no/n/off.
Result of parsing.
@dataclass
class CommandInvocation:
name: str
args: dict[str, Any]
tokens: list[str]
spec: CommandSpec
CommandErrorUnknownCommandErrorInvalidArgumentsError (message includes Usage and error text for quick fixes; both are localized if a translator was provided)When a translator function is provided to CommandParser.__init__, the following strings are localized:
This allows the entire command system to respond in the user’s language.
from bot_sdk import BaseBot, Message, CommandSpec, CommandArgument, CommandInvocation, run_bot
class CalculatorBot(BaseBot):
def __init__(self, client):
super().__init__(client)
self.command_parser.register_spec(
CommandSpec(
name="add",
description="Add two numbers",
aliases=["plus", "+"],
args=[
CommandArgument(name="a", type=float, required=True),
CommandArgument(name="b", type=float, required=True),
],
handler=self.handle_add,
)
)
self.command_parser.register_spec(
CommandSpec(
name="multiply",
description="Multiply two numbers",
aliases=["mul", "*"],
args=[
CommandArgument(name="a", type=float, required=True),
CommandArgument(name="b", type=float, required=True),
],
handler=self.handle_multiply,
)
)
self.command_parser.register_spec(
CommandSpec(
name="power",
description="a^b",
aliases=["pow", "**"],
args=[
CommandArgument(name="base", type=float, required=True),
CommandArgument(name="exponent", type=float, required=True),
],
handler=self.handle_power,
)
)
async def handle_add(self, inv: CommandInvocation, message, bot):
await self.send_reply(message, f"{inv.args['a']} + {inv.args['b']} = {inv.args['a'] + inv.args['b']}")
async def handle_multiply(self, inv: CommandInvocation, message, bot):
await self.send_reply(message, f"{inv.args['a']} × {inv.args['b']} = {inv.args['a'] * inv.args['b']}")
async def handle_power(self, inv: CommandInvocation, message, bot):
await self.send_reply(message, f"{inv.args['base']} ^ {inv.args['exponent']} = {inv.args['base'] ** inv.args['exponent']}")
async def on_message(self, message: Message) -> None:
await self.send_reply(message, "I am a calculator bot. Use /help.")
if __name__ == "__main__":
run_bot(CalculatorBot)
multiple=True) for free-form text.generate_help() to show available commands.