Your first plugin
Start from Hello World and write your first ShiritaiBot plugin.
Plugins can add commands to ShiritaiBot, give the model new tools, feed outside events such as email and notifications into the proactive engine, and step in at each stage of model requests and message sending.
This chapter shows you how to write a plugin from scratch. Before you start, you need:
- To know Python, including the basics of
async/await - ShiritaiBot running as described in the quick start, with at least one model set up
ShiritaiBot's plugin API is modeled on AstrBot's, so the basic structure is the same. If you've written AstrBot plugins before, moving to ShiritaiBot is easy.
Where plugins live
When ShiritaiBot starts, it scans every subfolder of <data folder>/plugins/; each subfolder is a plugin. The data folder is data in the folder you start ShiritaiBot from, unless you set another one with --home.
The folder name is the plugin ID. It may only contain lowercase letters, digits and underscores, such as hello_world or weather_uk. The plugin ID appears in config files, logs and data folders, so avoid changing it once it's set.
We recommend naming plugins srtb_plugin_<name>, such as srtb_plugin_wechat.
A plugin needs at least two files:
data/plugins/hello_world/
├── metadata.yaml # plugin information (required)
├── main.py # plugin entry point (required)
└── _conf_schema.json # settings definition (optional)Write metadata.yaml
metadata.yaml tells ShiritaiBot about the plugin: its author, name and so on.
name: hello_world
display_name: Hello World
desc: My first ShiritaiBot plugin
short_desc: Says hello
version: 1.0.0
author: your-name
repo: https://github.com/your-name/hello_world| Field | Description |
|---|---|
name | The plugin name. The plugin ID is always the folder name; this field is only shown when there's no display_name |
display_name | The name shown in the plugin list |
desc | The plugin description |
short_desc | A one-sentence summary |
version / author / repo | Version, author and repository URL, shown in the plugin's details |
support_platforms | Optional. Supported platforms, only qq and web; for display only |
shiritaibot_version | Optional. The ShiritaiBot versions required, such as ">=0.2,<1". When the version doesn't match, the plugin shows as failed to load |
Write main.py
In main.py, define a class that inherits from Plugin. Name it as you like, but a main.py may contain only one plugin class:
from shiritaibot.api import MessageEvent, Plugin, hook
class HelloWorld(Plugin):
async def initialize(self):
self.logger.log("Hello World plugin started")
@hook.command("hello")
async def hello(self, event: MessageEvent, name: str = ""):
"""Say hello"""
yield event.plain_result(f"Hello, {name or event.get_sender_name()}!")This code does two things:
initialize()runs when the plugin loads; here it just logs a line.@hook.command("hello")registers a/hellocommand. When a user sends/helloor/hello Alex, ShiritaiBot callshello()and takes thenameargument from the message. The function's docstring is shown in/help.
Import everything a plugin needs from shiritaibot.api. ShiritaiBot's other modules are internal and may change at any time, so don't import them directly.
Load and debug
- Put the plugin folder in
data/plugins/. - Open the Plugins page in the WebUI and click Reload plugins. ShiritaiBot scans the plugin folder again, and your plugin should appear in the list.
- New plugins are disabled by default. Open the plugin, check Enable plugin and save.
- Send
/helloin the chat page or on QQ and see whether the bot replies.
You don't need to restart ShiritaiBot after changing the code: click Reload this plugin in the plugin's settings to use the new code. If the new code has an error, the old version keeps running, the error shows in the plugin list, and you can reload again once it's fixed.
The plugin's logs (self.logger) appear in the terminal and in Activity Log → Runtime logs in the WebUI. Look there first when something goes wrong.
Other .py files in the plugin folder can be imported relatively, such as from .utils import parse_city, and they're reloaded along with the plugin.
Lifecycle
A plugin class has two lifecycle methods you can override:
import asyncio
from shiritaibot.api import Context, Plugin, PluginSettings
class MyPlugin(Plugin):
def __init__(self, context: Context, config: PluginSettings):
super().__init__(context, config)
self.task = None
async def initialize(self):
# Called when the plugin loads; a good place to open connections and start background tasks
self.task = asyncio.create_task(self.poll())
async def terminate(self):
# Called when the plugin is disabled, reloaded or removed, or when ShiritaiBot exits
if self.task:
self.task.cancel()
async def poll(self):
...Saving settings and clicking reload both reload the plugin: the old instance's terminate() runs first, then a new instance is created. So any background task or connection you start in initialize() must be closed in terminate(), or each reload leaves another copy running.
You don't have to write __init__. If you do, remember to call super().__init__(). A plugin without settings can also have an __init__ that takes only context.
Useful attributes of a plugin instance:
| Attribute | Description |
|---|---|
self.config | The plugin's settings; see Plugin settings |
self.context | Services the host provides; see Host services |
self.logger | The logger |
self.data_dir | The plugin's own data folder, data/plugin_data/<plugin ID>/, kept when the plugin is removed |
self.name | The plugin ID |
self.t() | Text in the chat's language; see Languages below |
Languages
A plugin's replies follow the chat's language (set with /lang or the global bot language; see Languages). Plugins can provide their own text in several languages too:
- Put
locales/zh-CN.jsonandlocales/en.jsonin the plugin folder, and read them in code withself.t("key", param=value).{param}in the text is replaced; write literal braces as{{ }}. When the current language is missing a key, the Chinese text is used, and when that's missing too, the key itself is returned. display_name,descandshort_descinmetadata.yaml, anddescription,hintandlabelsin_conf_schema.json, can be objects with one entry per language, such as{"zh-CN": "默认城市", "en": "Default city"}. The WebUI shows them in the viewer's interface language.- Logs (
self.logger) always use the global bot language. Command descriptions in/helpcome from docstrings, so for now they're in one language.
data/plugins/hello_world/
├── locales/
│ ├── zh-CN.json # {"greeting": "你好,{name}!"}
│ └── en.json # {"greeting": "Hello, {name}!"}
├── metadata.yaml
└── main.py@hook.command("hello")
async def hello(self, event: MessageEvent, name: str = ""):
"""Say hello"""
yield event.plain_result(self.t("greeting", name=name or event.get_sender_name()))Skills work the same way: put an English SKILL.en.md next to SKILL.md (and references/x.en.md next to references/x.md). When the chat is in English, ShiritaiBot reads the English file if there is one, and the original otherwise.
Third-party dependencies
ShiritaiBot doesn't install plugin dependencies automatically. If your plugin uses third-party libraries, put a requirements.txt in the plugin folder and explain how to install them in your README, for example by running this in the ShiritaiBot folder:
uv pip install -r data/plugins/hello_world/requirements.txtDependencies installed this way survive updates made from the WebUI. But if you run uv sync by hand, they're removed unless you add --inexact.
ShiritaiBot already includes common libraries such as httpx, pydantic and pyyaml. Use those where you can instead of adding new dependencies. ShiritaiBot may check plugin dependencies automatically in the future, but for now, please do it this way.
Share your plugin
Others can install your plugin in their ShiritaiBot in a few ways:
- Submit it to the plugin store. Publish a GitHub release, sign in to the store with GitHub and submit the repository; once an AI has reviewed the code and a maintainer has approved it, users can find it under Plugins → Market and install it.
- Upload it to a public GitHub repository. Users enter the repository URL in Plugins → Install plugin, and ShiritaiBot downloads the default branch.
- Package it as a ZIP, which users upload in the same place. The ZIP can contain the plugin files directly or inside one extra folder.
- Copy the folder into
data/plugins/by hand, then click Reload plugins.
When installing, users enter a plugin ID, which becomes the folder name. Installed plugins are disabled by default too; users fill in the settings and enable them.
Ground rules
Plugins run in the same process as ShiritaiBot, with the same system permissions and no sandbox. When you write a plugin:
- Don't block the event loop. Use async libraries such as
httpx.AsyncClientfor network requests, and move unavoidable blocking calls intoasyncio.to_thread(). Never use blocking calls such astime.sleep(): yourtime.sleep()freezes the whole bot, not just your plugin. - Clean up after yourself. Close the tasks and connections you started in
initialize()interminate(). - Protect users' credentials. Store passwords and tokens in settings fields with
secret; don't log them or return them to the model as they are. - Declare tool risk levels honestly. Don't mark tools that write data or affect the outside world as
safe; see LLM tools. - Treat outside content as untrusted. Text in email, web pages and issues may contain instructions aimed at the model, so think before handing it over.
Likewise, ShiritaiBot Devs can't vouch for the safety of plugins installed from the internet.
Next steps
- Commands and messages: register commands and listen to group messages
- LLM tools: give the model a new tool
- Plugin settings: let users configure your plugin in the WebUI
- Agent and send hooks: change model requests and outgoing messages
- Proactive events: feed outside changes into the proactive engine
- Host services: send messages, call models and store data
The full example plugin, examples/plugins/hello_world, uses most of the features in this chapter. Copy it as a starting point.