Tutorial: a polls plugin¶
This grows the polls plugin from Your first plugin into a real one. At the end, members can start polls, vote and change their votes, a job posts the results when time is up, and moderators can delete a poll after confirming a plan. Every piece is tested.
The finished plugin is examples/polls in teabot's repository. Its tests run with teabot's own, so the code on this page works as shown.
1. The plugin and its settings¶
Start src/teabot_polls/__init__.py afresh. Its imports, for the whole tutorial, are:
from datetime import datetime, timedelta
from typing import Annotated
from pydantic import BaseModel, Field
from teabot.sdk import (
DESTRUCTIVE,
READ,
ActionError,
Context,
Diff,
DiffEntry,
Plugin,
RoleRef,
TextChannel,
UntrustedText,
)
Below them, the plugin and its settings:
class Cfg(BaseModel):
default_minutes: int = Field(default=60, ge=1, le=10080)
voter_role: RoleRef | None = None
plugin = Plugin("polls", config=Cfg, description="Polls that members vote in with buttons.")
type Ctx = Context[Cfg]
Cfgis the plugin's settings. Server admins change them with/plugins config plugin:polls setting:default_minutes value:90. Give every setting a default, so a server that has set nothing still works.RoleRefholds a role's ID.type Ctx = Context[Cfg]names the settings' type once. Thenctx.configis aCfgin every action, and pyright checks it.
Delete tests/test_polls.py, which tests the old hello. Step 8 writes the new tests, so add each step's code to the file as you go, and run the tests at step 8.
2. The tables¶
Delete src/teabot_polls/migrations/0001_greetings.sql, and write src/teabot_polls/migrations/0001_polls.sql:
CREATE TABLE polls (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
guild_id bigint NOT NULL,
channel_id bigint NOT NULL,
question text NOT NULL,
options text[] NOT NULL,
ends_at timestamptz NOT NULL,
state text NOT NULL DEFAULT 'running' CHECK (state IN ('running', 'closed')),
UNIQUE (guild_id, id)
);
CREATE TABLE votes (
guild_id bigint NOT NULL,
poll_id bigint NOT NULL,
member_id teabot.member_id NOT NULL,
choice int NOT NULL,
PRIMARY KEY (guild_id, poll_id, member_id),
FOREIGN KEY (guild_id, poll_id) REFERENCES polls (guild_id, id) ON DELETE CASCADE
);
- Every table has a
guild_id, the server's ID. teabot shows plugin code only the current server's rows, which keeps each server's polls apart. The queries filter byguild_idtoo, which keeps them clear and lets Postgres use the index. - A foreign key includes
guild_idtoo, so a vote can never point at another server's poll. - teabot checks these rules when it loads the plugin, and stops with the fix if a table breaks one.
- Migrations only go forward. Once a plugin is released, add a
0002_...sqlfor a change instead of editing this file.
The queries this tutorial uses sit together near the top of the file:
START = """
INSERT INTO polls (guild_id, channel_id, question, options, ends_at) VALUES ($1, $2, $3, $4, $5) RETURNING id
"""
VOTE = """
INSERT INTO votes (guild_id, poll_id, member_id, choice)
SELECT guild_id, id, $3, $4 FROM polls
WHERE guild_id = $1 AND id = $2 AND state = 'running' AND ends_at > now() AND $4 <= cardinality(options)
ON CONFLICT (guild_id, poll_id, member_id) DO UPDATE SET choice = EXCLUDED.choice
"""
RUNNING = """
SELECT p.id, p.question, p.ends_at, count(v.member_id) AS voters
FROM polls p LEFT JOIN votes v ON v.guild_id = p.guild_id AND v.poll_id = p.id
WHERE p.guild_id = $1 AND p.state = 'running'
GROUP BY p.id ORDER BY p.ends_at
"""
LOCK_RUNNING = """
SELECT channel_id, question, options FROM polls WHERE guild_id = $1 AND id = $2 AND state = 'running' FOR UPDATE
"""
COUNTS = "SELECT choice, count(*) AS votes FROM votes WHERE guild_id = $1 AND poll_id = $2 GROUP BY choice"
CLOSE = "UPDATE polls SET state = 'closed' WHERE guild_id = $1 AND id = $2"
ONE = "SELECT id, question FROM polls WHERE guild_id = $1 AND id = $2"
DELETE = "DELETE FROM polls WHERE guild_id = $1 AND id = $2"
3. Starting a poll¶
class Started(BaseModel):
poll: int
ends_at: datetime
def render(self) -> str:
return f"Poll {self.poll} started; it closes <t:{int(self.ends_at.timestamp())}:R>."
type Choice = Annotated[str, Field(min_length=1, max_length=100)]
@plugin.action(needs="manage_messages")
async def start(
ctx: Ctx,
channel: TextChannel,
question: Annotated[str, Field(max_length=200)],
option_1: Choice,
option_2: Choice,
option_3: Choice | None = None,
option_4: Choice | None = None,
minutes: Annotated[int, Field(ge=1, le=10080)] | None = None,
) -> Started:
"""Start a poll.
Args:
channel: Where to post the poll.
question: What the poll asks.
option_1: The first option.
option_2: The second option.
option_3: A third option.
option_4: A fourth option.
minutes: How long it runs; the server's default if left out.
"""
options = [o for o in (option_1, option_2, option_3, option_4) if o]
ends_at = ctx.now + timedelta(minutes=minutes or ctx.config.default_minutes)
async with ctx.db.transaction() as tx:
poll = await tx.fetchval(int, START, ctx.guild.id, channel.id, question, options, ends_at)
await tx.schedule(close.bind(poll=poll), at=ends_at)
numbered = "\n".join(f"{n}. {option}" for n, option in enumerate(options, start=1))
await channel.send(f"**Poll {poll}: {question}**\n{numbered}\nVote with `/polls vote poll:{poll}`.")
return Started(poll=poll, ends_at=ends_at)
channel: TextChannelgives the member a channel picker, and the function the channel itself.Annotated[int, Field(ge=1, le=10080)]sets limits that Discord enforces before the member sends.option_3: Choice | None = Noneis an option the member may leave out.needs="manage_messages"is the Discord permission the action needs. teabot checks it every time.ctx.nowis the time. Read the clock only through it, since tests move it.- The closing job is scheduled in the same transaction as the poll, so neither exists without the other. The post is sent after the transaction, since nothing that waits on Discord belongs inside one.
4. Voting¶
@plugin.action()
async def vote(ctx: Ctx, poll: int, option: Annotated[int, Field(ge=1, le=4)]) -> str:
"""Vote in a running poll, or change your vote.
Args:
poll: The poll's number, from /polls list.
option: The number of the option you choose.
"""
role = ctx.config.voter_role
if role is not None:
member = await ctx.guild.get_member(ctx.actor.user_id)
if member is None or role not in member.role_ids:
raise ActionError("You need the voter role to vote here.")
done = await ctx.db.execute(VOTE, ctx.guild.id, poll, ctx.actor.user_id, option)
if done == "INSERT 0 0":
raise ActionError("That poll is not running, or has no option with that number.")
return f"Your vote is option {option}."
- A plain string is a reply.
ActionErrortells the member what went wrong, in your words. teabot records it in the audit log.ctx.actor.user_idis who asked.ctx.guild.get_member(...)finds them, with their roles.- The vote query does the checks in one statement: the poll is running, the option exists, and a second vote replaces the first. When nothing fits, Postgres reports
INSERT 0 0.
5. Listing the polls¶
class Running(BaseModel):
id: int
question: UntrustedText
ends_at: datetime
voters: int
@plugin.action(risk=READ, reply="public")
async def list_(ctx: Ctx) -> list[Running]:
"""The running polls."""
return await ctx.db.fetch(Running, RUNNING, ctx.guild.id)
risk=READsays the action changes nothing.reply="public"shows the reply to the channel. Replies are private by default.ctx.db.fetch(Running, ...)returns a list ofRunning, each row checked against the model. A list of models is shown one line per item.UntrustedTextmarks text a member wrote, so AI assistants receive it as data and never as instructions.- The trailing underscore keeps Python's
listfree. The command is still/polls list.
6. Closing a poll: a job¶
class Open(BaseModel):
channel_id: int
question: str
options: list[str]
class Count(BaseModel):
choice: int
votes: int
@plugin.job
async def close(ctx: Ctx, poll: int) -> None:
async with ctx.db.transaction() as tx:
found = await tx.fetchrow(Open, LOCK_RUNNING, ctx.guild.id, poll)
if found is None:
return
counts = {c.choice: c.votes for c in await tx.fetch(Count, COUNTS, ctx.guild.id, poll)}
await tx.execute(CLOSE, ctx.guild.id, poll)
lines = [f"{n}. {option}: {counts.get(n, 0)}" for n, option in enumerate(found.options, start=1)]
await tx.send(found.channel_id, f"**Poll {poll} has closed: {found.question}**\n" + "\n".join(lines))
- A job runs later, on teabot's queue. Its parameters after
ctxare what it is scheduled with:close.bind(poll=poll)in step 3, which pyright checks. - A job's key is its name and arguments, so scheduling the same
closeagain moves it, andtx.unschedule(close.bind(poll=...))removes it. - A job can run twice, after a crash. This one locks the poll and checks it is still running first, so a second run changes nothing.
tx.sendposts the results with the transaction: if the poll is closed, the results go out, and if anything fails first, neither happens. teabot posts them a moment after the commit, and retries while Discord is down.- Messages mention nobody unless you say so with
ping=. An@everyonein a question stays plain text.
7. Deleting a poll: plan, then apply¶
class Found(BaseModel):
id: int
question: UntrustedText
@plugin.action(risk=DESTRUCTIVE, needs="manage_messages")
async def delete(ctx: Ctx, poll: int) -> str:
"""Delete a poll and its votes.
Args:
poll: The poll's number, from /polls list.
"""
async with ctx.db.transaction() as tx:
await tx.execute(DELETE, ctx.guild.id, poll)
await tx.unschedule(close.bind(poll=poll))
return f"Deleted poll {poll}."
@delete.plan
async def plan_delete(ctx: Ctx, poll: int) -> Diff:
found = await ctx.db.fetchrow(Found, ONE, ctx.guild.id, poll)
if found is None:
raise ActionError("No poll has that number.")
return Diff(entries=[DiffEntry(change="delete", target=found.question, key=found.id)])
risk=DESTRUCTIVEis for changes that are hard to undo. Such an action needs a plan, written with@delete.plan.- The plan returns a
Diffof what would change. The member sees it, and confirms it within 15 minutes. If anything it shows changed meanwhile, they get a fresh plan instead. - The action itself then runs as a job. The member does not see its reply; they see that the change is applying.
8. Tests¶
Write tests/test_polls.py, with tests for each part. The finished file is examples/polls/tests/test_polls.py in teabot's repository; here are the parts that show something new.
Tests import from teabot.testing, and from your plugin:
import discord
import pytest
from teabot.testing import ActionFailed, FakeChannel, HarnessFactory, PluginHarness, Refused
from teabot_polls import Cfg, close, delete, list_, plugin, start, vote
A helper starts a poll:
async def started(harness: PluginHarness) -> tuple[FakeChannel, int]:
channel = harness.guild.add_channel(FakeChannel())
out = await harness.call(
start, channel=channel, question="Tea or coffee?", option_1="Tea", option_2="Coffee"
)
return channel, out.poll
The results, after the clock moves past the end:
async def test_the_results_are_posted_when_time_is_up(teabot_harness: HarnessFactory) -> None:
harness = await teabot_harness(plugin)
channel, poll = await started(harness)
voters = [harness.guild.add_member(discord.Permissions.none()) for _ in range(3)]
for member, option in zip(voters, [1, 1, 2], strict=True):
await harness.as_member(member).call(vote, poll=poll, option=option)
await harness.advance(minutes=61)
await harness.run_jobs()
assert channel.sent[-1].content == "**Poll 1 has closed: Tea or coffee?**\n1. Tea: 2\n2. Coffee: 1"
harness.call(start, ...)runs the action through teabot's real path, permissions and audit included. Pyright checks the arguments against the function, andoutis aStarted.- It calls as the server's owner, its first member, who has Administrator.
harness.as_member(member).call(...)calls as someone else. harness.advance(minutes=61)moves the clock:ctx.now,now()in your SQL, and when jobs fall due.harness.run_jobs()then runs the due jobs, and raises with the job's own error if one fails.
Settings, as an admin would set them:
async def test_only_the_voter_role_may_vote(teabot_harness: HarnessFactory) -> None:
harness = await teabot_harness(plugin)
voters = harness.guild.add_role("voters")
await harness.configure(Cfg(voter_role=voters.id))
_, poll = await started(harness)
outsider = harness.guild.add_member(discord.Permissions.none())
with pytest.raises(ActionFailed) as caught:
await harness.as_member(outsider).call(vote, poll=poll, option=1)
assert caught.value.public_message == "You need the voter role to vote here."
A plan, confirmed:
async def test_deleting_shows_a_plan_and_stops_the_results(teabot_harness: HarnessFactory) -> None:
harness = await teabot_harness(plugin)
channel, poll = await started(harness)
plan = await harness.plan(delete, poll=poll)
assert [(e.change, e.target) for e in plan.entries] == [("delete", "Tea or coffee?")]
await harness.confirm(plan)
assert await harness.call(list_) == []
await harness.advance(minutes=61)
await harness.run_jobs()
assert len(channel.sent) == 1
And a job run a second time, which must change nothing:
async def test_closing_twice_posts_the_results_once(teabot_harness: HarnessFactory) -> None:
harness = await teabot_harness(plugin)
channel, poll = await started(harness)
await harness.advance(minutes=61)
await harness.run_jobs()
await harness.run_job(close.bind(poll=poll))
assert len(channel.sent) == 2
Run them:
The snapshot test fails once, because the commands changed from hello to the poll commands. That is its job: it stops a renamed option or job argument reaching your servers by accident. Accept the new commands:
The tests also run teabot's checks on your code. They refuse imports from teabot's internals, reading the clock directly, SET in SQL, and a README without its "External connections".
9. Growing past one file¶
Move plugin = Plugin(...) and type Ctx into plugin.py, and import them from every other module. teabot imports every module of the package when it loads the plugin, so actions in actions.py and jobs in jobs.py register themselves. It skips tests, modules whose names start with _, and __main__.
10. Ship it¶
- Update the plugin's
README.mdand the docstring at the top of__init__.py, which still describehello, to list the poll commands. -
Stop
teabot devwith Ctrl+C, and rebuild the Compose bot with the plugin in it, so it runs without you:Then turn the plugin on in your server, if it is not on already:
To share it with other instances, see Publishing a plugin.