Skip to content

Your first plugin

A teabot plugin is a small Python package: functions that become slash commands and AI assistant tools, a database table or two of its own, and tests. At the end of this page, you have made one, tested it, and run it in Discord. It takes about ten minutes.

Before you start

You need:

  • A teabot instance from the quick start, with its folder open in a terminal.
  • uv on your machine, so your editor and the tests can use the plugin's code:

    curl -LsSf https://astral.sh/uv/install.sh | sh
    
  • Python you can read. A little SQL helps.

1. Make the plugin

In your instance's folder:

uv run teabot new-plugin polls
created plugins/polls
next: uv run --package teabot-polls pytest plugins/polls
then try it in Discord: docker compose stop bot, then uv run teabot dev
and in your server, /plugins enable plugin:polls

It writes one package, with an example action called hello:

plugins/polls/
    pyproject.toml                      the package, and how teabot finds it
    README.md                           what it does, and every server it contacts
    src/teabot_polls/
        __init__.py                     the plugin
        migrations/0001_greetings.sql   its table
        py.typed                        tells type checkers the package has types
    tests/
        test_polls.py                   its tests
        test_polls_snapshot.py          a record of its commands, kept in snapshot.json

2. Run its tests

uv run --package teabot-polls pytest plugins/polls
3 passed in 1.02s

The tests run against your instance's Postgres, which setup.sh started. Each test gets a database of its own, and drops it afterwards. The first run also writes tests/snapshot.json.

3. Read the plugin

This is all of src/teabot_polls/__init__.py:

plugins/polls/src/teabot_polls/__init__.py
"""teabot-polls. Imports only `teabot.sdk`.

- `polls.hello` records a member's greeting in the plugin's own table and says how many they have made.
"""

from typing import Annotated

from pydantic import BaseModel, Field
from teabot.sdk import Context, EmptyConfig, Plugin

plugin = Plugin("polls")
type Ctx = Context[EmptyConfig]


class Greeted(BaseModel):
    times: int

    def render(self) -> str:
        return f"Hello! That is hello number {self.times}."


@plugin.action()
async def hello(ctx: Ctx, greeting: Annotated[str, Field(max_length=100)] = "hello") -> Greeted:
    """Say hello.

    Args:
        greeting: What to say
    """
    async with ctx.db.transaction() as tx:
        await tx.execute(
            "INSERT INTO greetings (guild_id, member_id, greeting) VALUES ($1, $2, $3)",
            ctx.guild.id,
            ctx.actor.user_id,
            greeting,
        )
        times = await tx.fetchval(
            int,
            "SELECT count(*) FROM greetings WHERE guild_id = $1 AND member_id = $2",
            ctx.guild.id,
            ctx.actor.user_id,
        )
    return Greeted(times=times)
  • plugin = Plugin("polls") is the plugin. Its id, polls, is the command's name: /polls.
  • @plugin.action() makes hello an action: the slash command /polls hello, and the AI assistant tool polls_hello.
  • Its parameters after ctx are the command's options. The docstring's first line describes the command, and its Args: section describes each option.
  • ctx is the call: which server (ctx.guild), who asked (ctx.actor), and the plugin's database (ctx.db).
  • It returns a Greeted, and render is the reply the member sees.

The tests call the action the way Discord would, permissions and all:

plugins/polls/tests/test_polls.py
"""teabot-polls, through the real loader, migrations and call path (`teabot.testing`)."""

import discord
from teabot.testing import HarnessFactory

from teabot_polls import Greeted, hello, plugin


async def test_hello_counts_a_members_greetings(teabot_harness: HarnessFactory) -> None:
    harness = await teabot_harness(plugin)
    assert await harness.call(hello) == Greeted(times=1)
    assert await harness.call(hello, greeting="hi") == Greeted(times=2)


async def test_each_member_has_their_own_count(teabot_harness: HarnessFactory) -> None:
    harness = await teabot_harness(plugin)
    await harness.call(hello)
    other = harness.guild.add_member(discord.Permissions.none())
    assert await harness.as_member(other).call(hello) == Greeted(times=1)

4. Change it

Make the reply your own. In __init__.py, change render:

    def render(self) -> str:
        return f"Hi there! That is hello number {self.times}."

Run the tests again. They still pass, since they check what the action returns, not how it is shown.

5. See it in Discord

Run the bot from your plugin's code, so each save restarts it with your changes. Stop the Compose bot first, since only one process can run the bot:

docker compose stop bot
uv run teabot dev

teabot dev watches plugins/ and teabot.env, and restarts the bot when a file changes. Each restart migrates the plugin and sends its commands to the servers where it is on. Stop it with Ctrl+C. Then turn the plugin on in your server:

/plugins enable plugin:polls
/polls hello

teabot replies Hi there! That is hello number 1.

Next

  • The tutorial grows polls into a real plugin: options, votes, a job that posts the results, and a confirmed delete.
  • The reference has every part of a plugin in one page.