Metadata-Version: 2.5
Name: botpage
Version: 1.0.0
Summary: The official async Python SDK for accessing your BotPage dashboard configurations.
Project-URL: Homepage, https://botpage.xyz
Project-URL: Documentation, https://botpage.xyz/docs
Author: BotPage
License-Expression: MIT
License-File: LICENSE
Keywords: botpage,dashboard,discord,discord-bot,sdk
Classifier: Framework :: AsyncIO
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: aiohttp>=3.9
Provides-Extra: dev
Requires-Dist: aiohttp<3.14; extra == 'dev'
Requires-Dist: aioresponses>=0.7.6; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# botpage

The official async Python SDK for [BotPage](https://botpage.xyz). 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

```bash
pip install botpage
```

Requires **Python 3.10+**. The only dependency is [aiohttp](https://docs.aiohttp.org/), which discord.py already uses, so installing the SDK adds nothing new to a discord.py bot.

## Quick start

```python
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:

```python
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, *, ...)`

```python
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.

```python
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`.

```python
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.

```python
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.

```python
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.

```python
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

```python
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:

```python
# 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:

   ```bash
   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:

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

## License

MIT
