disband-bot 0.1.1__tar.gz

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.
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: disband-bot
3
+ Version: 0.1.1
4
+ Summary: Official Python client for Disband bots. Self-hosted, token-authenticated, zero dependencies.
5
+ License: MIT
6
+ Keywords: disband,bot,chat,messaging
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # disband-bot
11
+
12
+ The official Python client for [Disband](https://www.disband.dev) bots.
13
+
14
+ Bots are self-hosted: you run the code yourself, a server owner invites the bot,
15
+ and the bot connects with its token. Disband never hosts or executes your bot.
16
+ This client uses only the Python standard library (threading + urllib).
17
+
18
+ ## Setup
19
+
20
+ ```bash
21
+ pip install disband-bot
22
+ ```
23
+
24
+ or, from this monorepo:
25
+
26
+ ```bash
27
+ pip install ./packages/disband-bot-python
28
+ ```
29
+
30
+ Create a bot first:
31
+
32
+ 1. Open **Settings → Bots** in Disband and click **New bot**.
33
+ 2. Pick the scopes it needs and copy the token it gives you — it's shown once.
34
+ 3. In **Settings → Bots**, generate an invite link for the server you want to
35
+ join and send it to the server owner to approve.
36
+
37
+ ## Usage
38
+
39
+ ```python
40
+ from disband_bot import Client
41
+
42
+ client = Client(token=DISBAND_BOT_TOKEN)
43
+
44
+
45
+ @client.on("ready")
46
+ def on_ready(me):
47
+ print(f"Logged in as {me['name']} ({', '.join(me['scopes'])})")
48
+
49
+
50
+ @client.on("messageCreate")
51
+ def on_message(message):
52
+ if message.author_is_bot:
53
+ return
54
+ if message.content == "!ping":
55
+ message.reply("pong")
56
+
57
+
58
+ client.run() # connects and blocks forever
59
+ ```
60
+
61
+ ## API
62
+
63
+ ### `Client(token, base_url="https://www.disband.dev", gateway_timeout=20)`
64
+
65
+ ### Events
66
+
67
+ | Event | Args | Description |
68
+ |---|---|---|
69
+ | `ready` | `user` | Fired after connecting. `user["id"]` is the bot id. |
70
+ | `messageCreate` | `message` | A new message in a server the bot can see. |
71
+ | `messageUpdate` | `message` | A message was edited. |
72
+ | `messageDelete` | `message` | A message was deleted. |
73
+ | `error` | `error` | Gateway errors (the loop retries automatically). |
74
+
75
+ `Message` exposes `id`, `channel_id`, `server_id`, `author`, `content`,
76
+ `reply_to_id`, `mentions`, `attachment`, `created_at`, `display_id`, and
77
+ `message.reply(content)`. `message.author_is_bot` tells you whether the sender
78
+ was a bot.
79
+
80
+ ### Methods
81
+
82
+ ```python
83
+ await client.send_message(channel_id, "Deploy finished") # async handler? just call it
84
+ message.reply("pong") # reply to a received message
85
+ msgs = client.list_messages(channel_id, limit=25)
86
+ channels = client.list_channels(server_id)
87
+ members = client.list_members(server_id)
88
+ channel_id = client.create_channel(server_id, "deploys")
89
+ client.rename_channel(channel_id, "deploys-2")
90
+ client.delete_channel(channel_id)
91
+ client.leave_server(server_id)
92
+ invite = client.create_invite(server_id, ["messages.read", "messages.write"])
93
+ ```
94
+
95
+ ## Scopes
96
+
97
+ A bot's reach is the intersection of the scopes on its bot account and the
98
+ scopes an owner approved for a specific server:
99
+
100
+ - `messages.read` — receive message events and read messages/channels.
101
+ - `messages.write` — post and reply.
102
+ - `members.read` — read the member list.
103
+ - `channels.manage` — create, rename, and delete channels (also needs the
104
+ `manage_channels` role in that server).
105
+
106
+ ## License
107
+
108
+ MIT
@@ -0,0 +1,99 @@
1
+ # disband-bot
2
+
3
+ The official Python client for [Disband](https://www.disband.dev) bots.
4
+
5
+ Bots are self-hosted: you run the code yourself, a server owner invites the bot,
6
+ and the bot connects with its token. Disband never hosts or executes your bot.
7
+ This client uses only the Python standard library (threading + urllib).
8
+
9
+ ## Setup
10
+
11
+ ```bash
12
+ pip install disband-bot
13
+ ```
14
+
15
+ or, from this monorepo:
16
+
17
+ ```bash
18
+ pip install ./packages/disband-bot-python
19
+ ```
20
+
21
+ Create a bot first:
22
+
23
+ 1. Open **Settings → Bots** in Disband and click **New bot**.
24
+ 2. Pick the scopes it needs and copy the token it gives you — it's shown once.
25
+ 3. In **Settings → Bots**, generate an invite link for the server you want to
26
+ join and send it to the server owner to approve.
27
+
28
+ ## Usage
29
+
30
+ ```python
31
+ from disband_bot import Client
32
+
33
+ client = Client(token=DISBAND_BOT_TOKEN)
34
+
35
+
36
+ @client.on("ready")
37
+ def on_ready(me):
38
+ print(f"Logged in as {me['name']} ({', '.join(me['scopes'])})")
39
+
40
+
41
+ @client.on("messageCreate")
42
+ def on_message(message):
43
+ if message.author_is_bot:
44
+ return
45
+ if message.content == "!ping":
46
+ message.reply("pong")
47
+
48
+
49
+ client.run() # connects and blocks forever
50
+ ```
51
+
52
+ ## API
53
+
54
+ ### `Client(token, base_url="https://www.disband.dev", gateway_timeout=20)`
55
+
56
+ ### Events
57
+
58
+ | Event | Args | Description |
59
+ |---|---|---|
60
+ | `ready` | `user` | Fired after connecting. `user["id"]` is the bot id. |
61
+ | `messageCreate` | `message` | A new message in a server the bot can see. |
62
+ | `messageUpdate` | `message` | A message was edited. |
63
+ | `messageDelete` | `message` | A message was deleted. |
64
+ | `error` | `error` | Gateway errors (the loop retries automatically). |
65
+
66
+ `Message` exposes `id`, `channel_id`, `server_id`, `author`, `content`,
67
+ `reply_to_id`, `mentions`, `attachment`, `created_at`, `display_id`, and
68
+ `message.reply(content)`. `message.author_is_bot` tells you whether the sender
69
+ was a bot.
70
+
71
+ ### Methods
72
+
73
+ ```python
74
+ await client.send_message(channel_id, "Deploy finished") # async handler? just call it
75
+ message.reply("pong") # reply to a received message
76
+ msgs = client.list_messages(channel_id, limit=25)
77
+ channels = client.list_channels(server_id)
78
+ members = client.list_members(server_id)
79
+ channel_id = client.create_channel(server_id, "deploys")
80
+ client.rename_channel(channel_id, "deploys-2")
81
+ client.delete_channel(channel_id)
82
+ client.leave_server(server_id)
83
+ invite = client.create_invite(server_id, ["messages.read", "messages.write"])
84
+ ```
85
+
86
+ ## Scopes
87
+
88
+ A bot's reach is the intersection of the scopes on its bot account and the
89
+ scopes an owner approved for a specific server:
90
+
91
+ - `messages.read` — receive message events and read messages/channels.
92
+ - `messages.write` — post and reply.
93
+ - `members.read` — read the member list.
94
+ - `channels.manage` — create, rename, and delete channels (also needs the
95
+ `manage_channels` role in that server).
96
+
97
+ ## License
98
+
99
+ MIT
@@ -0,0 +1,23 @@
1
+ """disband-bot: the official Python client for Disband bots."""
2
+
3
+ from .client import Client
4
+ from .errors import (
5
+ AuthError,
6
+ DisbandError,
7
+ HttpError,
8
+ PermissionError,
9
+ RateLimitError,
10
+ )
11
+ from .message import Message
12
+
13
+ __all__ = [
14
+ "Client",
15
+ "Message",
16
+ "DisbandError",
17
+ "HttpError",
18
+ "AuthError",
19
+ "PermissionError",
20
+ "RateLimitError",
21
+ ]
22
+
23
+ __version__ = "0.1.0"
@@ -0,0 +1,237 @@
1
+ """The Disband bot client."""
2
+
3
+ import asyncio
4
+ import inspect
5
+ import threading
6
+ import time
7
+ import traceback
8
+ from urllib.parse import quote, urlencode, urlsplit
9
+
10
+ from .errors import AuthError
11
+ from .message import Message
12
+ from .rest import REST
13
+
14
+ EVENT_NAMES = frozenset(
15
+ {"ready", "messageCreate", "messageUpdate", "messageDelete", "error"}
16
+ )
17
+
18
+
19
+ def _path_segment(value):
20
+ return quote(str(value), safe="")
21
+
22
+
23
+ async def _await_handler(result):
24
+ await result
25
+
26
+
27
+ class Client:
28
+ """A Disband bot.
29
+
30
+ Bots are self-hosted: run this client wherever you like, and it talks to
31
+ the Disband API with a bot token created in Settings -> Bots.
32
+ """
33
+
34
+ def __init__(self, token, base_url="https://www.disband.dev", gateway_timeout=20,
35
+ allow_insecure_localhost=False):
36
+ if not token:
37
+ raise ValueError("A bot token is required (Client(token=...))")
38
+ parsed = urlsplit(base_url)
39
+ loopback = parsed.hostname in {"localhost", "127.0.0.1", "::1"}
40
+ if parsed.username or parsed.password or parsed.fragment:
41
+ raise ValueError("Bot API URLs cannot contain credentials or fragments")
42
+ if parsed.scheme != "https" and not (parsed.scheme == "http" and allow_insecure_localhost and loopback):
43
+ raise ValueError("Bot API URLs must use HTTPS (or explicitly enabled loopback HTTP)")
44
+ self.token = token
45
+ self.base_url = base_url.rstrip("/")
46
+ self.gateway_timeout = gateway_timeout
47
+ self._rest = REST(self)
48
+ self._listeners = {name: [] for name in EVENT_NAMES}
49
+ self._lock = threading.Lock()
50
+ self._stopped = threading.Event()
51
+ self._thread = None
52
+ self.user = None
53
+ self.connected = False
54
+
55
+ # ------------------------------------------------------------ events
56
+
57
+ def on(self, event, handler=None):
58
+ """Register a handler, usable as a decorator or directly.
59
+
60
+ ``client.on("messageCreate", handler)`` or::
61
+
62
+ @client.on("messageCreate")
63
+ async def handle(message):
64
+ ...
65
+ """
66
+
67
+ def register(fn):
68
+ if event not in EVENT_NAMES:
69
+ raise ValueError("Unknown event %r" % event)
70
+ with self._lock:
71
+ self._listeners[event].append(fn)
72
+ return fn
73
+
74
+ if handler is not None:
75
+ return register(handler)
76
+ return register
77
+
78
+ def once(self, event, handler=None):
79
+ def register(fn):
80
+ def wrapped(*args):
81
+ with self._lock:
82
+ self._listeners[event].remove(wrapped)
83
+ return fn(*args)
84
+
85
+ self.on(event, wrapped)
86
+ return fn
87
+
88
+ if handler is not None:
89
+ return register(handler)
90
+ return register
91
+
92
+ def _report_handler_error(self, event, error):
93
+ with self._lock:
94
+ has_error_handler = bool(self._listeners["error"])
95
+ if event == "error" or not has_error_handler:
96
+ traceback.print_exception(type(error), error, error.__traceback__)
97
+ else:
98
+ self._emit("error", error)
99
+
100
+ def _emit(self, event, *args):
101
+ with self._lock:
102
+ handlers = list(self._listeners.get(event, ()))
103
+ for handler in handlers:
104
+ try:
105
+ result = handler(*args)
106
+ if inspect.isawaitable(result):
107
+ try:
108
+ loop = asyncio.get_running_loop()
109
+ except RuntimeError:
110
+ asyncio.run(_await_handler(result))
111
+ else:
112
+ task = loop.create_task(_await_handler(result))
113
+ task.add_done_callback(lambda done, name=event: self._on_handler_done(name, done))
114
+ except Exception as error:
115
+ self._report_handler_error(event, error)
116
+
117
+ def _on_handler_done(self, event, task):
118
+ if task.cancelled():
119
+ return
120
+ error = task.exception()
121
+ if error is not None:
122
+ self._report_handler_error(event, error)
123
+
124
+ # ------------------------------------------------------------ lifecycle
125
+
126
+ def connect(self):
127
+ """Resolves the bot identity, fires ``ready``, starts the gateway.
128
+
129
+ Spawns a daemon thread for the gateway loop and returns immediately.
130
+ To block forever, call :meth:`run` instead.
131
+ """
132
+ me = self._rest.get("/api/bot/me")
133
+ self.user = {
134
+ "id": me["bot"]["id"],
135
+ "user_id": me["bot"].get("user_id"),
136
+ "name": me["bot"].get("name"),
137
+ "username": me["bot"].get("username"),
138
+ "avatar_url": me["bot"].get("avatar_url"),
139
+ "scopes": me["bot"].get("scopes", []),
140
+ }
141
+ self.connected = True
142
+ self._emit("ready", self.user)
143
+ if not self._thread or not self._thread.is_alive():
144
+ self._stopped.clear()
145
+ self._thread = threading.Thread(
146
+ target=self._gateway_loop, daemon=True
147
+ )
148
+ self._thread.start()
149
+ return self
150
+
151
+ def run(self):
152
+ """Connects and blocks until the client is stopped."""
153
+ self.connect()
154
+ while not self._stopped.is_set():
155
+ time.sleep(0.1)
156
+
157
+ def close(self):
158
+ """Stops the gateway loop."""
159
+ self._stopped.set()
160
+ self.connected = False
161
+
162
+ def _gateway_loop(self):
163
+ while not self._stopped.is_set():
164
+ try:
165
+ payload = self._rest.get(
166
+ "/api/v1/gateway?timeout=%d" % self.gateway_timeout
167
+ )
168
+ for event in payload.get("events", []):
169
+ if self._stopped.is_set():
170
+ break
171
+ name = event["type"]
172
+ if name in ("messageCreate", "messageUpdate"):
173
+ self._emit(name, Message(event["payload"].get("message", event["payload"]), self))
174
+ else:
175
+ self._emit(name, event["payload"])
176
+ except AuthError:
177
+ self._emit(
178
+ "error",
179
+ RuntimeError(
180
+ "Invalid bot token - check your DISBAND_BOT_TOKEN."
181
+ ),
182
+ )
183
+ break
184
+ except Exception as exc: # noqa: BLE001 - keep the loop alive
185
+ self._emit("error", exc)
186
+ self._stopped.wait(3)
187
+
188
+ # ------------------------------------------------------------ REST helpers
189
+
190
+ def send_message(self, channel_id, content, reply_to_id=None):
191
+ data = self._rest.post(
192
+ "/api/v1/channels/%s/messages" % _path_segment(channel_id),
193
+ {"content": content, "reply_to_id": reply_to_id},
194
+ )
195
+ return Message(data["message"], self)
196
+
197
+ def list_messages(self, channel_id, limit=None, before=None):
198
+ params = []
199
+ if limit is not None:
200
+ params.append(("limit", str(limit)))
201
+ if before is not None:
202
+ params.append(("before", str(before)))
203
+ qs = ("?" + urlencode(params)) if params else ""
204
+ data = self._rest.get("/api/v1/channels/%s/messages%s" % (_path_segment(channel_id), qs))
205
+ return [Message(m, self) for m in data.get("messages", [])]
206
+
207
+ def list_channels(self, server_id):
208
+ data = self._rest.get("/api/v1/servers/%s/channels" % _path_segment(server_id))
209
+ return data.get("channels", [])
210
+
211
+ def list_members(self, server_id):
212
+ data = self._rest.get("/api/v1/servers/%s/members" % _path_segment(server_id))
213
+ return data.get("members", [])
214
+
215
+ def create_channel(self, server_id, name, type="text", category_id=None):
216
+ data = self._rest.post(
217
+ "/api/v1/servers/%s/channels" % _path_segment(server_id),
218
+ {"name": name, "type": type, "category_id": category_id},
219
+ )
220
+ return data.get("channel_id")
221
+
222
+ def rename_channel(self, channel_id, name):
223
+ return self._rest.patch("/api/v1/channels/%s" % _path_segment(channel_id), {"name": name})
224
+
225
+ def delete_channel(self, channel_id):
226
+ return self._rest.delete("/api/v1/channels/%s" % _path_segment(channel_id))
227
+
228
+ def leave_server(self, server_id):
229
+ return self._rest.post("/api/v1/servers/%s/leave" % _path_segment(server_id))
230
+
231
+ def create_invite(self, server_id, scopes):
232
+ if not self.user:
233
+ raise RuntimeError("Client is not connected - call connect() first.")
234
+ return self._rest.post(
235
+ "/api/v1/bots/%s/invites" % _path_segment(self.user["id"]),
236
+ {"server_id": server_id, "scopes": scopes},
237
+ )
@@ -0,0 +1,30 @@
1
+ """Errors raised by the Disband bot client."""
2
+
3
+
4
+ class DisbandError(Exception):
5
+ """Base class for all errors from the Disband API."""
6
+
7
+
8
+ class HttpError(DisbandError):
9
+ """A non-2xx response from the API."""
10
+
11
+ def __init__(self, status, message, body=None):
12
+ super().__init__(message)
13
+ self.status = status
14
+ self.body = body
15
+
16
+
17
+ class AuthError(HttpError):
18
+ """The bot token was missing, unknown, or revoked."""
19
+
20
+
21
+ class PermissionError(HttpError):
22
+ """The bot lacks the required scope or membership for this action."""
23
+
24
+
25
+ class RateLimitError(HttpError):
26
+ """Too many requests — respect ``retry_after_seconds``."""
27
+
28
+ def __init__(self, status, message, body=None, retry_after_seconds=0):
29
+ super().__init__(status, message, body)
30
+ self.retry_after_seconds = retry_after_seconds
@@ -0,0 +1,40 @@
1
+ """Message model for Disband bots."""
2
+
3
+
4
+ class Message:
5
+ """A message received from, or sent to, a Disband channel."""
6
+
7
+ def __init__(self, data, client):
8
+ self.client = client
9
+ self.id = data.get("id")
10
+ self.channel_id = data.get("channel_id")
11
+ self.server_id = data.get("server_id")
12
+ self.author = data.get("author") or None
13
+ self.content = data.get("content") or ""
14
+ self.reply_to_id = data.get("reply_to_id")
15
+ self.mentions = data.get("mentions") or []
16
+ attachment_url = data.get("attachment_url")
17
+ self.attachment = (
18
+ {"url": attachment_url, "type": data.get("attachment_type")}
19
+ if attachment_url
20
+ else None
21
+ )
22
+ self.created_at = data.get("created_at")
23
+ self.edited_at = data.get("edited_at")
24
+ self.display_id = data.get("display_id")
25
+
26
+ @property
27
+ def author_is_bot(self):
28
+ author = self.author or {}
29
+ return bool(author.get("is_bot"))
30
+
31
+ def reply(self, content):
32
+ """Replies to this message in the same channel."""
33
+ return self.client.send_message(self.channel_id, content, reply_to_id=self.id)
34
+
35
+ def __repr__(self):
36
+ return "<Message id=%s channel=%s content=%r>" % (
37
+ self.id,
38
+ self.channel_id,
39
+ self.content[:40],
40
+ )
@@ -0,0 +1,78 @@
1
+ """Minimal HTTP layer for the Disband bot API (stdlib only)."""
2
+
3
+ import json
4
+ import urllib.error
5
+ import urllib.request
6
+
7
+ from .errors import AuthError, HttpError, PermissionError, RateLimitError
8
+
9
+
10
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
11
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
12
+ return None
13
+
14
+
15
+ class REST:
16
+ def __init__(self, client):
17
+ self.client = client
18
+ self.base_url = client.base_url
19
+ self.opener = urllib.request.build_opener(_NoRedirect)
20
+
21
+ def _headers(self):
22
+ return {
23
+ "Authorization": "Bot " + self.client.token,
24
+ "Content-Type": "application/json",
25
+ "User-Agent": "disband-bot (+https://www.disband.dev)",
26
+ }
27
+
28
+ def _parse(self, response, raw):
29
+ try:
30
+ body = json.loads(raw.decode("utf-8")) if raw else None
31
+ except (ValueError, UnicodeDecodeError):
32
+ body = None
33
+ if 200 <= response.status < 300:
34
+ return body
35
+ message = (body or {}).get("error") if isinstance(body, dict) else None
36
+ message = message or "Request failed with status %d" % response.status
37
+ if response.status == 401:
38
+ raise AuthError(response.status, message, body)
39
+ if response.status == 429:
40
+ retry = 0
41
+ try:
42
+ retry = float(response.headers.get("Retry-After") or 0)
43
+ except (TypeError, ValueError):
44
+ retry = 0
45
+ raise RateLimitError(response.status, message, body, retry)
46
+ if response.status == 403:
47
+ raise PermissionError(response.status, message, body)
48
+ raise HttpError(response.status, message, body)
49
+
50
+ def request(self, method, path, body=None):
51
+ data = None
52
+ if body is not None:
53
+ data = json.dumps(body).encode("utf-8")
54
+ req = urllib.request.Request(
55
+ self.base_url + path,
56
+ data=data,
57
+ headers=self._headers(),
58
+ method=method,
59
+ )
60
+ try:
61
+ with self.opener.open(req, timeout=max(float(self.client.gateway_timeout) + 10.0, 30.0)) as resp:
62
+ return self._parse(resp, resp.read())
63
+ except urllib.error.HTTPError as e:
64
+ return self._parse(e, e.read())
65
+ except urllib.error.URLError as e:
66
+ raise HttpError(0, "Network error: %s" % e.reason)
67
+
68
+ def get(self, path):
69
+ return self.request("GET", path)
70
+
71
+ def post(self, path, body=None):
72
+ return self.request("POST", path, body)
73
+
74
+ def patch(self, path, body=None):
75
+ return self.request("PATCH", path, body)
76
+
77
+ def delete(self, path):
78
+ return self.request("DELETE", path)
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: disband-bot
3
+ Version: 0.1.1
4
+ Summary: Official Python client for Disband bots. Self-hosted, token-authenticated, zero dependencies.
5
+ License: MIT
6
+ Keywords: disband,bot,chat,messaging
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # disband-bot
11
+
12
+ The official Python client for [Disband](https://www.disband.dev) bots.
13
+
14
+ Bots are self-hosted: you run the code yourself, a server owner invites the bot,
15
+ and the bot connects with its token. Disband never hosts or executes your bot.
16
+ This client uses only the Python standard library (threading + urllib).
17
+
18
+ ## Setup
19
+
20
+ ```bash
21
+ pip install disband-bot
22
+ ```
23
+
24
+ or, from this monorepo:
25
+
26
+ ```bash
27
+ pip install ./packages/disband-bot-python
28
+ ```
29
+
30
+ Create a bot first:
31
+
32
+ 1. Open **Settings → Bots** in Disband and click **New bot**.
33
+ 2. Pick the scopes it needs and copy the token it gives you — it's shown once.
34
+ 3. In **Settings → Bots**, generate an invite link for the server you want to
35
+ join and send it to the server owner to approve.
36
+
37
+ ## Usage
38
+
39
+ ```python
40
+ from disband_bot import Client
41
+
42
+ client = Client(token=DISBAND_BOT_TOKEN)
43
+
44
+
45
+ @client.on("ready")
46
+ def on_ready(me):
47
+ print(f"Logged in as {me['name']} ({', '.join(me['scopes'])})")
48
+
49
+
50
+ @client.on("messageCreate")
51
+ def on_message(message):
52
+ if message.author_is_bot:
53
+ return
54
+ if message.content == "!ping":
55
+ message.reply("pong")
56
+
57
+
58
+ client.run() # connects and blocks forever
59
+ ```
60
+
61
+ ## API
62
+
63
+ ### `Client(token, base_url="https://www.disband.dev", gateway_timeout=20)`
64
+
65
+ ### Events
66
+
67
+ | Event | Args | Description |
68
+ |---|---|---|
69
+ | `ready` | `user` | Fired after connecting. `user["id"]` is the bot id. |
70
+ | `messageCreate` | `message` | A new message in a server the bot can see. |
71
+ | `messageUpdate` | `message` | A message was edited. |
72
+ | `messageDelete` | `message` | A message was deleted. |
73
+ | `error` | `error` | Gateway errors (the loop retries automatically). |
74
+
75
+ `Message` exposes `id`, `channel_id`, `server_id`, `author`, `content`,
76
+ `reply_to_id`, `mentions`, `attachment`, `created_at`, `display_id`, and
77
+ `message.reply(content)`. `message.author_is_bot` tells you whether the sender
78
+ was a bot.
79
+
80
+ ### Methods
81
+
82
+ ```python
83
+ await client.send_message(channel_id, "Deploy finished") # async handler? just call it
84
+ message.reply("pong") # reply to a received message
85
+ msgs = client.list_messages(channel_id, limit=25)
86
+ channels = client.list_channels(server_id)
87
+ members = client.list_members(server_id)
88
+ channel_id = client.create_channel(server_id, "deploys")
89
+ client.rename_channel(channel_id, "deploys-2")
90
+ client.delete_channel(channel_id)
91
+ client.leave_server(server_id)
92
+ invite = client.create_invite(server_id, ["messages.read", "messages.write"])
93
+ ```
94
+
95
+ ## Scopes
96
+
97
+ A bot's reach is the intersection of the scopes on its bot account and the
98
+ scopes an owner approved for a specific server:
99
+
100
+ - `messages.read` — receive message events and read messages/channels.
101
+ - `messages.write` — post and reply.
102
+ - `members.read` — read the member list.
103
+ - `channels.manage` — create, rename, and delete channels (also needs the
104
+ `manage_channels` role in that server).
105
+
106
+ ## License
107
+
108
+ MIT
@@ -0,0 +1,12 @@
1
+ README.md
2
+ pyproject.toml
3
+ disband_bot/__init__.py
4
+ disband_bot/client.py
5
+ disband_bot/errors.py
6
+ disband_bot/message.py
7
+ disband_bot/rest.py
8
+ disband_bot.egg-info/PKG-INFO
9
+ disband_bot.egg-info/SOURCES.txt
10
+ disband_bot.egg-info/dependency_links.txt
11
+ disband_bot.egg-info/top_level.txt
12
+ tests/test_transport.py
@@ -0,0 +1 @@
1
+ disband_bot
@@ -0,0 +1,15 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "disband-bot"
7
+ version = "0.1.1"
8
+ description = "Official Python client for Disband bots. Self-hosted, token-authenticated, zero dependencies."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ keywords = ["disband", "bot", "chat", "messaging"]
13
+
14
+ [tool.setuptools]
15
+ packages = ["disband_bot"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,85 @@
1
+ import asyncio
2
+ import io
3
+ import unittest
4
+
5
+ from disband_bot.client import Client
6
+ from disband_bot.errors import HttpError
7
+ from disband_bot.rest import _NoRedirect
8
+
9
+
10
+ class _Response:
11
+ status = 200
12
+
13
+ def __enter__(self):
14
+ return self
15
+
16
+ def __exit__(self, *_args):
17
+ return False
18
+
19
+ def read(self):
20
+ return b'{"messages": []}'
21
+
22
+
23
+ class _Opener:
24
+ def __init__(self):
25
+ self.request = None
26
+ self.timeout = None
27
+
28
+ def open(self, request, timeout):
29
+ self.request = request
30
+ self.timeout = timeout
31
+ return _Response()
32
+
33
+
34
+ class TransportTests(unittest.TestCase):
35
+ def test_api_base_requires_https_except_explicit_loopback(self):
36
+ for url in ("http://example.com", "http://localhost:8080", "file:///tmp/api", "https://user:pass@example.com", "https://example.com/#fragment"):
37
+ with self.subTest(url=url), self.assertRaises(ValueError):
38
+ Client("token", base_url=url)
39
+ Client("token", base_url="http://127.0.0.1:8080", allow_insecure_localhost=True)
40
+
41
+ def test_paths_and_query_values_are_encoded_and_requests_have_timeout(self):
42
+ client = Client("token", gateway_timeout=45)
43
+ opener = _Opener()
44
+ client._rest.opener = opener
45
+ client.list_messages("channel/../other", before="id&limit=999")
46
+ self.assertIn("/channels/channel%2F..%2Fother/messages", opener.request.full_url)
47
+ self.assertIn("before=id%26limit%3D999", opener.request.full_url)
48
+ self.assertEqual(opener.timeout, 55.0)
49
+ self.assertEqual(opener.request.get_header("Authorization"), "Bot token")
50
+
51
+ def test_redirect_handler_refuses_auth_token_forwarding(self):
52
+ self.assertIsNone(_NoRedirect().redirect_request(None, io.BytesIO(), 302, "Found", {}, "https://other.example"))
53
+
54
+ def test_async_one_time_handler_runs_without_a_current_event_loop(self):
55
+ client = Client("token")
56
+ seen = []
57
+
58
+ @client.once("messageCreate")
59
+ async def receive(value):
60
+ seen.append(value)
61
+
62
+ client._emit("messageCreate", "first")
63
+ client._emit("messageCreate", "second")
64
+ self.assertEqual(seen, ["first"])
65
+
66
+ def test_async_handler_failure_reaches_error_listener_in_running_loop(self):
67
+ client = Client("token")
68
+ errors = []
69
+ client.on("error", lambda error: errors.append(str(error)))
70
+
71
+ @client.on("messageCreate")
72
+ async def fail(_value):
73
+ raise RuntimeError("handler failed")
74
+
75
+ async def emit_and_wait():
76
+ client._emit("messageCreate", "event")
77
+ await asyncio.sleep(0)
78
+ await asyncio.sleep(0)
79
+
80
+ asyncio.run(emit_and_wait())
81
+ self.assertEqual(errors, ["handler failed"])
82
+
83
+
84
+ if __name__ == "__main__":
85
+ unittest.main()