Command API

This page assumes you’ve completed Creating a Simple Hello World Module. If not, check the previous pages.

Now for a more realistic module, creating a hello world command.

The Command Class

Each command in Monium has their own class based on Command. And you need to set 2 attributes when creating it, name and args, like so:

from monium.ext.command import Command

class HelloWorldCommand(Command):
    name = "hello"
    args = []

Making It Do Something

Now, this command needs to do something, and we’re going to do it by implementing run, like so:

import discord

from monium.ext.command import Command

class HelloWorldCommand(Command):
    name = "hello"
    args = []

    async def run(message: discord.Message, **kwargs):
        # self.client is a shortcut to self.module.client which is a instance of
        # MoniumClient (discord.Client subclass)
        await self.client.send_message(message.channel, "Hello, world!")

Now, the command is done, but if you run this bot now, nothing will happen. Commands aren’t automatically activated like modules. Instead, you’ll have to register them

Registering It

On your module classes on_ready function, add the following line:

self.client.cmd.register_command(HelloWorldCommand(self))

This will register your command using the CommandParser instance of the bot. Please note that all commands have self (Module class instance) as an argument.

Command Arguments

If you want to add arguments to your command, it’s really easy. Just add a string to the command’s class’ args like so:

args = ["name"]

Now, in your command function, you can access that by kwargs.get("name") like so:

async def run(self, message: discord.Message, **kwargs):
    name = kwargs.get("name")
    if not name:
        # You could just use the "default" argument in dict.get, but
        # I'm doing it like this in this example to show a way if you want
        # to do something more than just have a default argument
        name = "World"  # or maybe send an error. Up to you

    # The f"Hello, {name}" part is the new string formatting method in
    # Python 3.6 and above that automatically fills in the variables by
    # their names. Nothing special going on here.
    await self.client.send_message(message.channel, f"Hello, {name}!")

And that’s about it for commands. The same module (with some comments) can be found on our examples repository with args without args.