botpage 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- botpage/__init__.py +6 -0
- botpage/_client.py +271 -0
- botpage/_clock.py +7 -0
- botpage/_errors.py +17 -0
- botpage/py.typed +0 -0
- botpage-1.0.0.dist-info/METADATA +265 -0
- botpage-1.0.0.dist-info/RECORD +9 -0
- botpage-1.0.0.dist-info/WHEEL +4 -0
- botpage-1.0.0.dist-info/licenses/LICENSE +21 -0
botpage/__init__.py
ADDED
botpage/_client.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import math
|
|
5
|
+
from collections import deque
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, Iterable, Union
|
|
8
|
+
from urllib.parse import quote
|
|
9
|
+
|
|
10
|
+
import aiohttp
|
|
11
|
+
|
|
12
|
+
from . import _clock
|
|
13
|
+
from ._errors import BotpageError, BotpageRateLimitError
|
|
14
|
+
|
|
15
|
+
DEFAULT_BASE_URL = "https://botpage.xyz/api/v1"
|
|
16
|
+
DEFAULT_RETRY_AFTER_SECONDS = 10.0
|
|
17
|
+
MAX_CACHE_ENTRIES = 1000
|
|
18
|
+
RATE_WINDOW_SECONDS = 60.0
|
|
19
|
+
RATE_LIMIT_EXHAUSTED_COOLDOWN_SECONDS = 5.0
|
|
20
|
+
# The shortest wait the local limiter asks for, and the margin past the oldest request's expiry.
|
|
21
|
+
MIN_RATE_LIMIT_WAIT_SECONDS = 0.1
|
|
22
|
+
RATE_WINDOW_MARGIN_SECONDS = 0.05
|
|
23
|
+
_INVALID_JSON = object()
|
|
24
|
+
|
|
25
|
+
# A Discord guild ID; discord.py gives it as an int (`guild.id`), the API takes a string.
|
|
26
|
+
GuildId = Union[str, int]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def _read_json(response: aiohttp.ClientResponse) -> Any:
|
|
30
|
+
"""The parsed JSON body, or ``_INVALID_JSON`` when the body isn't JSON."""
|
|
31
|
+
try:
|
|
32
|
+
return await response.json(content_type=None)
|
|
33
|
+
except ValueError:
|
|
34
|
+
return _INVALID_JSON
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _data_of(body: dict[str, Any]) -> dict[str, Any]:
|
|
38
|
+
return dict(body.get("data") or {})
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _parse_retry_after(header: str | None) -> float:
|
|
42
|
+
try:
|
|
43
|
+
seconds = float(header) if header is not None else DEFAULT_RETRY_AFTER_SECONDS
|
|
44
|
+
except ValueError:
|
|
45
|
+
return DEFAULT_RETRY_AFTER_SECONDS
|
|
46
|
+
return seconds if math.isfinite(seconds) and seconds >= 0 else DEFAULT_RETRY_AFTER_SECONDS
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class _CacheEntry:
|
|
51
|
+
data: dict[str, Any]
|
|
52
|
+
expires_at: float
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _retrieve_exception(task: asyncio.Task[Any]) -> None:
|
|
56
|
+
"""Mark a shared read's failure as seen, in case every caller was cancelled meanwhile."""
|
|
57
|
+
if not task.cancelled():
|
|
58
|
+
task.exception()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class BotpageClient:
|
|
62
|
+
"""Async client for the BotPage developer API."""
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
api_key: str,
|
|
67
|
+
*,
|
|
68
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
69
|
+
cache_ttl_seconds: float = 5,
|
|
70
|
+
max_requests_per_minute: int = 100,
|
|
71
|
+
auto_wait_on_rate_limit: bool = False,
|
|
72
|
+
session: aiohttp.ClientSession | None = None,
|
|
73
|
+
) -> None:
|
|
74
|
+
"""Create a client. No HTTP session is opened until the first request.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
api_key: Your BotPage developer API key.
|
|
78
|
+
base_url: The API's base URL, for testing against another instance.
|
|
79
|
+
cache_ttl_seconds: How long reads are cached. ``0`` disables the cache.
|
|
80
|
+
max_requests_per_minute: The local rate limit.
|
|
81
|
+
auto_wait_on_rate_limit: Sleep until the limit resets instead of raising.
|
|
82
|
+
session: An aiohttp session to use. The client never closes it.
|
|
83
|
+
"""
|
|
84
|
+
if not api_key:
|
|
85
|
+
raise ValueError("BotpageClient requires an API key.")
|
|
86
|
+
self._api_key = api_key
|
|
87
|
+
self._base_url = base_url[:-1] if base_url.endswith("/") else base_url
|
|
88
|
+
self._cache_ttl_seconds = max(0.0, cache_ttl_seconds)
|
|
89
|
+
self._max_requests_per_minute = max(1, max_requests_per_minute)
|
|
90
|
+
self._auto_wait_on_rate_limit = auto_wait_on_rate_limit
|
|
91
|
+
# When each request in the last minute was sent, oldest first.
|
|
92
|
+
self._request_times: deque[float] = deque()
|
|
93
|
+
# Set by a 429 or `x-ratelimit-remaining: 0`; no request is sent before it.
|
|
94
|
+
self._server_cooldown_until = 0.0
|
|
95
|
+
self._session = session
|
|
96
|
+
self._owns_session = session is None
|
|
97
|
+
self._cache: dict[str, _CacheEntry] = {}
|
|
98
|
+
# One shared read per guild while it's in flight, so concurrent reads make one request.
|
|
99
|
+
self._in_flight: dict[str, asyncio.Task[dict[str, Any]]] = {}
|
|
100
|
+
# In-flight reads that started before an update or clear_cache: their data
|
|
101
|
+
# is older than what's now known, so they must not be cached when they land.
|
|
102
|
+
self._stale_reads: set[str] = set()
|
|
103
|
+
|
|
104
|
+
async def __aenter__(self) -> BotpageClient:
|
|
105
|
+
return self
|
|
106
|
+
|
|
107
|
+
async def __aexit__(self, *exc_info: object) -> None:
|
|
108
|
+
await self.close()
|
|
109
|
+
|
|
110
|
+
async def close(self) -> None:
|
|
111
|
+
"""Close the HTTP session the client created. A session passed in is left open."""
|
|
112
|
+
if self._owns_session and self._session is not None:
|
|
113
|
+
session, self._session = self._session, None
|
|
114
|
+
await session.close()
|
|
115
|
+
|
|
116
|
+
def _cache_update(self, key: str, guild: dict[str, Any]) -> None:
|
|
117
|
+
"""Cache the guild an update returned, in place of anything a read fetched before it."""
|
|
118
|
+
self._mark_reads_stale([key])
|
|
119
|
+
self._set_cache_entry(key, guild)
|
|
120
|
+
|
|
121
|
+
def _set_cache_entry(self, key: str, data: dict[str, Any]) -> None:
|
|
122
|
+
"""Cache a guild's values as the newest entry, making room if the cache is full."""
|
|
123
|
+
if self._cache_ttl_seconds <= 0:
|
|
124
|
+
return
|
|
125
|
+
now = _clock.now()
|
|
126
|
+
if key in self._cache:
|
|
127
|
+
# Re-inserting moves the key to the end of the dict, the newest position.
|
|
128
|
+
del self._cache[key]
|
|
129
|
+
elif len(self._cache) >= MAX_CACHE_ENTRIES:
|
|
130
|
+
for expired in [k for k, e in self._cache.items() if e.expires_at <= now]:
|
|
131
|
+
del self._cache[expired]
|
|
132
|
+
if len(self._cache) >= MAX_CACHE_ENTRIES:
|
|
133
|
+
del self._cache[next(iter(self._cache))]
|
|
134
|
+
self._cache[key] = _CacheEntry(dict(data), now + self._cache_ttl_seconds)
|
|
135
|
+
|
|
136
|
+
def _get_session(self) -> aiohttp.ClientSession:
|
|
137
|
+
if self._session is None:
|
|
138
|
+
self._session = aiohttp.ClientSession()
|
|
139
|
+
return self._session
|
|
140
|
+
|
|
141
|
+
async def _wait_for_rate_limit(self) -> None:
|
|
142
|
+
"""Hold a request back until the local window has room, recording it once it may proceed."""
|
|
143
|
+
while True:
|
|
144
|
+
now = _clock.now()
|
|
145
|
+
# The server's cooldown is checked first, and a blocked call never enters the window.
|
|
146
|
+
if self._server_cooldown_until > now:
|
|
147
|
+
wait = self._server_cooldown_until - now
|
|
148
|
+
if self._auto_wait_on_rate_limit:
|
|
149
|
+
await _clock.sleep(wait)
|
|
150
|
+
continue
|
|
151
|
+
raise BotpageRateLimitError(
|
|
152
|
+
"[Botpage SDK] Server rate limit cooldown active. Blocked locally to "
|
|
153
|
+
f"protect your quota. Try again in {math.ceil(wait)}s.",
|
|
154
|
+
wait,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
while self._request_times and self._request_times[0] <= now - RATE_WINDOW_SECONDS:
|
|
158
|
+
self._request_times.popleft()
|
|
159
|
+
if len(self._request_times) < self._max_requests_per_minute:
|
|
160
|
+
self._request_times.append(now)
|
|
161
|
+
return
|
|
162
|
+
wait = max(
|
|
163
|
+
MIN_RATE_LIMIT_WAIT_SECONDS,
|
|
164
|
+
self._request_times[0] + RATE_WINDOW_SECONDS - now + RATE_WINDOW_MARGIN_SECONDS,
|
|
165
|
+
)
|
|
166
|
+
if self._auto_wait_on_rate_limit:
|
|
167
|
+
await _clock.sleep(wait)
|
|
168
|
+
continue
|
|
169
|
+
raise BotpageRateLimitError(
|
|
170
|
+
f"[Botpage SDK] Local rate limit reached ({self._max_requests_per_minute} req/min). "
|
|
171
|
+
f"Blocked locally to avoid server rejection. Retry in {math.ceil(wait)}s.",
|
|
172
|
+
wait,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
async def _request(self, method: str, endpoint: str, json: Any = None) -> dict[str, Any]:
|
|
176
|
+
await self._wait_for_rate_limit()
|
|
177
|
+
session = self._get_session()
|
|
178
|
+
headers = {
|
|
179
|
+
"Content-Type": "application/json",
|
|
180
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
181
|
+
}
|
|
182
|
+
try:
|
|
183
|
+
async with session.request(
|
|
184
|
+
method, f"{self._base_url}{endpoint}", headers=headers, json=json
|
|
185
|
+
) as response:
|
|
186
|
+
body = await _read_json(response)
|
|
187
|
+
status = response.status
|
|
188
|
+
retry_after_header = response.headers.get("Retry-After")
|
|
189
|
+
rate_limit_exhausted = response.headers.get("x-ratelimit-remaining") == "0"
|
|
190
|
+
except (aiohttp.ClientError, asyncio.TimeoutError) as err:
|
|
191
|
+
raise BotpageError(f"Network request failed: {err}") from err
|
|
192
|
+
|
|
193
|
+
if rate_limit_exhausted:
|
|
194
|
+
self._server_cooldown_until = _clock.now() + RATE_LIMIT_EXHAUSTED_COOLDOWN_SECONDS
|
|
195
|
+
|
|
196
|
+
if not 200 <= status < 300:
|
|
197
|
+
message = (isinstance(body, dict) and body.get("message")) or f"HTTP Error {status}"
|
|
198
|
+
if status == 429:
|
|
199
|
+
retry_after = _parse_retry_after(retry_after_header)
|
|
200
|
+
self._server_cooldown_until = _clock.now() + retry_after
|
|
201
|
+
raise BotpageRateLimitError(f"Botpage API Error: {message}", retry_after)
|
|
202
|
+
raise BotpageError(f"Botpage API Error: {message}", status)
|
|
203
|
+
|
|
204
|
+
if body is _INVALID_JSON:
|
|
205
|
+
raise BotpageError("Botpage API Error: response was not valid JSON", status)
|
|
206
|
+
return body if isinstance(body, dict) else {}
|
|
207
|
+
|
|
208
|
+
async def get_guild_data(self, guild_id: GuildId, *, force: bool = False) -> dict[str, Any]:
|
|
209
|
+
"""Return all of a guild's dashboard values.
|
|
210
|
+
|
|
211
|
+
Reads are cached per guild for ``cache_ttl_seconds``. ``force=True`` skips the cache.
|
|
212
|
+
"""
|
|
213
|
+
key = str(guild_id)
|
|
214
|
+
entry = None if force else self._cache.get(key)
|
|
215
|
+
if entry is not None:
|
|
216
|
+
if entry.expires_at > _clock.now():
|
|
217
|
+
return dict(entry.data)
|
|
218
|
+
del self._cache[key]
|
|
219
|
+
|
|
220
|
+
task = self._in_flight.get(key)
|
|
221
|
+
if task is None:
|
|
222
|
+
task = asyncio.create_task(self._fetch_guild_data(key))
|
|
223
|
+
self._in_flight[key] = task
|
|
224
|
+
task.add_done_callback(_retrieve_exception)
|
|
225
|
+
# Shielded so one caller being cancelled doesn't cancel the read the others share.
|
|
226
|
+
return dict(await asyncio.shield(task))
|
|
227
|
+
|
|
228
|
+
async def _fetch_guild_data(self, key: str) -> dict[str, Any]:
|
|
229
|
+
try:
|
|
230
|
+
res = await self._request("GET", f"/data?guildId={quote(key, safe='')}")
|
|
231
|
+
data = _data_of(res)
|
|
232
|
+
if key not in self._stale_reads:
|
|
233
|
+
self._set_cache_entry(key, data)
|
|
234
|
+
return data
|
|
235
|
+
finally:
|
|
236
|
+
# Cleared as the read ends, however it ends, so a failure never reaches a later call.
|
|
237
|
+
self._in_flight.pop(key, None)
|
|
238
|
+
self._stale_reads.discard(key)
|
|
239
|
+
|
|
240
|
+
def _mark_reads_stale(self, keys: Iterable[str]) -> None:
|
|
241
|
+
self._stale_reads.update(key for key in keys if key in self._in_flight)
|
|
242
|
+
|
|
243
|
+
async def get_guild_field(self, guild_id: GuildId, field: str, *, force: bool = False) -> Any:
|
|
244
|
+
"""Return one dashboard value, or ``None`` if it isn't set. Uses the same cache."""
|
|
245
|
+
data = await self.get_guild_data(guild_id, force=force)
|
|
246
|
+
return data.get(field)
|
|
247
|
+
|
|
248
|
+
async def update_guild_data(self, guild_id: GuildId, updates: dict[str, Any]) -> dict[str, Any]:
|
|
249
|
+
"""Update several fields and return all of the guild's values after the update."""
|
|
250
|
+
res = await self._request("PATCH", "/data", {"guildId": str(guild_id), "updates": updates})
|
|
251
|
+
data = _data_of(res)
|
|
252
|
+
self._cache_update(str(guild_id), data)
|
|
253
|
+
return data
|
|
254
|
+
|
|
255
|
+
async def update_guild_field(self, guild_id: GuildId, field: str, value: Any) -> dict[str, Any]:
|
|
256
|
+
"""Update one field and return all of the guild's values after the update."""
|
|
257
|
+
res = await self._request(
|
|
258
|
+
"PATCH", "/data", {"guildId": str(guild_id), "field": field, "value": value}
|
|
259
|
+
)
|
|
260
|
+
data = _data_of(res)
|
|
261
|
+
self._cache_update(str(guild_id), data)
|
|
262
|
+
return data
|
|
263
|
+
|
|
264
|
+
def clear_cache(self, guild_id: GuildId | None = None) -> None:
|
|
265
|
+
"""Forget one guild's cached values, or every guild's when no ID is given."""
|
|
266
|
+
if guild_id is None:
|
|
267
|
+
self._cache.clear()
|
|
268
|
+
self._mark_reads_stale(self._in_flight)
|
|
269
|
+
else:
|
|
270
|
+
self._cache.pop(str(guild_id), None)
|
|
271
|
+
self._mark_reads_stale([str(guild_id)])
|
botpage/_clock.py
ADDED
botpage/_errors.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class BotpageError(Exception):
|
|
5
|
+
"""Raised for every SDK failure. ``status`` is the HTTP status, or ``None`` for network errors."""
|
|
6
|
+
|
|
7
|
+
def __init__(self, message: str, status: int | None = None) -> None:
|
|
8
|
+
super().__init__(message)
|
|
9
|
+
self.status = status
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BotpageRateLimitError(BotpageError):
|
|
13
|
+
"""Raised when a request is rate limited. ``retry_after`` is the wait in seconds."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str, retry_after: float = 0) -> None:
|
|
16
|
+
super().__init__(message, 429)
|
|
17
|
+
self.retry_after = retry_after
|
botpage/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: botpage
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: The official async Python SDK for accessing your BotPage dashboard configurations.
|
|
5
|
+
Project-URL: Homepage, https://botpage.xyz
|
|
6
|
+
Project-URL: Documentation, https://botpage.xyz/docs
|
|
7
|
+
Author: BotPage
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: botpage,dashboard,discord,discord-bot,sdk
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: aiohttp>=3.9
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: aiohttp<3.14; extra == 'dev'
|
|
18
|
+
Requires-Dist: aioresponses>=0.7.6; extra == 'dev'
|
|
19
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# botpage
|
|
24
|
+
|
|
25
|
+
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.
|
|
26
|
+
|
|
27
|
+
The developer API is available to Premium bots. Full documentation: https://botpage.xyz/docs
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install botpage
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
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.
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import asyncio
|
|
41
|
+
from botpage import BotpageClient
|
|
42
|
+
|
|
43
|
+
async def main() -> None:
|
|
44
|
+
async with BotpageClient("your-api-key") as botpage:
|
|
45
|
+
# Read all settings for a Discord server
|
|
46
|
+
config = await botpage.get_guild_data("123456789012345678")
|
|
47
|
+
|
|
48
|
+
# Read a single field (None if it isn't set)
|
|
49
|
+
welcome_channel = await botpage.get_guild_field("123456789012345678", "welcomeChannel")
|
|
50
|
+
|
|
51
|
+
# Update a single field
|
|
52
|
+
await botpage.update_guild_field("123456789012345678", "prefix", "?")
|
|
53
|
+
|
|
54
|
+
asyncio.run(main())
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Guild IDs can be strings or ints, so you can pass discord.py's `guild.id` as it is.
|
|
58
|
+
|
|
59
|
+
## Using it with discord.py
|
|
60
|
+
|
|
61
|
+
Create the client at module level, read settings in your handlers, and close the client when the bot shuts down:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import os
|
|
65
|
+
|
|
66
|
+
import discord
|
|
67
|
+
from botpage import BotpageClient, BotpageError
|
|
68
|
+
|
|
69
|
+
intents = discord.Intents.default()
|
|
70
|
+
intents.message_content = True
|
|
71
|
+
|
|
72
|
+
botpage = BotpageClient(os.environ["BOTPAGE_API_KEY"])
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Bot(discord.Client):
|
|
76
|
+
async def close(self) -> None:
|
|
77
|
+
await botpage.close()
|
|
78
|
+
await super().close()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
bot = Bot(intents=intents)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@bot.event
|
|
85
|
+
async def on_message(message: discord.Message) -> None:
|
|
86
|
+
if message.author.bot or message.guild is None:
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
prefix = await botpage.get_guild_field(message.guild.id, "prefix") or "!"
|
|
91
|
+
except BotpageError:
|
|
92
|
+
prefix = "!"
|
|
93
|
+
|
|
94
|
+
if message.content == f"{prefix}ping":
|
|
95
|
+
await message.reply("Pong!")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
bot.run(os.environ["DISCORD_TOKEN"])
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
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.
|
|
102
|
+
|
|
103
|
+
## API reference
|
|
104
|
+
|
|
105
|
+
### `BotpageClient(api_key, *, ...)`
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
BotpageClient(
|
|
109
|
+
api_key,
|
|
110
|
+
*,
|
|
111
|
+
base_url="https://botpage.xyz/api/v1",
|
|
112
|
+
cache_ttl_seconds=5,
|
|
113
|
+
max_requests_per_minute=100,
|
|
114
|
+
auto_wait_on_rate_limit=False,
|
|
115
|
+
session=None,
|
|
116
|
+
)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
| Option | Default | Description |
|
|
120
|
+
| --- | --- | --- |
|
|
121
|
+
| `api_key` | (required) | Your developer API key from the BotPage dashboard. An empty key raises `ValueError`. |
|
|
122
|
+
| `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. |
|
|
123
|
+
| `cache_ttl_seconds` | `5` | How long reads are cached, per server. `0` turns the cache off. Negative values count as `0`. |
|
|
124
|
+
| `max_requests_per_minute` | `100` | The local rate limit. Values below `1` count as `1`. |
|
|
125
|
+
| `auto_wait_on_rate_limit` | `False` | When `True`, the client sleeps until it may send again instead of raising `BotpageRateLimitError`. |
|
|
126
|
+
| `session` | `None` | An `aiohttp.ClientSession` to use instead of one the client creates. The client never closes it. |
|
|
127
|
+
|
|
128
|
+
Creating the client doesn't open a connection, so you can create it at module level before the event loop starts.
|
|
129
|
+
|
|
130
|
+
### `await get_guild_data(guild_id, *, force=False) -> dict`
|
|
131
|
+
|
|
132
|
+
Returns all of a server's dashboard values as a dict.
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
config = await botpage.get_guild_data("123456789012345678")
|
|
136
|
+
# {"prefix": "!", "welcomeEnabled": True, "logsChannel": "987654321098765432"}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`force=True` skips the cache and fetches the latest values.
|
|
140
|
+
|
|
141
|
+
### `await get_guild_field(guild_id, field, *, force=False) -> Any`
|
|
142
|
+
|
|
143
|
+
Returns one value, or `None` if it isn't set. It uses the same cache as `get_guild_data`.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
prefix = await botpage.get_guild_field("123456789012345678", "prefix")
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### `await update_guild_data(guild_id, updates) -> dict`
|
|
150
|
+
|
|
151
|
+
Updates several fields in one request and returns all of the server's values after the update.
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
updated = await botpage.update_guild_data(
|
|
155
|
+
"123456789012345678",
|
|
156
|
+
{"prefix": "?", "welcomeEnabled": False},
|
|
157
|
+
)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### `await update_guild_field(guild_id, field, value) -> dict`
|
|
161
|
+
|
|
162
|
+
Updates one field and returns all of the server's values after the update.
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
await botpage.update_guild_field("123456789012345678", "logsChannel", "987654321098765432")
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### `clear_cache(guild_id=None) -> None`
|
|
169
|
+
|
|
170
|
+
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.
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
botpage.clear_cache("123456789012345678") # one server
|
|
174
|
+
botpage.clear_cache() # every server
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### `await close() -> None`
|
|
178
|
+
|
|
179
|
+
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.
|
|
180
|
+
|
|
181
|
+
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.
|
|
182
|
+
|
|
183
|
+
## Errors
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
from botpage import BotpageError, BotpageRateLimitError
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
await botpage.update_guild_field(guild_id, "prefix", "?")
|
|
190
|
+
except BotpageRateLimitError as err:
|
|
191
|
+
print(f"Rate limited, retry in {err.retry_after:.1f}s")
|
|
192
|
+
except BotpageError as err:
|
|
193
|
+
print(f"BotPage request failed ({err.status}): {err}")
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
- **`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.
|
|
197
|
+
- **`BotpageRateLimitError`** is a subclass of `BotpageError` with `status` set to `429`. `retry_after` is how long to wait **in seconds** (a float).
|
|
198
|
+
|
|
199
|
+
## Caching
|
|
200
|
+
|
|
201
|
+
- Reads are cached in memory per server for `cache_ttl_seconds` (5 seconds by default). A read within that time makes no HTTP request.
|
|
202
|
+
- After an update, the cache holds the values the API returned, so your next read sees what you just wrote.
|
|
203
|
+
- Concurrent reads for the same server share one HTTP request, so a burst of events doesn't send a burst of identical calls.
|
|
204
|
+
- The cache holds at most 1000 servers. When it's full, expired entries are dropped first, then the oldest one.
|
|
205
|
+
- Use `force=True` to skip the cache for one read, `clear_cache()` to empty it, or `cache_ttl_seconds=0` to turn it off.
|
|
206
|
+
|
|
207
|
+
## Rate limiting
|
|
208
|
+
|
|
209
|
+
The client limits itself so it stops you before the API rejects you:
|
|
210
|
+
|
|
211
|
+
- At most `max_requests_per_minute` requests (100 by default) in any 60-second window. Cached reads don't count.
|
|
212
|
+
- When the API answers with a 429, the client respects its `Retry-After` header (10 seconds if missing) and sends nothing until then.
|
|
213
|
+
- When the API reports no remaining quota (`x-ratelimit-remaining: 0`), the client holds back for 5 seconds.
|
|
214
|
+
|
|
215
|
+
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.
|
|
216
|
+
|
|
217
|
+
## Closing the client
|
|
218
|
+
|
|
219
|
+
Three ways to manage the HTTP session:
|
|
220
|
+
|
|
221
|
+
```python
|
|
222
|
+
# 1. Long-running bot: create once, close on shutdown.
|
|
223
|
+
botpage = BotpageClient(api_key)
|
|
224
|
+
...
|
|
225
|
+
await botpage.close()
|
|
226
|
+
|
|
227
|
+
# 2. Script: `async with` closes the session on exit.
|
|
228
|
+
async with BotpageClient(api_key) as botpage:
|
|
229
|
+
config = await botpage.get_guild_data(guild_id)
|
|
230
|
+
|
|
231
|
+
# 3. Your own aiohttp session: the client uses it and never closes it.
|
|
232
|
+
async with aiohttp.ClientSession() as session:
|
|
233
|
+
botpage = BotpageClient(api_key, session=session)
|
|
234
|
+
config = await botpage.get_guild_data(guild_id)
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
The client reuses one session for all its requests, so connections are pooled.
|
|
238
|
+
|
|
239
|
+
## Type hints
|
|
240
|
+
|
|
241
|
+
The package ships type hints (`py.typed`), so editors autocomplete it and type checkers check your calls.
|
|
242
|
+
|
|
243
|
+
## Releasing
|
|
244
|
+
|
|
245
|
+
For maintainers. Publishing is done by hand.
|
|
246
|
+
|
|
247
|
+
1. Bump `version` in `pyproject.toml`.
|
|
248
|
+
2. Run the tests: `pip install -e ".[dev]"`, then `pytest`.
|
|
249
|
+
3. Build the wheel and sdist from this folder:
|
|
250
|
+
|
|
251
|
+
```bash
|
|
252
|
+
pip install --upgrade build twine
|
|
253
|
+
rm -rf dist # PowerShell: Remove-Item -Recurse -Force dist
|
|
254
|
+
python -m build
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
4. Upload with a PyPI API token (create one at https://pypi.org/manage/account/token/). Twine reads the token from the environment:
|
|
258
|
+
|
|
259
|
+
```bash
|
|
260
|
+
TWINE_USERNAME=__token__ TWINE_PASSWORD=pypi-... twine upload dist/*
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## License
|
|
264
|
+
|
|
265
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
botpage/__init__.py,sha256=-GdM3ze0Z0OgAzi0Q3Yd5OeBtZz7-v80Y98ZDeEXP6Y,212
|
|
2
|
+
botpage/_client.py,sha256=Mmq_y1C18zv8Y_v6GaFozL6C47GJY-0iGiEqk7bNs6Y,11995
|
|
3
|
+
botpage/_clock.py,sha256=pfG7JmaX38T1_k_Jnn740qlmcNmNWuVfODJkN3iwP98,155
|
|
4
|
+
botpage/_errors.py,sha256=SVib7jtxixVF75heWNy90D7aH2z626KHlsDeeGgXo5A,591
|
|
5
|
+
botpage/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
botpage-1.0.0.dist-info/METADATA,sha256=jMwiC9QEGN9jIzEgxHUXo1gSOE03PAPItzOvpx7QMFg,9634
|
|
7
|
+
botpage-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
botpage-1.0.0.dist-info/licenses/LICENSE,sha256=8yn2aFmM6Lt1SgZFTAq-mbxApGzmCozXu8d9hPC6ANA,1064
|
|
9
|
+
botpage-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BotPage
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|