Skip to main content

botpage

The official async Python SDK for BotPage. Use it to read and update each server's dashboard settings from your Discord bot.

The developer API is available to Premium bots. Full documentation: https://botpage.xyz/docs

Installation

pip install botpage

Requires Python 3.10+. The only dependency is aiohttp, which discord.py already uses, so installing the SDK adds nothing new to a discord.py bot.

Quick start

import asyncio
from botpage import BotpageClient

async def main() -> None:
    async with BotpageClient("your-api-key") as botpage:
        # Read all settings for a Discord server
        config = await botpage.get_guild_data("123456789012345678")

        # Read a single field (None if it isn't set)
        welcome_channel = await botpage.get_guild_field("123456789012345678", "welcomeChannel")

        # Update a single field
        await botpage.update_guild_field("123456789012345678", "prefix", "?")

asyncio.run(main())

Guild IDs can be strings or ints, so you can pass discord.py's guild.id as it is.

Using it with discord.py

Create the client at module level, read settings in your handlers, and close the client when the bot shuts down:

import os

import discord
from botpage import BotpageClient, BotpageError

intents = discord.Intents.default()
intents.message_content = True

botpage = BotpageClient(os.environ["BOTPAGE_API_KEY"])


class Bot(discord.Client):
    async def close(self) -> None:
        await botpage.close()
        await super().close()


bot = Bot(intents=intents)


@bot.event
async def on_message(message: discord.Message) -> None:
    if message.author.bot or message.guild is None:
        return

    try:
        prefix = await botpage.get_guild_field(message.guild.id, "prefix") or "!"
    except BotpageError:
        prefix = "!"

    if message.content == f"{prefix}ping":
        await message.reply("Pong!")


bot.run(os.environ["DISCORD_TOKEN"])

Reads are cached for a few seconds, so calling get_guild_field in every message handler is fine. See https://botpage.xyz/docs for a full example bot.

API reference

BotpageClient(api_key, *, ...)

BotpageClient(
    api_key,
    *,
    base_url="https://botpage.xyz/api/v1",
    cache_ttl_seconds=5,
    max_requests_per_minute=100,
    auto_wait_on_rate_limit=False,
    session=None,
)
Option Default Description
api_key (required) Your developer API key from the BotPage dashboard. An empty key raises ValueError.
base_url "https://botpage.xyz/api/v1" The API's base URL. Change it to test against a staging or local instance. A trailing slash is ignored.
cache_ttl_seconds 5 How long reads are cached, per server. 0 turns the cache off. Negative values count as 0.
max_requests_per_minute 100 The local rate limit. Values below 1 count as 1.
auto_wait_on_rate_limit False When True, the client sleeps until it may send again instead of raising BotpageRateLimitError.
session None An aiohttp.ClientSession to use instead of one the client creates. The client never closes it.

Creating the client doesn't open a connection, so you can create it at module level before the event loop starts.

await get_guild_data(guild_id, *, force=False) -> dict

Returns all of a server's dashboard values as a dict.

config = await botpage.get_guild_data("123456789012345678")
# {"prefix": "!", "welcomeEnabled": True, "logsChannel": "987654321098765432"}

force=True skips the cache and fetches the latest values.

await get_guild_field(guild_id, field, *, force=False) -> Any

Returns one value, or None if it isn't set. It uses the same cache as get_guild_data.

prefix = await botpage.get_guild_field("123456789012345678", "prefix")

await update_guild_data(guild_id, updates) -> dict

Updates several fields in one request and returns all of the server's values after the update.

updated = await botpage.update_guild_data(
    "123456789012345678",
    {"prefix": "?", "welcomeEnabled": False},
)

await update_guild_field(guild_id, field, value) -> dict

Updates one field and returns all of the server's values after the update.

await botpage.update_guild_field("123456789012345678", "logsChannel", "987654321098765432")

clear_cache(guild_id=None) -> None

Forgets one server's cached values, or every server's when called with no ID. Use it after settings change somewhere else, such as on the dashboard, and you need the next read to fetch them. It isn't async.

botpage.clear_cache("123456789012345678")  # one server
botpage.clear_cache()                      # every server

await close() -> None

Closes the HTTP session the client created. Call it when your bot shuts down to avoid "Unclosed client session" warnings. A session passed through session= is left open. Calling close() more than once is safe, and a request made after close() opens a new session.

Every dict the client returns is a copy, so adding, removing or replacing its keys never affects the cache. The copy is shallow: nested lists and dicts are shared, so don't change those in place.

Errors

from botpage import BotpageError, BotpageRateLimitError

try:
    await botpage.update_guild_field(guild_id, "prefix", "?")
except BotpageRateLimitError as err:
    print(f"Rate limited, retry in {err.retry_after:.1f}s")
except BotpageError as err:
    print(f"BotPage request failed ({err.status}): {err}")
  • BotpageError is raised for every SDK failure, so one except BotpageError catches them all. status is the HTTP status, or None for a network failure. The message includes the API's error text, for example an unknown field or a bot that isn't a Premium bot.
  • BotpageRateLimitError is a subclass of BotpageError with status set to 429. retry_after is how long to wait in seconds (a float).

Caching

  • Reads are cached in memory per server for cache_ttl_seconds (5 seconds by default). A read within that time makes no HTTP request.
  • After an update, the cache holds the values the API returned, so your next read sees what you just wrote.
  • Concurrent reads for the same server share one HTTP request, so a burst of events doesn't send a burst of identical calls.
  • The cache holds at most 1000 servers. When it's full, expired entries are dropped first, then the oldest one.
  • Use force=True to skip the cache for one read, clear_cache() to empty it, or cache_ttl_seconds=0 to turn it off.

Rate limiting

The client limits itself so it stops you before the API rejects you:

  • At most max_requests_per_minute requests (100 by default) in any 60-second window. Cached reads don't count.
  • When the API answers with a 429, the client respects its Retry-After header (10 seconds if missing) and sends nothing until then.
  • When the API reports no remaining quota (x-ratelimit-remaining: 0), the client holds back for 5 seconds.

A request the API answers with a 429 always raises BotpageRateLimitError. After that, and whenever the local limit is reached, later calls raise BotpageRateLimitError without touching the network until the limit resets. With auto_wait_on_rate_limit=True, those later calls sleep until the limit resets and then send the request.

Closing the client

Three ways to manage the HTTP session:

# 1. Long-running bot: create once, close on shutdown.
botpage = BotpageClient(api_key)
...
await botpage.close()

# 2. Script: `async with` closes the session on exit.
async with BotpageClient(api_key) as botpage:
    config = await botpage.get_guild_data(guild_id)

# 3. Your own aiohttp session: the client uses it and never closes it.
async with aiohttp.ClientSession() as session:
    botpage = BotpageClient(api_key, session=session)
    config = await botpage.get_guild_data(guild_id)

The client reuses one session for all its requests, so connections are pooled.

Type hints

The package ships type hints (py.typed), so editors autocomplete it and type checkers check your calls.

Releasing

For maintainers. Publishing is done by hand.

  1. Bump version in pyproject.toml.

  2. Run the tests: pip install -e ".[dev]", then pytest.

  3. Build the wheel and sdist from this folder:

    pip install --upgrade build twine
    rm -rf dist        # PowerShell: Remove-Item -Recurse -Force dist
    python -m build
    
  4. Upload with a PyPI API token (create one at https://pypi.org/manage/account/token/). Twine reads the token from the environment:

    TWINE_USERNAME=__token__ TWINE_PASSWORD=pypi-... twine upload dist/*
    

License

MIT

Metadata

Release files for botpage 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for botpage 1.0.0
File Size Uploaded Provenance Actions
botpage-1.0.0.tar.gz 13.0 kB Without provenance Details for botpage-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for botpage 1.0.0
File Interpreter ABI Platform Actions
botpage-1.0.0-py3-none-any.whl Python 3 none any Details for botpage-1.0.0-py3-none-any.whl

Total release size: 23.4 kB

Release files / botpage-1.0.0.tar.gz

Download URL botpage-1.0.0.tar.gz
Size 13.0 kB
Tags Source
SHA-256 checksum
How to use checksums
36bddda67952bb10a312b8f2c85e929eba33dc47da27f72b4b6c9c60a592d94b
BLAKE2b-256 checksum
How to use checksums
be4894592029b11665bc57ace892cb7937719c6f619cb6f7dbc909a850d81f58
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / botpage-1.0.0-py3-none-any.whl

Download URL botpage-1.0.0-py3-none-any.whl
Size 10.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
937d72d2dd5b3160a3fcd8d7835c91a7ed1761c22c6c5b9efd30105634c8337c
BLAKE2b-256 checksum
How to use checksums
0f6b139e23b51ee56e88069f33cdb1a56595e6ee9992322cdd9055bc3a4ac607
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for botpage 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page