yapbot API reference
Every public name in the yapbot package, with the signature the source actually has. The guided version — installing, a bot in ten lines, slash commands and examples — is Write a bot in Python.
Documented against yapbot 0.1.1, the current release on PyPI. yapbot.__version__ tells you which one you have; if it is newer than 0.1.1, this page may be behind it. Version history is at the end.
yapbot 0.1.1, the first release on PyPI (3 December 2026). Status is alpha: names can change in a minor release while the protocol is version 1. yapbot.__version__ is the string to log when you report a bug.
1. Install
pip install yapbot
Python 3.10 or newer. The wheel pulls in two dependencies, aiohttp>=3.9 and protobuf>=5.28, and ships the generated gateway stubs inside the package at yapbot/_proto, so there is no separate protobuf build step. Only yapbot is imported; the unrelated yap project on PyPI is not involved.
From a checkout, pip install client/bots/python installs the same package. The library is AGPL-3.0-only, like the server.
2. What the package exports
Everything public is re-exported from the package root, so one import line is enough:
from yapbot import Bot, BotStopped, Context, Rest, YapError
print(__import__("yapbot").__version__) # "0.1.1"
| Name | What it is |
|---|---|
Bot | The gateway connection, the decorators and the command dispatcher. |
Context | One command invocation: ids, author, text, reply(), history(). |
Rest | The REST calls a bot needs, authenticated with the same token. |
YapError | An API error carrying the server's status, code and message. |
BotStopped | Raised by run() when the token is rejected or revoked. |
__version__ | The package version, currently "0.1.1". |
GatewayClosed exists in yapbot.gateway for tests and for Bot's own reconnect loop; it is not part of the documented surface.
3. Bot
Constructor
Bot(server, token, *, prefix="!", logger=None)
| Argument | Meaning |
|---|---|
server | Base URL, for example "https://api.getyap.dev". A value with no :// gets https:// in front. REST goes to {base}/api/v1; the gateway to wss://{host}/gateway (ws:// for an http server). |
token | The bot token, yapbot_ plus 50 base64url characters, shown once by the Cheatsheet
developer portal. A bot has no password, so this is the whole credential. |
prefix | The character that starts a text command. Default "!". It may be more than one character; the whole prefix is stripped before the name is read. |
logger | A logging.Logger. Defaults to the module logger named "yapbot". Connection state, failed handlers and rejected tokens are logged here. |
State
Read-only from your code; the library fills these in as frames arrive.
| Attribute | Type | What it holds |
|---|---|---|
base, host | str | The normalised origin and hostname of the server. |
gateway_url | str | The WebSocket URL the bot connects to. |
token, prefix | str | As passed in. The token is never logged. |
user_id | int | The bot's own account id; 0 until Ready. |
username | str | The bot's username; "" until Ready. |
latency_ms | int | Round trip of the last Ping/Pong, in milliseconds; 0 until the first Pong. |
spaces | list[Space] | The proto Space messages from Ready, with their channels. Replaced on every reconnect. |
channel_space | dict[int, int] | Channel id to space id, from Ready and from space_of() lookups. |
rest | Rest | None | None until run() opens its aiohttp session, then the REST client. |
commands | dict[str, str] | Command name to help text, aliases included, sorted by name. |
slash_commands | list[dict[str, str]] | [{"name", "description"}] in registration order — the list the server stores. |
Decorators
@bot.command(name, *, help="", aliases=())
@bot.slash(name, *, description="")
@bot.event(name)
| Decorator | What it registers |
|---|---|
command | A prefixed command. name and every alias are matched case-insensitively as the first word after the prefix. help is what bot.commands reports; it is not sent anywhere. |
slash | A slash command. It runs on a message that begins /name, and the list is published with PUT /bots/{id}/commands when Ready arrives. Publishing failure is logged and not fatal. |
event | A gateway event handler by frame name — see Events. Several handlers may be registered for one name; they run in registration order. |
Decorators return the function unchanged, so they stack: one function can answer both !roll and /roll.
@bot.command("roll", help="roll dice", aliases=("dice",))
@bot.slash("roll", description="roll dice")
async def roll(ctx: Context, spec: str = "1d6") -> None:
await ctx.reply(spec)
A handler is called as fn(ctx, *words), where words are the whitespace-split arguments after the name — the same list as ctx.args. It may be a plain function or a coroutine function; a coroutine is awaited, and a sync handler's own await is your job. Handlers run concurrently in their own tasks, and an exception is logged and answered once with "Something went wrong running that command." rather than closing the socket.
Methods
await bot.run()
await bot.close()
await bot.send(channel_id, content)
await bot.space_of(channel_id)
| Method | Behaviour |
|---|---|
await run() | Opens the REST session, connects the gateway, sends Hello{access_token, protocol_version=1}, pings at half the advertised heartbeat_ms, and reconnects with exponential backoff (1 s, doubling, capped at 60 s). Returns when close() is called. A token the server rejects, revokes or rotates raises BotStopped instead of reconnecting. |
await close() | Stops the loop: cancels handler tasks still running and closes the socket, so a pending run() returns. |
await send(channel_id, content) | Sends SendMessage through the gateway, so the reply is ordered with what the bot just read. Accepts int or numeric str. Raises RuntimeError("not connected") before run() has a socket, and ValueError above 4,000 characters. |
await space_of(channel_id) | The space a channel belongs to, resolving it through GET /spaces when the bot connected before that channel existed. Returns 0 when the channel is not visible, and remembers the answer. |
4. Context
A dataclass, one per command invocation. It is constructed by the dispatcher, never by your code.
| Field | Type | Meaning |
|---|---|---|
bot | Bot | The bot that received the message. |
channel_id | int | Where the command was typed. |
space_id | int | The channel's space; 0 if it could not be resolved. |
message_id | int | The message that invoked the command. |
author_id | int | The sender's account id. |
author | str | The sender's username (not the display name). |
content | str | The whole message, prefix or slash included. |
args | list[str] | The words after the command name, split on whitespace. |
| Method | Behaviour |
|---|---|
await reply(text) | Sends to the same channel through the gateway, so it is ordered with the message being answered. Same 4,000-character cap as bot.send(). |
await history(limit=50) | GET /channels/{id}/messages for the same channel, oldest first. No cursor: the call returns the most recent limit messages (default 50, max 100). See Rest.history to page further back. |
5. Events
@bot.event(name) receives the frame's payload message as its only argument, the way the proto defines it. Two names are the library's own; everything else is a gateway frame name.
| Event | Payload | When it fires |
|---|---|---|
ready | Ready | Hello was accepted. user, spaces, heartbeat_ms and the current voice states are on it. Fires again after every reconnect. |
message | Message | A readable message arrived: the plaintext Message from MessageCreate. The bot's own messages, other bots' messages and anything starting yap1: never reach it. |
message_update | MessageUpdate | A message was edited; message holds the new body. |
message_delete | MessageDelete | A message was deleted; message_id and channel_id. |
reaction_update | ReactionUpdate | A reaction count changed: emoji, count, user_id, added. |
typing | Typing | Someone started typing. Ephemeral, never stored; throttle any reply. |
member_join | MemberJoin | Somebody accepted an invite, or the bot itself was installed. space_id plus the new member. |
channel_create | ChannelCreate | A channel was created; channel has id, space, name, kind and position. |
channel_update | ChannelUpdate | A channel was renamed or moved; category is set only when it changed. |
channel_delete | ChannelDelete | A channel was deleted; drop its history. |
space_update | SpaceUpdate | The space profile changed; the full current name, description, icon and banner are present. |
space_delete | SpaceDelete | The owner deleted the space. |
profile_update | ProfileUpdate | Somebody's display name, status, colour, avatar or banner changed. |
voice_state | VoiceState | Someone joined, left, muted or deafened in a voice channel. |
voice_joined | VoiceJoined | The answer to a VoiceJoin: the roster and the peer setup. |
voice_signal | VoiceSignal | WebRTC signalling for a bot that is in a call; from_user_id is set on the server's copy. |
voice_join_request | VoiceJoinRequest | A REST-only client asked this account's desktop app to join voice. |
voice_control | VoiceControl | A REST-only client toggled mute or deafen. |
error | Error | The server reported a protocol error. The library logs it, and an UNAUTHORIZED code also stops the bot with BotStopped. |
Pong is consumed to update latency_ms and is not delivered as an event. MessageCreate is delivered as message, never under its frame name.
An event handler's exception is logged and does not stop the loop or the other handlers.
6. Rest
The bot token works on REST exactly as it does on the gateway, with no login, refresh or proof. bot.rest exists once run() has started. To use REST on its own, construct it inside a session:
import aiohttp
from yapbot import Rest
async with aiohttp.ClientSession() as session:
rest = Rest("https://api.getyap.dev", "yapbot_...", session)
print(await rest.spaces())
Rest(base, token, session) strips a trailing slash from base and prefixes /api/v1 itself. Ids are accepted as int or numeric str, and every method raises YapError for a non-2xx answer. A 204 returns None.
Commands
| Method | Request |
|---|---|
await set_commands(bot_id, commands) | PUT /bots/{id}/commands with {"commands": [{"name", "description"}]}; replaces the previous list. What @bot.slash publishes for you. |
await commands(space_id) | GET /spaces/{id}/commands — every bot's commands in that space, for a / menu. |
Spaces, members and roles
| Method | Request |
|---|---|
await spaces() | GET /spaces — the spaces the bot is a member of, with channels. |
await members(space_id) | GET /spaces/{id}/members |
await roles(space_id) | GET /spaces/{id}/roles — @everyone first: {id, name, permissions, everyone, …}. |
await create_role(space_id, name, *, permissions=0) | POST /spaces/{id}/roles — needs MANAGE_ROLES. |
await update_role(role_id, *, name=None, color=None, permissions=None) | PATCH /roles/{id} — only the fields you pass. @everyone accepts only permissions. |
await delete_role(role_id) | DELETE /roles/{id} — @everyone cannot be deleted. |
await set_member_roles(space_id, user, role_ids) | PUT /spaces/{id}/members/{user}/roles with {"role_ids": [...]} — replaces the member's set; needs MANAGE_ROLES. |
await put_overwrite(space_id, *, scope, scope_id, target_kind, target_id, allow=0, deny=0) | PUT /spaces/{id}/overwrites — allow and deny bits for one role or member, on a channel or a category label. Needs MANAGE_ROLES. |
await delete_overwrite(space_id, *, scope, scope_id, target_kind, target_id) | DELETE /spaces/{id}/overwrites; the same call with both bit sets at 0 is equivalent. |
Channels
| Method | Request |
|---|---|
await create_category(space_id, name) | POST /spaces/{id}/categories — needs MANAGE_CHANNELS. |
await create_channel(space_id, name, *, kind="text", category="") | POST /spaces/{id}/channels — kind is "text" or "voice"; needs MANAGE_CHANNELS. |
await update_channel(channel_id, *, name=None, category=None) | PATCH /channels/{id} — rename, move, or both; needs MANAGE_CHANNELS. |
await delete_channel(channel_id) | DELETE /channels/{id} — deletes its messages too; needs MANAGE_CHANNELS. |
Messages
| Method | Request |
|---|---|
await history(channel_id, limit=50, before=None) | GET /channels/{id}/messages?limit=…&before=… — oldest first, up to limit (default 50, server max 100). Pass the oldest id you hold as before to page further back. The endpoint also accepts after; the wrapper does not expose it. |
await send_message(channel_id, content) | POST /channels/{id}/messages — the REST path. bot.send() uses the gateway instead, which keeps ordering. |
await edit_message(message_id, content) | PATCH /messages/{id} — only a message this bot wrote; the server refuses anyone else's. |
await delete_message(message_id) | DELETE /messages/{id} — the author or a member with MANAGE_MESSAGES. |
await add_reaction(message_id, emoji) | PUT /messages/{id}/reactions/{emoji} — idempotent; the emoji is percent-encoded as a path segment. |
await remove_reaction(message_id, emoji) | DELETE /messages/{id}/reactions/{emoji} — removes this bot's own reaction only. |
await pins(channel_id) | GET /channels/{id}/pins — up to 50, newest pin first; needs VIEW_CHANNEL. |
await pin(channel_id, message_id) | PUT /channels/{id}/pins/{message} |
await unpin(channel_id, message_id) | DELETE /channels/{id}/pins/{message} |
Invites and moderation
| Method | Request |
|---|---|
await create_invite(space_id) | POST /spaces/{id}/invites — a code valid for 7 days; needs CREATE_INVITE, which @everyone grants. |
await bans(space_id) | GET /spaces/{id}/bans — newest first; needs BAN. |
await ban(space_id, user, reason="") | PUT /spaces/{id}/bans/{user} — user is an id or a username; bans and removes the membership in one call. |
await unban(space_id, user) | DELETE /spaces/{id}/bans/{user} — lifts the ban, does not re-add the member. |
await kick(space_id, user) | DELETE /spaces/{id}/members/{user} — removes the membership; a fresh invite can bring them back. |
7. Errors
YapError(status, code, message)
str(exc) is "{status} {code}: {message}", and the three parts are also attributes. status is the HTTP status; code is the server's short error name, or "http" when the body was not the usual JSON; message is written for a person and is safe to log.
from yapbot import YapError
try:
await bot.rest.create_channel(space_id, "logs", category="Team")
except YapError as exc:
if exc.status == 403:
print("the bot lacks MANAGE_CHANNELS here")
else:
print(exc.status, exc.code, exc.message)
| Exception | Raised by | What to do |
|---|---|---|
YapError | Every Rest call | Read status and code; retry only 429 and 5xx. |
BotStopped | run() | The token was rejected, revoked or rotated. Rotate it in the developer portal; reconnecting cannot fix it. |
RuntimeError | bot.send() | Called before the gateway connected. Send from a handler, or wait for ready. |
ValueError | bot.send(), ctx.reply() | The message is over 4,000 characters, or a frame would exceed 64 KiB. Split it. |
8. Limits and behaviour
| Limit | Value |
|---|---|
| Message length | 4,000 characters; one gateway frame is 64 KiB. The library raises before the server has to refuse. |
| Slash commands per bot | 25. Names are 1–32 characters of a-z, 0-9, - or _ (lower-cased for you); descriptions up to 100 characters. |
| History page | 50 messages by default, 100 at most, returned oldest first; limit is clamped by the server. |
| Heartbeat | Half the heartbeat_ms from Ready; the server closes a socket silent for 2.5× that. |
| Reconnect | 1 s, doubling, capped at 60 s, reset after a successful connection. |
| Python | 3.10 or newer, with aiohttp>=3.9 and protobuf>=5.28. |
A bot is a real account and an ordinary member of the spaces it was invited to, so the same permission bits decide what it can read, send and manage. Account-level actions — creating spaces, DMs, friends, profiles, API keys, encryption keys — belong to people and answer 403. Encrypted spaces stay sealed: the bot has no key, receives yap1: envelopes, and the library skips them before commands or handlers see them. Two bots never answer each other, because a message whose author is a bot is skipped exactly like the bot's own.
Version history
Both releases are on PyPI, and the package code is the same in each: 0.1.1 differs from 0.1.0 only in yapbot/__init__.py's __version__ and the packaged metadata. There is no CHANGELOG in the package yet; this table is the record.
| Version | What it is |
|---|---|
0.1.1 | Current, and the version this page documents. Republished 0.1.0 with the corrected README; the importable surface is unchanged: Bot, BotStopped, Context, Rest, YapError, __version__. |
0.1.0 | First upload: the asyncio gateway client, the 29 REST helpers, the generated protobuf modules under yapbot._proto, and py.typed for type checkers. Requires Python 3.10 or newer. |
Published from the repository with git tag python-v0.1.1; the workflow refuses a tag whose version does not match both pyproject.toml and yapbot.__version__.
Sources: client/bots/python/yapbot (bot.py, rest.py, gateway.py), published as yapbot on PyPI. Updated . The guided version is Write a bot in Python.