Skip to content

How to make a plugin.

Ccode-lang edited this page Sep 29, 2023 · 10 revisions

Introduction

When you run a Xander instance you may notice this line in your log:

[14/04/2023 11:47:35] Loading plugins

This is one of the most useful features of Xander at work. You can load Python scripts with a certain format as plugins to add extra commands (and features) to the bot without modifying the bot.py file directly.

Making your first plugin

A basic plugin looks like the below:

# You can import extra modules here if you need to

# A variable that is initialized by onload(). It stores a dictionary of references so that you can print to the terminal in a stylized way and call discord functions without reimporting them.
obj = None


# Called when the plugin is loaded. It receives a variable input of a dictionary of references. (More info next to obj variable)
def onload(objin):
    # Make sure we are using the global obj variable
    global obj
    
    # Set obj to the dictionary given to onload()
    obj = objin
    
    # A simple call to the log() function from bot.py which prints to the log.
    obj["log"]("Example plugin loaded!")

# Called when a message is received. It must be async and has an input of a discord message object. (More information in discord.py docs)
async def onmessage(message):
    # An example of what we can do with a message object.
    obj["log"](f"The message \"{message.content}\" was sent by {message.author.name}")

# A function called when the bot program exits.
def onexit():
    obj["log"]("Example plugin exit run.")

What is contained in the obj dictionary?

Here is a pseudocode definition below:

access = {
    "discord": A reference to the discord module, basically what is returned by the statement "import discord",
    "log": The log() function which logs output,
    "modlog": The modlog() function which writes messages to the modlog,
    "config": A reference to the config.py module, useful if you want to add your own config for the plugin,
    "client": The client object of the bot.  More info is on the discord.py docs.
}
Clone this wiki locally