taverns.py 0.1.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.
- taverns/__init__.py +80 -0
- taverns/client.py +244 -0
- taverns/commands.py +76 -0
- taverns/errors.py +36 -0
- taverns/gateway.py +161 -0
- taverns/intents.py +74 -0
- taverns/interaction.py +83 -0
- taverns/permissions.py +117 -0
- taverns/rest.py +181 -0
- taverns/types.py +193 -0
- taverns/webhook.py +75 -0
- taverns_py-0.1.0.dist-info/METADATA +145 -0
- taverns_py-0.1.0.dist-info/RECORD +16 -0
- taverns_py-0.1.0.dist-info/WHEEL +5 -0
- taverns_py-0.1.0.dist-info/licenses/LICENSE +191 -0
- taverns_py-0.1.0.dist-info/top_level.txt +1 -0
taverns/__init__.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""
|
|
2
|
+
taverns.py — Python SDK for building Tavern bots.
|
|
3
|
+
|
|
4
|
+
Quick start::
|
|
5
|
+
|
|
6
|
+
from taverns import Client, Intents
|
|
7
|
+
|
|
8
|
+
client = Client(intents=Intents.MESSAGES | Intents.INTERACTIONS)
|
|
9
|
+
|
|
10
|
+
@client.event
|
|
11
|
+
async def on_ready():
|
|
12
|
+
print(f"Logged in as {client.user.display_name}")
|
|
13
|
+
|
|
14
|
+
@client.event
|
|
15
|
+
async def on_interaction_create(interaction):
|
|
16
|
+
await interaction.reply("Pong!")
|
|
17
|
+
|
|
18
|
+
client.run("tavbot_xxx")
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from .client import Client
|
|
22
|
+
from .commands import command, option
|
|
23
|
+
from .errors import (
|
|
24
|
+
AuthenticationError,
|
|
25
|
+
GatewayError,
|
|
26
|
+
HTTPError,
|
|
27
|
+
InteractionError,
|
|
28
|
+
RateLimitError,
|
|
29
|
+
TavernError,
|
|
30
|
+
)
|
|
31
|
+
from .intents import Intents
|
|
32
|
+
from .interaction import Interaction
|
|
33
|
+
from .permissions import Permissions
|
|
34
|
+
from .rest import RESTClient
|
|
35
|
+
from .types import (
|
|
36
|
+
BotCommand,
|
|
37
|
+
BotSelf,
|
|
38
|
+
Channel,
|
|
39
|
+
CommandOption,
|
|
40
|
+
CommandOptionType,
|
|
41
|
+
Member,
|
|
42
|
+
Message,
|
|
43
|
+
Tavern,
|
|
44
|
+
User,
|
|
45
|
+
)
|
|
46
|
+
from .webhook import verify_webhook_signature
|
|
47
|
+
|
|
48
|
+
__version__ = "0.1.0"
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
# Core
|
|
52
|
+
"Client",
|
|
53
|
+
"RESTClient",
|
|
54
|
+
"Intents",
|
|
55
|
+
"Permissions",
|
|
56
|
+
# Types
|
|
57
|
+
"User",
|
|
58
|
+
"Tavern",
|
|
59
|
+
"Channel",
|
|
60
|
+
"Member",
|
|
61
|
+
"Message",
|
|
62
|
+
"BotCommand",
|
|
63
|
+
"BotSelf",
|
|
64
|
+
"CommandOption",
|
|
65
|
+
"CommandOptionType",
|
|
66
|
+
# Interactions
|
|
67
|
+
"Interaction",
|
|
68
|
+
# Commands
|
|
69
|
+
"command",
|
|
70
|
+
"option",
|
|
71
|
+
# Webhook
|
|
72
|
+
"verify_webhook_signature",
|
|
73
|
+
# Errors
|
|
74
|
+
"TavernError",
|
|
75
|
+
"AuthenticationError",
|
|
76
|
+
"HTTPError",
|
|
77
|
+
"RateLimitError",
|
|
78
|
+
"GatewayError",
|
|
79
|
+
"InteractionError",
|
|
80
|
+
]
|
taverns/client.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Main Client class for building Tavern bots.
|
|
2
|
+
|
|
3
|
+
Usage::
|
|
4
|
+
|
|
5
|
+
from taverns import Client, Intents
|
|
6
|
+
|
|
7
|
+
client = Client(intents=Intents.MESSAGES | Intents.INTERACTIONS)
|
|
8
|
+
|
|
9
|
+
@client.event
|
|
10
|
+
async def on_ready():
|
|
11
|
+
print(f"Logged in as {client.user.display_name}")
|
|
12
|
+
|
|
13
|
+
@client.event
|
|
14
|
+
async def on_message_create(message):
|
|
15
|
+
if message.content == "!ping":
|
|
16
|
+
await client.send_message(message.tavern_id, message.channel_id, content="Pong!")
|
|
17
|
+
|
|
18
|
+
client.run("tavbot_xxx")
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import logging
|
|
25
|
+
from typing import Any, Callable, Coroutine
|
|
26
|
+
|
|
27
|
+
from .gateway import Gateway
|
|
28
|
+
from .interaction import Interaction
|
|
29
|
+
from .rest import RESTClient
|
|
30
|
+
from .types import BotCommand, BotSelf, Channel, Member, Message, Tavern, User
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger("taverns")
|
|
33
|
+
|
|
34
|
+
EventCallback = Callable[..., Coroutine[Any, Any, None]]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Client:
|
|
38
|
+
"""The main interface for interacting with the Taverns platform.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
intents: Gateway intents bitfield (session-level). Use :class:`Intents` constants.
|
|
42
|
+
api_url: Override the REST API base URL.
|
|
43
|
+
ws_url: Override the WebSocket gateway URL.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
*,
|
|
49
|
+
intents: int | None = None,
|
|
50
|
+
api_url: str = "https://api.tav.gg/api/v1",
|
|
51
|
+
ws_url: str = "wss://ws.tav.gg",
|
|
52
|
+
):
|
|
53
|
+
self._intents = intents
|
|
54
|
+
self._api_url = api_url
|
|
55
|
+
self._ws_url = ws_url
|
|
56
|
+
self._token: str | None = None
|
|
57
|
+
self._rest: RESTClient | None = None
|
|
58
|
+
self._gateway: Gateway | None = None
|
|
59
|
+
self._bot_self: BotSelf | None = None
|
|
60
|
+
self._event_handlers: dict[str, list[EventCallback]] = {}
|
|
61
|
+
self._taverns: dict[str, Tavern] = {}
|
|
62
|
+
self._channels: dict[str, Channel] = {}
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def user(self) -> User:
|
|
66
|
+
"""The bot's own user identity. Available after login."""
|
|
67
|
+
if not self._bot_self:
|
|
68
|
+
raise RuntimeError("Client is not logged in")
|
|
69
|
+
return self._bot_self.user
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def taverns(self) -> dict[str, Tavern]:
|
|
73
|
+
"""Dict of tavern_id -> Tavern for all Taverns the bot is installed in."""
|
|
74
|
+
return self._taverns
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def rest(self) -> RESTClient:
|
|
78
|
+
"""The REST client for direct API calls."""
|
|
79
|
+
if not self._rest:
|
|
80
|
+
raise RuntimeError("Client is not logged in")
|
|
81
|
+
return self._rest
|
|
82
|
+
|
|
83
|
+
# ─── Event registration ──────────────────────────────
|
|
84
|
+
|
|
85
|
+
def event(self, func: EventCallback) -> EventCallback:
|
|
86
|
+
"""Decorator to register an event handler.
|
|
87
|
+
|
|
88
|
+
The function name determines the event: ``on_ready``, ``on_message_create``, etc.
|
|
89
|
+
|
|
90
|
+
Example::
|
|
91
|
+
|
|
92
|
+
@client.event
|
|
93
|
+
async def on_message_create(message):
|
|
94
|
+
print(message.content)
|
|
95
|
+
"""
|
|
96
|
+
name = func.__name__
|
|
97
|
+
if name.startswith("on_"):
|
|
98
|
+
name = name[3:] # strip "on_" prefix
|
|
99
|
+
self._event_handlers.setdefault(name, []).append(func)
|
|
100
|
+
return func
|
|
101
|
+
|
|
102
|
+
def on(self, event_name: str) -> Callable[[EventCallback], EventCallback]:
|
|
103
|
+
"""Decorator to register an event handler by name.
|
|
104
|
+
|
|
105
|
+
Example::
|
|
106
|
+
|
|
107
|
+
@client.on("message_create")
|
|
108
|
+
async def handle_msg(message):
|
|
109
|
+
print(message.content)
|
|
110
|
+
"""
|
|
111
|
+
def decorator(func: EventCallback) -> EventCallback:
|
|
112
|
+
self._event_handlers.setdefault(event_name, []).append(func)
|
|
113
|
+
return func
|
|
114
|
+
return decorator
|
|
115
|
+
|
|
116
|
+
# ─── Convenience methods ─────────────────────────────
|
|
117
|
+
|
|
118
|
+
async def send_message(
|
|
119
|
+
self, tavern_id: str, channel_id: str, *, content: str, reply_to_id: str | None = None,
|
|
120
|
+
) -> Message:
|
|
121
|
+
"""Send a message to a channel."""
|
|
122
|
+
return await self.rest.send_message(
|
|
123
|
+
tavern_id, channel_id, content=content, reply_to_id=reply_to_id,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
async def register_commands(self, commands: list[dict[str, Any]]) -> list[BotCommand]:
|
|
127
|
+
"""Register slash commands for this bot.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
commands: List of command dicts. Use :func:`taverns.commands.command` to build.
|
|
131
|
+
"""
|
|
132
|
+
return await self.rest.register_commands(commands)
|
|
133
|
+
|
|
134
|
+
# ─── Lifecycle ───────────────────────────────────────
|
|
135
|
+
|
|
136
|
+
async def login(self, token: str) -> None:
|
|
137
|
+
"""Authenticate with the API and connect to the gateway.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
token: Bot token (starts with ``tavbot_``).
|
|
141
|
+
"""
|
|
142
|
+
self._token = token
|
|
143
|
+
self._rest = RESTClient(token, api_url=self._api_url)
|
|
144
|
+
|
|
145
|
+
# Fetch bot identity
|
|
146
|
+
self._bot_self = await self._rest.get_self()
|
|
147
|
+
self._taverns = {t.id: t for t in self._bot_self.taverns}
|
|
148
|
+
|
|
149
|
+
logger.info(
|
|
150
|
+
"Logged in as %s (connected to %d taverns)",
|
|
151
|
+
self.user.display_name, len(self._taverns),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# Populate channels
|
|
155
|
+
for tavern in self._bot_self.taverns:
|
|
156
|
+
try:
|
|
157
|
+
channels = await self._rest.get_channels(tavern.id)
|
|
158
|
+
for ch in channels:
|
|
159
|
+
self._channels[ch.id] = ch
|
|
160
|
+
except Exception as e:
|
|
161
|
+
logger.warning("Failed to fetch channels for %s: %s", tavern.id, e)
|
|
162
|
+
|
|
163
|
+
# Dispatch ready event
|
|
164
|
+
await self._dispatch("ready")
|
|
165
|
+
|
|
166
|
+
# Connect to gateway
|
|
167
|
+
self._gateway = Gateway(
|
|
168
|
+
token,
|
|
169
|
+
intents=self._intents,
|
|
170
|
+
ws_url=self._ws_url,
|
|
171
|
+
on_event=self._handle_event,
|
|
172
|
+
)
|
|
173
|
+
await self._gateway.connect()
|
|
174
|
+
|
|
175
|
+
async def close(self) -> None:
|
|
176
|
+
"""Disconnect and clean up."""
|
|
177
|
+
if self._gateway:
|
|
178
|
+
await self._gateway.disconnect()
|
|
179
|
+
if self._rest:
|
|
180
|
+
await self._rest.close()
|
|
181
|
+
logger.info("Client closed")
|
|
182
|
+
|
|
183
|
+
def run(self, token: str) -> None:
|
|
184
|
+
"""Blocking call that logs in and runs the bot until interrupted.
|
|
185
|
+
|
|
186
|
+
This is the simplest way to start a bot::
|
|
187
|
+
|
|
188
|
+
client.run("tavbot_xxx")
|
|
189
|
+
"""
|
|
190
|
+
async def _runner() -> None:
|
|
191
|
+
try:
|
|
192
|
+
await self.login(token)
|
|
193
|
+
except KeyboardInterrupt:
|
|
194
|
+
pass
|
|
195
|
+
finally:
|
|
196
|
+
await self.close()
|
|
197
|
+
|
|
198
|
+
try:
|
|
199
|
+
asyncio.run(_runner())
|
|
200
|
+
except KeyboardInterrupt:
|
|
201
|
+
pass
|
|
202
|
+
|
|
203
|
+
# ─── Internal event dispatch ─────────────────────────
|
|
204
|
+
|
|
205
|
+
async def _handle_event(self, event_name: str, data: dict[str, Any]) -> None:
|
|
206
|
+
"""Route gateway events to registered handlers."""
|
|
207
|
+
# Convert data to typed objects where applicable
|
|
208
|
+
if event_name == "message_create":
|
|
209
|
+
obj = Message.from_dict(data)
|
|
210
|
+
await self._dispatch(event_name, obj)
|
|
211
|
+
elif event_name == "interaction_create":
|
|
212
|
+
obj = Interaction.from_dict(data, rest=self._rest)
|
|
213
|
+
await self._dispatch(event_name, obj)
|
|
214
|
+
elif event_name in ("member_join", "member_leave"):
|
|
215
|
+
obj = Member.from_dict(data)
|
|
216
|
+
await self._dispatch(event_name, obj)
|
|
217
|
+
elif event_name in ("channel_create", "channel_update"):
|
|
218
|
+
obj = Channel.from_dict(data)
|
|
219
|
+
self._channels[obj.id] = obj
|
|
220
|
+
await self._dispatch(event_name, obj)
|
|
221
|
+
elif event_name == "channel_delete":
|
|
222
|
+
ch_id = data.get("id", "")
|
|
223
|
+
self._channels.pop(ch_id, None)
|
|
224
|
+
await self._dispatch(event_name, data)
|
|
225
|
+
elif event_name == "bot_installed":
|
|
226
|
+
tavern = Tavern.from_dict(data) if "name" in data else None
|
|
227
|
+
if tavern:
|
|
228
|
+
self._taverns[tavern.id] = tavern
|
|
229
|
+
await self._dispatch(event_name, data)
|
|
230
|
+
elif event_name == "bot_removed":
|
|
231
|
+
t_id = data.get("tavernId", "")
|
|
232
|
+
self._taverns.pop(t_id, None)
|
|
233
|
+
await self._dispatch(event_name, data)
|
|
234
|
+
else:
|
|
235
|
+
await self._dispatch(event_name, data)
|
|
236
|
+
|
|
237
|
+
async def _dispatch(self, event_name: str, *args: Any) -> None:
|
|
238
|
+
"""Call all registered handlers for an event."""
|
|
239
|
+
handlers = self._event_handlers.get(event_name, [])
|
|
240
|
+
for handler in handlers:
|
|
241
|
+
try:
|
|
242
|
+
await handler(*args)
|
|
243
|
+
except Exception:
|
|
244
|
+
logger.exception("Error in event handler for %s", event_name)
|
taverns/commands.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Slash command builder utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .types import CommandOptionType
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def command(
|
|
11
|
+
name: str,
|
|
12
|
+
description: str,
|
|
13
|
+
*,
|
|
14
|
+
options: list[dict[str, Any]] | None = None,
|
|
15
|
+
default_member_permissions: str | None = None,
|
|
16
|
+
) -> dict[str, Any]:
|
|
17
|
+
"""Build a slash command definition for registration.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
name: Command name (lowercase alphanumeric + hyphens, max 32 chars).
|
|
21
|
+
description: Command description (max 100 chars).
|
|
22
|
+
options: List of command options (use :func:`option` to build).
|
|
23
|
+
default_member_permissions: BigInt string of required Tavern permissions.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
dict ready to pass to :meth:`Client.register_commands`.
|
|
27
|
+
|
|
28
|
+
Example::
|
|
29
|
+
|
|
30
|
+
from taverns.commands import command, option
|
|
31
|
+
from taverns.types import CommandOptionType
|
|
32
|
+
|
|
33
|
+
cmds = [
|
|
34
|
+
command("ping", "Check bot latency"),
|
|
35
|
+
command("ban", "Ban a user", options=[
|
|
36
|
+
option("user", "User to ban", CommandOptionType.USER, required=True),
|
|
37
|
+
option("reason", "Ban reason", CommandOptionType.STRING),
|
|
38
|
+
]),
|
|
39
|
+
]
|
|
40
|
+
await client.register_commands(cmds)
|
|
41
|
+
"""
|
|
42
|
+
cmd: dict[str, Any] = {"name": name, "description": description}
|
|
43
|
+
if options:
|
|
44
|
+
cmd["options"] = options
|
|
45
|
+
if default_member_permissions:
|
|
46
|
+
cmd["defaultMemberPermissions"] = default_member_permissions
|
|
47
|
+
return cmd
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def option(
|
|
51
|
+
name: str,
|
|
52
|
+
description: str,
|
|
53
|
+
type: CommandOptionType | int = CommandOptionType.STRING,
|
|
54
|
+
*,
|
|
55
|
+
required: bool = False,
|
|
56
|
+
choices: list[dict[str, Any]] | None = None,
|
|
57
|
+
) -> dict[str, Any]:
|
|
58
|
+
"""Build a command option definition.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
name: Option name (lowercase alphanumeric + hyphens).
|
|
62
|
+
description: Option description.
|
|
63
|
+
type: Option type (use :class:`CommandOptionType`).
|
|
64
|
+
required: Whether this option is required.
|
|
65
|
+
choices: Preset choices for the option.
|
|
66
|
+
"""
|
|
67
|
+
opt: dict[str, Any] = {
|
|
68
|
+
"name": name,
|
|
69
|
+
"description": description,
|
|
70
|
+
"type": int(type),
|
|
71
|
+
}
|
|
72
|
+
if required:
|
|
73
|
+
opt["required"] = True
|
|
74
|
+
if choices:
|
|
75
|
+
opt["choices"] = choices
|
|
76
|
+
return opt
|
taverns/errors.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Taverns SDK error types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class TavernError(Exception):
|
|
7
|
+
"""Base exception for all Taverns SDK errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AuthenticationError(TavernError):
|
|
11
|
+
"""Raised when bot token authentication fails."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HTTPError(TavernError):
|
|
15
|
+
"""Raised when an API request fails."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, status: int, message: str, *, response_body: dict | None = None):
|
|
18
|
+
self.status = status
|
|
19
|
+
self.response_body = response_body
|
|
20
|
+
super().__init__(f"HTTP {status}: {message}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RateLimitError(HTTPError):
|
|
24
|
+
"""Raised when rate limited (429). Contains retry_after in seconds."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, retry_after: float, message: str = "Rate limited"):
|
|
27
|
+
self.retry_after = retry_after
|
|
28
|
+
super().__init__(429, message)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class GatewayError(TavernError):
|
|
32
|
+
"""Raised on WebSocket gateway errors."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class InteractionError(TavernError):
|
|
36
|
+
"""Raised when an interaction response fails."""
|
taverns/gateway.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""WebSocket gateway client with heartbeat, intents, and auto-reconnect."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import random
|
|
9
|
+
from typing import Any, Callable, Coroutine
|
|
10
|
+
|
|
11
|
+
import websockets
|
|
12
|
+
import websockets.exceptions
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("taverns.gateway")
|
|
15
|
+
|
|
16
|
+
DEFAULT_WS_URL = "wss://ws.tav.gg"
|
|
17
|
+
HEARTBEAT_INTERVAL = 30 # seconds
|
|
18
|
+
MAX_RECONNECT_DELAY = 30 # seconds
|
|
19
|
+
|
|
20
|
+
# Maps wire event names to friendly Python event names
|
|
21
|
+
EVENT_NAME_MAP: dict[str, str] = {
|
|
22
|
+
"tavern_message": "message_create",
|
|
23
|
+
"tavern_message_edited": "message_update",
|
|
24
|
+
"tavern_message_deleted": "message_delete",
|
|
25
|
+
"tavern_messages_bulk_deleted": "message_bulk_delete",
|
|
26
|
+
"tavern_member_joined": "member_join",
|
|
27
|
+
"tavern_member_left": "member_leave",
|
|
28
|
+
"tavern_channel_created": "channel_create",
|
|
29
|
+
"tavern_channel_updated": "channel_update",
|
|
30
|
+
"tavern_channel_deleted": "channel_delete",
|
|
31
|
+
"tavern_role_updated": "role_update",
|
|
32
|
+
"tavern_role_deleted": "role_delete",
|
|
33
|
+
"tavern_updated": "tavern_update",
|
|
34
|
+
"tavern_typing_indicator": "typing",
|
|
35
|
+
"tavern_reaction_updated": "reaction_update",
|
|
36
|
+
"tavern_message_pinned": "message_pin",
|
|
37
|
+
"tavern_message_unpinned": "message_unpin",
|
|
38
|
+
"tavern_voice_state_update": "voice_state_update",
|
|
39
|
+
"tavern_event_created": "event_create",
|
|
40
|
+
"tavern_event_updated": "event_update",
|
|
41
|
+
"tavern_event_deleted": "event_delete",
|
|
42
|
+
"tavern_thread_created": "thread_create",
|
|
43
|
+
"tavern_thread_message": "thread_message",
|
|
44
|
+
"tavern_forum_post_created": "forum_post_create",
|
|
45
|
+
"interaction_create": "interaction_create",
|
|
46
|
+
"interaction_response": "interaction_response",
|
|
47
|
+
"interaction_deferred": "interaction_deferred",
|
|
48
|
+
"bot_installed": "bot_installed",
|
|
49
|
+
"bot_removed": "bot_removed",
|
|
50
|
+
"bot_permissions_updated": "bot_permissions_updated",
|
|
51
|
+
"presence_update": "presence_update",
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
EventHandler = Callable[[str, dict[str, Any]], Coroutine[Any, Any, None]]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Gateway:
|
|
59
|
+
"""WebSocket gateway connection to the Taverns platform.
|
|
60
|
+
|
|
61
|
+
Connects with bot token authentication and optional session intents.
|
|
62
|
+
Sends heartbeats every 30 seconds and auto-reconnects on disconnect.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
token: str,
|
|
68
|
+
*,
|
|
69
|
+
intents: int | None = None,
|
|
70
|
+
ws_url: str = DEFAULT_WS_URL,
|
|
71
|
+
on_event: EventHandler | None = None,
|
|
72
|
+
):
|
|
73
|
+
self._token = token
|
|
74
|
+
self._intents = intents
|
|
75
|
+
self._ws_url = ws_url
|
|
76
|
+
self._on_event = on_event
|
|
77
|
+
self._ws: Any = None
|
|
78
|
+
self._heartbeat_task: asyncio.Task | None = None
|
|
79
|
+
self._running = False
|
|
80
|
+
self._reconnect_attempt = 0
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def is_connected(self) -> bool:
|
|
84
|
+
return self._ws is not None and self._ws.open
|
|
85
|
+
|
|
86
|
+
async def connect(self) -> None:
|
|
87
|
+
"""Connect to the gateway and start receiving events."""
|
|
88
|
+
self._running = True
|
|
89
|
+
while self._running:
|
|
90
|
+
try:
|
|
91
|
+
await self._connect_once()
|
|
92
|
+
except asyncio.CancelledError:
|
|
93
|
+
break
|
|
94
|
+
except Exception as e:
|
|
95
|
+
if not self._running:
|
|
96
|
+
break
|
|
97
|
+
delay = min(
|
|
98
|
+
(2 ** self._reconnect_attempt) + random.uniform(0, 1),
|
|
99
|
+
MAX_RECONNECT_DELAY,
|
|
100
|
+
)
|
|
101
|
+
self._reconnect_attempt += 1
|
|
102
|
+
logger.warning(
|
|
103
|
+
"Gateway disconnected (%s), reconnecting in %.1fs (attempt %d)",
|
|
104
|
+
e, delay, self._reconnect_attempt,
|
|
105
|
+
)
|
|
106
|
+
await asyncio.sleep(delay)
|
|
107
|
+
|
|
108
|
+
async def _connect_once(self) -> None:
|
|
109
|
+
url = f"{self._ws_url}?token={self._token}"
|
|
110
|
+
if self._intents is not None:
|
|
111
|
+
url += f"&intents={self._intents}"
|
|
112
|
+
|
|
113
|
+
logger.info("Connecting to gateway: %s", self._ws_url)
|
|
114
|
+
|
|
115
|
+
async with websockets.connect(url) as ws:
|
|
116
|
+
self._ws = ws
|
|
117
|
+
self._reconnect_attempt = 0
|
|
118
|
+
logger.info("Gateway connected")
|
|
119
|
+
|
|
120
|
+
# Start heartbeat
|
|
121
|
+
self._heartbeat_task = asyncio.create_task(self._heartbeat_loop(ws))
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
async for raw in ws:
|
|
125
|
+
try:
|
|
126
|
+
data = json.loads(raw)
|
|
127
|
+
event_name = data.get("event", "")
|
|
128
|
+
event_data = data.get("data", {})
|
|
129
|
+
|
|
130
|
+
friendly = EVENT_NAME_MAP.get(event_name, event_name)
|
|
131
|
+
if self._on_event:
|
|
132
|
+
await self._on_event(friendly, event_data)
|
|
133
|
+
except json.JSONDecodeError:
|
|
134
|
+
logger.warning("Received non-JSON message from gateway")
|
|
135
|
+
finally:
|
|
136
|
+
if self._heartbeat_task:
|
|
137
|
+
self._heartbeat_task.cancel()
|
|
138
|
+
try:
|
|
139
|
+
await self._heartbeat_task
|
|
140
|
+
except asyncio.CancelledError:
|
|
141
|
+
pass
|
|
142
|
+
self._ws = None
|
|
143
|
+
|
|
144
|
+
async def _heartbeat_loop(self, ws: Any) -> None:
|
|
145
|
+
"""Send heartbeat every 30 seconds to keep the connection alive."""
|
|
146
|
+
while True:
|
|
147
|
+
await asyncio.sleep(HEARTBEAT_INTERVAL)
|
|
148
|
+
try:
|
|
149
|
+
await ws.send(json.dumps({"action": "heartbeat", "data": {}}))
|
|
150
|
+
logger.debug("Heartbeat sent")
|
|
151
|
+
except websockets.exceptions.ConnectionClosed:
|
|
152
|
+
break
|
|
153
|
+
|
|
154
|
+
async def disconnect(self) -> None:
|
|
155
|
+
"""Gracefully disconnect from the gateway."""
|
|
156
|
+
self._running = False
|
|
157
|
+
if self._heartbeat_task:
|
|
158
|
+
self._heartbeat_task.cancel()
|
|
159
|
+
if self._ws:
|
|
160
|
+
await self._ws.close()
|
|
161
|
+
self._ws = None
|
taverns/intents.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Gateway intent bitfield — controls which events a bot receives.
|
|
2
|
+
|
|
3
|
+
Two-layer model:
|
|
4
|
+
- Application-level: BotApplication.allowedIntents (developer configures max)
|
|
5
|
+
- Session-level: declared at connect time via ?intents= query parameter
|
|
6
|
+
- Effective: session & allowed (computed server-side)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Intents:
|
|
13
|
+
"""Bitfield of gateway intents.
|
|
14
|
+
|
|
15
|
+
Usage::
|
|
16
|
+
|
|
17
|
+
intents = Intents.MESSAGES | Intents.MESSAGE_CONTENT | Intents.INTERACTIONS
|
|
18
|
+
client = Client(intents=intents)
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
MESSAGES: int = 1 << 0
|
|
22
|
+
MESSAGE_CONTENT: int = 1 << 1 # Privileged
|
|
23
|
+
MEMBERS: int = 1 << 2 # Privileged
|
|
24
|
+
MODERATION: int = 1 << 3
|
|
25
|
+
CHANNELS: int = 1 << 4
|
|
26
|
+
THREADS: int = 1 << 5
|
|
27
|
+
FORUMS: int = 1 << 6
|
|
28
|
+
ROLES: int = 1 << 7
|
|
29
|
+
SETTINGS: int = 1 << 8
|
|
30
|
+
EVENTS: int = 1 << 9
|
|
31
|
+
VOICE: int = 1 << 10
|
|
32
|
+
BROADCASTS: int = 1 << 11
|
|
33
|
+
TYPING: int = 1 << 12
|
|
34
|
+
REACTIONS: int = 1 << 13
|
|
35
|
+
PINS: int = 1 << 14
|
|
36
|
+
INTERACTIONS: int = 1 << 15
|
|
37
|
+
|
|
38
|
+
# Shortcuts
|
|
39
|
+
DEFAULT: int = 0x7FF9 # All non-privileged (bits 0, 3-15)
|
|
40
|
+
ALL: int = 0xFFFF # All intents including privileged
|
|
41
|
+
|
|
42
|
+
@staticmethod
|
|
43
|
+
def from_list(*intent_names: str) -> int:
|
|
44
|
+
"""Build an intents value from intent names.
|
|
45
|
+
|
|
46
|
+
Example::
|
|
47
|
+
|
|
48
|
+
intents = Intents.from_list("MESSAGES", "INTERACTIONS")
|
|
49
|
+
"""
|
|
50
|
+
mapping = {
|
|
51
|
+
"MESSAGES": Intents.MESSAGES,
|
|
52
|
+
"MESSAGE_CONTENT": Intents.MESSAGE_CONTENT,
|
|
53
|
+
"MEMBERS": Intents.MEMBERS,
|
|
54
|
+
"MODERATION": Intents.MODERATION,
|
|
55
|
+
"CHANNELS": Intents.CHANNELS,
|
|
56
|
+
"THREADS": Intents.THREADS,
|
|
57
|
+
"FORUMS": Intents.FORUMS,
|
|
58
|
+
"ROLES": Intents.ROLES,
|
|
59
|
+
"SETTINGS": Intents.SETTINGS,
|
|
60
|
+
"EVENTS": Intents.EVENTS,
|
|
61
|
+
"VOICE": Intents.VOICE,
|
|
62
|
+
"BROADCASTS": Intents.BROADCASTS,
|
|
63
|
+
"TYPING": Intents.TYPING,
|
|
64
|
+
"REACTIONS": Intents.REACTIONS,
|
|
65
|
+
"PINS": Intents.PINS,
|
|
66
|
+
"INTERACTIONS": Intents.INTERACTIONS,
|
|
67
|
+
}
|
|
68
|
+
value = 0
|
|
69
|
+
for name in intent_names:
|
|
70
|
+
upper = name.upper()
|
|
71
|
+
if upper not in mapping:
|
|
72
|
+
raise ValueError(f"Unknown intent: {name}")
|
|
73
|
+
value |= mapping[upper]
|
|
74
|
+
return value
|