Creating Extensions for SudoBot v9

SudoBot has support for extensions, and it was introduced in version 6.17. Extensions can extend the bot's feature, by adding commands, event listeners, services and a lot more stuff. You can install/uninstall/disable extensions, or create your own to make the bot behave exactly how you want. Extensions can be written using JavaScript and TypeScript.

In this article, you'll learn how SudoBot's extension system works.

The extensions directory

To start using extensions, you need to create a root directory where extensions will be installed. In this guide, we'll name the directory installed_extensions/. To create a directory named installed_extensions/ in the main project root, run the following:

mkdir installed_extensions

Every installed extension goes inside this directory.

Now to tell SudoBot where to look for extensions, add the EXTENSIONS_DIRECTORY environment variable to your .env file:

# Path to the extensions root directory
EXTENSIONS_DIRECTORY=/example/path/to/extensions/directory

Each installed extension has a directory associated with it inside the installed_extensions/ directory. Inside of that inner directory, there is a special file extension.json which contains meta information about the extension, and how to build it.

The extension.json file looks something like this:

{
    id: "org.example.sudobot.extension.hello" /* Extension ID */,
    main: "index.js" /* The entry point file name. */,
    src_main: "index.ts" /* The entry point file name. */,
    commands: "commands" /* Commands directory. The bot will load commands from this directory. */,
    events: "events" /* Event handlers directory. The bot will load event handlers from this directory. */,
    language: "typescript" /* The language being used for this extension. Can be either "javascript" or "typescript". */,
    main_directory: "./build" /* The main directory where the entry point is located. */,
    src_directory: "./src" /* The source directory where the source file of the entry point is located. */,
    build_command: "npm run build" /* Command to build the extension. In this case `npm run build` invokes `tsc`. */,
}

Creating your first SudoBot extension

To get started, first create a directory named installed_extensions inside the project root. In that directory, create another directory for your extension. The name of this directory usually should be your extension's name. In this example, we'll name the extension "hello".

Then inside your extension's directory, create the extension.json file, and the src/ directory. Inside src, create events and commands directories. The final directory tree should look something like this:

+ sudobot/ [project root]
  + installed_extensions/
    + hello/
      + src/
        + commands/
        + events/
      - extension.json

Now add the following to your extension.json file:

{
    id: "org.example.sudobot.extension.hello",
    main: "index.js",
    src_main: "index.ts",
    commands: "commands",
    events: "events",
    language: "typescript",
    main_directory: "./build",
    src_directory: "./src",
    build_command: "npm run build"
}

We'll be using TypeScript to write the extension in this example. If you'd like to use JavaScript instead, you can set language to javascript and you don't need to specify a build command, and your main directory will be the directory where you put your JavaScript files (usually src/). You should also adjust the paths to point to that directory (rather than build/ which is used in this example).

Setting up TypeScript and Dependencies

First, run npm init to initialize your extension project. This will ask you a few questions and create a package.json file. Then run:

npm install --save ../.. # Path to the sudobot project root
Info

Remember this is a really important step to make sure your extension can access SudoBot's core utilities to initialize itself. If you don't link SudoBot with your extension, it will fail to import the necessary files.

Then we can go ahead and install the dependencies and also set up TypeScript.

npm install module-alias
npm install -D typescript @types/node
npx tsc --init

This will add typescript as a dev dependency and also create a tsconfig.node.json file which contains the configuration for the TypeScript compiler.

Now open up tsconfig.node.json file, and add the following (you can tweak these options if you want):

{
    "compilerOptions": {
        "target": "ES2021",
        "module": "commonjs",
        "rootDir": "./src",
        "baseUrl": "./",
        "paths": {
            "@sudobot/*": ["node_modules/sudobot/build/out/main/typescript/*"],
            "@framework/*": [
                "node_modules/sudobot/build/out/framework/typescript/*"
            ]
        },
        "resolveJsonModule": true,
        "outDir": "./build",
        "newLine": "lf",
        "noEmitHelpers": true,
        "noEmitOnError": true,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "skipLibCheck": true
    },
    "exclude": ["./tests", "./build"]
}

This sets up the @sudobot and @framework import aliases for TypeScript, specifies the source root and build directory, and a few other things that are needed. After this, create a symbolic link named tsconfig.json that points to tsconfig.node.json. On windows, just copy the file. The command to create the symbolic link on a Unix/Linux based system would be the following:

ln -s ./tsconfig.node.json ./tsconfig.json
Info

Remember to build the bot beforehand! As you can see, this alias points to the build directory which is created when you build the bot.

Then open up package.json file and add the following inside the root object:

"_moduleAliases": {
    "@framework": "node_modules/sudobot/build/out/framework/typescript",
    "@sudobot": "node_modules/sudobot/build/out/main/typescript"
},
"scripts": {
    "build": "tsc"
}

You might be thinking, why do we need to add the module aliases twice? It's because TypeScript doesn't actually deal with these module aliases, it just checks the types and imports. In runtime, we need another way to resolve these imports. We use module-alias for that.

The entry point

We need to create the entry point now! Make a file src/index.ts and put the following code inside of that file:

import "module-alias/register";
import { Extension } from "@sudobot/core/Extension";
 
class HelloExtension extends Extension {
    // ...
}
 
export default HelloExtension;

That's actually all we need inside this file.

Adding commands to the extension

Alright, let's add a command to the extension! Create a file src/commands/HelloCommand.ts and inside of that file, put the following code:

import { Command, type CommandMessage } from "@framework/commands/Command";
import type Context from "@framework/commands/Context";
 
class HelloCommand extends Command {
    public override readonly name = "hello";
    public override readonly description = "A simple hello-world command.";
 
    public override async execute(context: Context<CommandMessage>) {
        await context.reply("Hello world, from the hello extension!");
    }
}
 
export default HelloCommand;

This command just responds to the user with "Hello world, from the hello extension!".

Adding event listeners to the extension

Now, let's add an event listener to the extension! Create a file src/events/MessageCreateEventListener.ts and inside of that file, put the following code:

import EventListener from "@framework/events/EventListener";
import { Events } from "@framework/types/ClientEvents";
import type { Message } from "discord.js";
 
class MessageCreateEventListener extends EventListener<Events.MessageCreate> {
    public override readonly name = Events.MessageCreate;
 
    public override async execute(message: Message<boolean>): Promise<void> {
        if (message.author.bot) {
            return;
        }
 
        if (message.content === "ping") {
            await message.reply("Pong, from the hello extension!");
        }
    }
}
 
export default MessageCreateEventListener;

This event listener listens to MessageCreate event, and whenever someone sends a message with content "ping", it will reply to them.

Building the extension

Building your newly created extension involves the same procedures as any other TypeScript project. Install the dependencies and run the TypeScript compiler from the extension's directory (installed_extensions/hello):

npm install -D
npm run build

If using Bun:

bun install -D
bun run build

This will take a little bit time. After that, you're ready to go. You can now start the bot from the main project root (assuming you've built it already):

npm start

Please note that if you're using Bun to run the bot, the extensions will need to be configured differently. We'll include the instructions on how to do it manually and also how you can automate it, very soon.

And then if everything was configured correctly, the hello command will be loaded and can be executed on any server.

Congratulations, you've just built an extension for SudoBot!

Help and Support

If you need help with anything, feel free to create a discussion topic at the GitHub repo. You can also contact via email at [email protected], or join our Discord Server.