yapbot 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.

Potentially problematic release.


This version of yapbot might be problematic. Click here for more details.

yapbot/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Yap bot library: a real bot account, its token, and the gateway."""
2
+
3
+ from .bot import Bot, BotStopped, Context
4
+ from .rest import Rest, YapError
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = ["Bot", "BotStopped", "Context", "Rest", "YapError"]
@@ -0,0 +1 @@
1
+ """The generated gateway stubs, inside the package so `pip install yapbot` ships them."""
@@ -0,0 +1,104 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: yap/v1/gateway.proto
5
+ # Protobuf Python Version: 7.35.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 7,
15
+ 35,
16
+ 1,
17
+ '',
18
+ 'yap/v1/gateway.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+
26
+
27
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x14yap/v1/gateway.proto\x12\x06yap.v1\"\x81\t\n\x05\x46rame\x12\x0b\n\x03seq\x18\x01 \x01(\x04\x12\x1e\n\x05hello\x18\n \x01(\x0b\x32\r.yap.v1.HelloH\x00\x12+\n\x0csend_message\x18\x0b \x01(\x0b\x32\x13.yap.v1.SendMessageH\x00\x12\x1c\n\x04ping\x18\x0c \x01(\x0b\x32\x0c.yap.v1.PingH\x00\x12\'\n\nvoice_join\x18\r \x01(\x0b\x32\x11.yap.v1.VoiceJoinH\x00\x12)\n\x0bvoice_leave\x18\x0e \x01(\x0b\x32\x12.yap.v1.VoiceLeaveH\x00\x12+\n\x0cvoice_update\x18\x0f \x01(\x0b\x32\x13.yap.v1.VoiceUpdateH\x00\x12+\n\x0cvoice_signal\x18\x10 \x01(\x0b\x32\x13.yap.v1.VoiceSignalH\x00\x12\x1e\n\x05ready\x18\x14 \x01(\x0b\x32\r.yap.v1.ReadyH\x00\x12/\n\x0emessage_create\x18\x15 \x01(\x0b\x32\x15.yap.v1.MessageCreateH\x00\x12/\n\x0e\x63hannel_create\x18\x16 \x01(\x0b\x32\x15.yap.v1.ChannelCreateH\x00\x12\x1c\n\x04pong\x18\x17 \x01(\x0b\x32\x0c.yap.v1.PongH\x00\x12\x1e\n\x05\x65rror\x18\x18 \x01(\x0b\x32\r.yap.v1.ErrorH\x00\x12+\n\x0cvoice_joined\x18\x19 \x01(\x0b\x32\x13.yap.v1.VoiceJoinedH\x00\x12)\n\x0bvoice_state\x18\x1a \x01(\x0b\x32\x12.yap.v1.VoiceStateH\x00\x12+\n\x0cspace_delete\x18\x1b \x01(\x0b\x32\x13.yap.v1.SpaceDeleteH\x00\x12/\n\x0e\x63hannel_delete\x18\x1c \x01(\x0b\x32\x15.yap.v1.ChannelDeleteH\x00\x12+\n\x0cspace_update\x18\x1d \x01(\x0b\x32\x13.yap.v1.SpaceUpdateH\x00\x12/\n\x0e\x63hannel_update\x18\x1e \x01(\x0b\x32\x15.yap.v1.ChannelUpdateH\x00\x12/\n\x0emessage_update\x18\x1f \x01(\x0b\x32\x15.yap.v1.MessageUpdateH\x00\x12/\n\x0emessage_delete\x18 \x01(\x0b\x32\x15.yap.v1.MessageDeleteH\x00\x12\x31\n\x0freaction_update\x18! \x01(\x0b\x32\x16.yap.v1.ReactionUpdateH\x00\x12 \n\x06typing\x18\" \x01(\x0b\x32\x0e.yap.v1.TypingH\x00\x12)\n\x0bmember_join\x18# \x01(\x0b\x32\x12.yap.v1.MemberJoinH\x00\x12\x36\n\x12voice_join_request\x18$ \x01(\x0b\x32\x18.yap.v1.VoiceJoinRequestH\x00\x12-\n\rvoice_control\x18% \x01(\x0b\x32\x14.yap.v1.VoiceControlH\x00\x12/\n\x0eprofile_update\x18\x32 \x01(\x0b\x32\x15.yap.v1.ProfileUpdateH\x00\x42\x04\n\x02op\"F\n\x05Hello\x12\x14\n\x0c\x61\x63\x63\x65ss_token\x18\x01 \x01(\t\x12\x18\n\x10protocol_version\x18\x02 \x01(\r\x12\r\n\x05proof\x18\x03 \x01(\t\"{\n\x05Ready\x12\x1a\n\x04user\x18\x01 \x01(\x0b\x32\x0c.yap.v1.User\x12\x1d\n\x06spaces\x18\x02 \x03(\x0b\x32\r.yap.v1.Space\x12\x14\n\x0cheartbeat_ms\x18\x03 \x01(\r\x12!\n\x05voice\x18\x04 \x03(\x0b\x32\x12.yap.v1.VoiceState\"\x98\x01\n\x04User\x12\n\n\x02id\x18\x01 \x01(\x06\x12\x10\n\x08username\x18\x02 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x03 \x01(\t\x12\x0e\n\x06status\x18\x04 \x01(\t\x12\r\n\x05\x63olor\x18\x05 \x01(\x05\x12\x0b\n\x03\x62ot\x18\x06 \x01(\x08\x12\x10\n\x08verified\x18\x07 \x01(\x08\x12\x0e\n\x06\x61vatar\x18\x14 \x01(\t\x12\x0e\n\x06\x62\x61nner\x18\x15 \x01(\t\"+\n\rProfileUpdate\x12\x1a\n\x04user\x18\x01 \x01(\x0b\x32\x0c.yap.v1.User\"i\n\x05Space\x12\n\n\x02id\x18\x01 \x01(\x06\x12\x0c\n\x04name\x18\x02 \x01(\t\x12!\n\x08\x63hannels\x18\x03 \x03(\x0b\x32\x0f.yap.v1.Channel\x12\x10\n\x08owner_id\x18\x04 \x01(\x06\x12\x11\n\tencrypted\x18\x05 \x01(\x08\"j\n\x07\x43hannel\x12\n\n\x02id\x18\x01 \x01(\x06\x12\x10\n\x08space_id\x18\x02 \x01(\x06\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x10\n\x08position\x18\x04 \x01(\x05\x12!\n\x04kind\x18\x05 \x01(\x0e\x32\x13.yap.v1.ChannelKind\"\xef\x01\n\x07Message\x12\n\n\x02id\x18\x01 \x01(\x06\x12\x12\n\nchannel_id\x18\x02 \x01(\x06\x12\x11\n\tauthor_id\x18\x03 \x01(\x06\x12\x13\n\x0b\x61uthor_name\x18\x04 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x05 \x01(\t\x12\x15\n\rcreated_at_ms\x18\x06 \x01(\x03\x12\x1b\n\x13\x61uthor_display_name\x18\x07 \x01(\t\x12\x14\n\x0c\x61uthor_color\x18\x08 \x01(\x05\x12\x14\n\x0c\x65\x64ited_at_ms\x18\t \x01(\x03\x12\x12\n\nauthor_bot\x18\n \x01(\x08\x12\x17\n\x0f\x61uthor_verified\x18\x0b \x01(\x08\"A\n\x0bSendMessage\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\x12\r\n\x05nonce\x18\x02 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x03 \x01(\t\"@\n\rMessageCreate\x12 \n\x07message\x18\x01 \x01(\x0b\x32\x0f.yap.v1.Message\x12\r\n\x05nonce\x18\x02 \x01(\t\"1\n\rChannelCreate\x12 \n\x07\x63hannel\x18\x01 \x01(\x0b\x32\x0f.yap.v1.Channel\"\x1f\n\x0bSpaceDelete\x12\x10\n\x08space_id\x18\x01 \x01(\x06\"5\n\rChannelDelete\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\x12\x10\n\x08space_id\x18\x02 \x01(\x06\"-\n\x0bSpaceUpdate\x12\x10\n\x08space_id\x18\x01 \x01(\x06\x12\x0c\n\x04name\x18\x02 \x01(\t\"g\n\rChannelUpdate\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\x12\x10\n\x08space_id\x18\x02 \x01(\x06\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\x15\n\x08\x63\x61tegory\x18\x04 \x01(\tH\x00\x88\x01\x01\x42\x0b\n\t_category\"1\n\rMessageUpdate\x12 \n\x07message\x18\x01 \x01(\x0b\x32\x0f.yap.v1.Message\"7\n\rMessageDelete\x12\x12\n\nmessage_id\x18\x01 \x01(\x06\x12\x12\n\nchannel_id\x18\x02 \x01(\x06\"v\n\x0eReactionUpdate\x12\x12\n\nmessage_id\x18\x01 \x01(\x06\x12\x12\n\nchannel_id\x18\x02 \x01(\x06\x12\r\n\x05\x65moji\x18\x03 \x01(\t\x12\r\n\x05\x63ount\x18\x04 \x01(\r\x12\x0f\n\x07user_id\x18\x05 \x01(\x06\x12\r\n\x05\x61\x64\x64\x65\x64\x18\x06 \x01(\x08\"<\n\nMemberJoin\x12\x10\n\x08space_id\x18\x01 \x01(\x06\x12\x1c\n\x06member\x18\x02 \x01(\x0b\x32\x0c.yap.v1.User\"Q\n\x06Typing\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\x12\x10\n\x08space_id\x18\x02 \x01(\x06\x12\x0f\n\x07user_id\x18\x03 \x01(\x06\x12\x10\n\x08username\x18\x04 \x01(\t\"\x1e\n\x04Ping\x12\x16\n\x0e\x63lient_time_ms\x18\x01 \x01(\x04\"\x1e\n\x04Pong\x12\x16\n\x0e\x63lient_time_ms\x18\x01 \x01(\x04\"H\n\x05\x45rror\x12\x1f\n\x04\x63ode\x18\x01 \x01(\x0e\x32\x11.yap.v1.ErrorCode\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\r\n\x05nonce\x18\x03 \x01(\t\"\x1f\n\tVoiceJoin\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\"\x0c\n\nVoiceLeave\"@\n\x0bVoiceUpdate\x12\r\n\x05muted\x18\x01 \x01(\x08\x12\x10\n\x08\x64\x65\x61\x66\x65ned\x18\x02 \x01(\x08\x12\x10\n\x08speaking\x18\x03 \x01(\x08\"V\n\x0bVoiceSignal\x12\x12\n\nto_user_id\x18\x01 \x01(\x06\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x0f\n\x07payload\x18\x03 \x01(\t\x12\x14\n\x0c\x66rom_user_id\x18\x04 \x01(\x06\"?\n\tIceServer\x12\x0c\n\x04urls\x18\x01 \x03(\t\x12\x10\n\x08username\x18\x02 \x01(\t\x12\x12\n\ncredential\x18\x03 \x01(\t\"\x83\x01\n\x0bVoiceJoined\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\x12&\n\x0bice_servers\x18\x02 \x03(\x0b\x32\x11.yap.v1.IceServer\x12\x12\n\nrelay_only\x18\x03 \x01(\x08\x12$\n\x07members\x18\x04 \x03(\x0b\x32\x13.yap.v1.VoiceMember\"c\n\x0bVoiceMember\x12\x0f\n\x07user_id\x18\x01 \x01(\x06\x12\x10\n\x08username\x18\x02 \x01(\t\x12\r\n\x05muted\x18\x03 \x01(\x08\x12\x10\n\x08\x64\x65\x61\x66\x65ned\x18\x04 \x01(\x08\x12\x10\n\x08speaking\x18\x05 \x01(\x08\"X\n\nVoiceState\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\x12\x10\n\x08space_id\x18\x02 \x01(\x06\x12$\n\x07members\x18\x03 \x03(\x0b\x32\x13.yap.v1.VoiceMember\"&\n\x10VoiceJoinRequest\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\"C\n\x0cVoiceControl\x12\x12\n\nchannel_id\x18\x01 \x01(\x06\x12\r\n\x05muted\x18\x02 \x01(\x08\x12\x10\n\x08\x64\x65\x61\x66\x65ned\x18\x03 \x01(\x08*<\n\x0b\x43hannelKind\x12\x15\n\x11\x43HANNEL_KIND_TEXT\x10\x00\x12\x16\n\x12\x43HANNEL_KIND_VOICE\x10\x01*\xe0\x01\n\tErrorCode\x12\x1a\n\x16\x45RROR_CODE_UNSPECIFIED\x10\x00\x12\x18\n\x14\x45RROR_CODE_BAD_FRAME\x10\x01\x12\x1b\n\x17\x45RROR_CODE_UNAUTHORIZED\x10\x02\x12\x18\n\x14\x45RROR_CODE_FORBIDDEN\x10\x03\x12\x1b\n\x17\x45RROR_CODE_RATE_LIMITED\x10\x04\x12\x16\n\x12\x45RROR_CODE_INVALID\x10\x05\x12\x18\n\x14\x45RROR_CODE_NOT_FOUND\x10\x06\x12\x17\n\x13\x45RROR_CODE_INTERNAL\x10\x07\x62\x06proto3')
28
+
29
+ _globals = globals()
30
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
31
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'yap.v1.gateway_pb2', _globals)
32
+ if not _descriptor._USE_C_DESCRIPTORS:
33
+ DESCRIPTOR._loaded_options = None
34
+ _globals['_CHANNELKIND']._serialized_start=3677
35
+ _globals['_CHANNELKIND']._serialized_end=3737
36
+ _globals['_ERRORCODE']._serialized_start=3740
37
+ _globals['_ERRORCODE']._serialized_end=3964
38
+ _globals['_FRAME']._serialized_start=33
39
+ _globals['_FRAME']._serialized_end=1186
40
+ _globals['_HELLO']._serialized_start=1188
41
+ _globals['_HELLO']._serialized_end=1258
42
+ _globals['_READY']._serialized_start=1260
43
+ _globals['_READY']._serialized_end=1383
44
+ _globals['_USER']._serialized_start=1386
45
+ _globals['_USER']._serialized_end=1538
46
+ _globals['_PROFILEUPDATE']._serialized_start=1540
47
+ _globals['_PROFILEUPDATE']._serialized_end=1583
48
+ _globals['_SPACE']._serialized_start=1585
49
+ _globals['_SPACE']._serialized_end=1690
50
+ _globals['_CHANNEL']._serialized_start=1692
51
+ _globals['_CHANNEL']._serialized_end=1798
52
+ _globals['_MESSAGE']._serialized_start=1801
53
+ _globals['_MESSAGE']._serialized_end=2040
54
+ _globals['_SENDMESSAGE']._serialized_start=2042
55
+ _globals['_SENDMESSAGE']._serialized_end=2107
56
+ _globals['_MESSAGECREATE']._serialized_start=2109
57
+ _globals['_MESSAGECREATE']._serialized_end=2173
58
+ _globals['_CHANNELCREATE']._serialized_start=2175
59
+ _globals['_CHANNELCREATE']._serialized_end=2224
60
+ _globals['_SPACEDELETE']._serialized_start=2226
61
+ _globals['_SPACEDELETE']._serialized_end=2257
62
+ _globals['_CHANNELDELETE']._serialized_start=2259
63
+ _globals['_CHANNELDELETE']._serialized_end=2312
64
+ _globals['_SPACEUPDATE']._serialized_start=2314
65
+ _globals['_SPACEUPDATE']._serialized_end=2359
66
+ _globals['_CHANNELUPDATE']._serialized_start=2361
67
+ _globals['_CHANNELUPDATE']._serialized_end=2464
68
+ _globals['_MESSAGEUPDATE']._serialized_start=2466
69
+ _globals['_MESSAGEUPDATE']._serialized_end=2515
70
+ _globals['_MESSAGEDELETE']._serialized_start=2517
71
+ _globals['_MESSAGEDELETE']._serialized_end=2572
72
+ _globals['_REACTIONUPDATE']._serialized_start=2574
73
+ _globals['_REACTIONUPDATE']._serialized_end=2692
74
+ _globals['_MEMBERJOIN']._serialized_start=2694
75
+ _globals['_MEMBERJOIN']._serialized_end=2754
76
+ _globals['_TYPING']._serialized_start=2756
77
+ _globals['_TYPING']._serialized_end=2837
78
+ _globals['_PING']._serialized_start=2839
79
+ _globals['_PING']._serialized_end=2869
80
+ _globals['_PONG']._serialized_start=2871
81
+ _globals['_PONG']._serialized_end=2901
82
+ _globals['_ERROR']._serialized_start=2903
83
+ _globals['_ERROR']._serialized_end=2975
84
+ _globals['_VOICEJOIN']._serialized_start=2977
85
+ _globals['_VOICEJOIN']._serialized_end=3008
86
+ _globals['_VOICELEAVE']._serialized_start=3010
87
+ _globals['_VOICELEAVE']._serialized_end=3022
88
+ _globals['_VOICEUPDATE']._serialized_start=3024
89
+ _globals['_VOICEUPDATE']._serialized_end=3088
90
+ _globals['_VOICESIGNAL']._serialized_start=3090
91
+ _globals['_VOICESIGNAL']._serialized_end=3176
92
+ _globals['_ICESERVER']._serialized_start=3178
93
+ _globals['_ICESERVER']._serialized_end=3241
94
+ _globals['_VOICEJOINED']._serialized_start=3244
95
+ _globals['_VOICEJOINED']._serialized_end=3375
96
+ _globals['_VOICEMEMBER']._serialized_start=3377
97
+ _globals['_VOICEMEMBER']._serialized_end=3476
98
+ _globals['_VOICESTATE']._serialized_start=3478
99
+ _globals['_VOICESTATE']._serialized_end=3566
100
+ _globals['_VOICEJOINREQUEST']._serialized_start=3568
101
+ _globals['_VOICEJOINREQUEST']._serialized_end=3606
102
+ _globals['_VOICECONTROL']._serialized_start=3608
103
+ _globals['_VOICECONTROL']._serialized_end=3675
104
+ # @@protoc_insertion_point(module_scope)
yapbot/bot.py ADDED
@@ -0,0 +1,317 @@
1
+ """A Yap bot: one bot account, one token, one gateway connection.
2
+
3
+ Bots are created from the developer portal (`yap.foreskin.dev/developer`), which mints a token. The account
4
+ has no password, so the token is the whole credential — losing it means rotating it in the panel.
5
+
6
+ What a bot can and cannot do is the server's rule, not this library's (docs/protocol.md, "Bots"):
7
+ inside a space it is an ordinary member, and account-level actions belong to people. Encrypted
8
+ spaces stay sealed to it, exactly as they do to any client without the keys.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import inspect
15
+ import logging
16
+ import time
17
+ from dataclasses import dataclass
18
+ from typing import Any, Awaitable, Callable
19
+ from urllib.parse import urlparse
20
+
21
+ import aiohttp
22
+
23
+ from .gateway import Gateway, GatewayClosed
24
+ from .rest import Rest, YapError
25
+
26
+ SEALED_PREFIX = "yap1:"
27
+ log = logging.getLogger("yapbot")
28
+
29
+
30
+ class BotStopped(Exception):
31
+ """The token was rejected or revoked; reconnecting cannot help."""
32
+
33
+
34
+ @dataclass
35
+ class Context:
36
+ """One command invocation."""
37
+
38
+ bot: "Bot"
39
+ channel_id: int
40
+ space_id: int
41
+ message_id: int
42
+ author_id: int
43
+ author: str
44
+ content: str
45
+ args: list[str]
46
+
47
+ async def reply(self, text: str) -> None:
48
+ await self.bot.send(self.channel_id, text)
49
+
50
+ async def history(self, limit: int = 50) -> list[dict[str, Any]]:
51
+ return await self.bot.rest.history(self.channel_id, limit)
52
+
53
+
54
+ Command = Callable[..., Awaitable[None] | None]
55
+
56
+
57
+ class Bot:
58
+ """Register commands, then `await bot.run()`."""
59
+
60
+ def __init__(
61
+ self,
62
+ server: str,
63
+ token: str,
64
+ *,
65
+ prefix: str = "!",
66
+ logger: logging.Logger | None = None,
67
+ ):
68
+ if "://" not in server:
69
+ server = f"https://{server}"
70
+ parsed = urlparse(server)
71
+ self.host = parsed.hostname or ""
72
+ self.base = f"{parsed.scheme}://{parsed.netloc}"
73
+ scheme = "wss" if parsed.scheme == "https" else "ws"
74
+ self.gateway_url = f"{scheme}://{parsed.netloc}/gateway"
75
+ self.token = token
76
+ self.prefix = prefix
77
+ self.log = logger or log
78
+
79
+ self.user_id = 0
80
+ self.username = ""
81
+ # Round trip of the last Ping/Pong, in milliseconds; 0 until the first answers.
82
+ self.latency_ms = 0
83
+ self.spaces: list[Any] = []
84
+ # channel id -> space id, filled from Ready, so a command knows where it fired.
85
+ self.channel_space: dict[int, int] = {}
86
+ self.rest: Rest | None = None
87
+
88
+ self._commands: dict[str, tuple[Command, str]] = {}
89
+ # Slash commands: dispatched from `/name` and published so clients can list them.
90
+ self._slash: dict[str, tuple[Command, str]] = {}
91
+ self._events: dict[str, list[Command]] = {}
92
+ self._gateway: Gateway | None = None
93
+ self._tasks: set[asyncio.Task] = set()
94
+ self._closed = False
95
+
96
+ # ---------- registration ----------
97
+
98
+ def command(
99
+ self, name: str, *, help: str = "", aliases: tuple[str, ...] = ()
100
+ ) -> Callable[[Command], Command]:
101
+ """`@bot.command("roll", help="roll dice", aliases=("dice",))`."""
102
+
103
+ def register(fn: Command) -> Command:
104
+ for alias in (name, *aliases):
105
+ self._commands[alias.lower()] = (fn, help)
106
+ return fn
107
+
108
+ return register
109
+
110
+ def slash(
111
+ self, name: str, *, description: str = ""
112
+ ) -> Callable[[Command], Command]:
113
+ """`@bot.slash("kiss", description="kiss someone")`.
114
+
115
+ Two things happen: clients list it behind `/` in the space (the bot publishes the list
116
+ when it connects), and a message beginning `/name` runs it. There is no interaction
117
+ object — a slash command is an ordinary message, so it works in every client.
118
+ """
119
+
120
+ def register(fn: Command) -> Command:
121
+ self._slash[name.strip().lower()] = (fn, description)
122
+ return fn
123
+
124
+ return register
125
+
126
+ @property
127
+ def slash_commands(self) -> list[dict[str, str]]:
128
+ """The list as the server stores it, in registration order."""
129
+ return [
130
+ {"name": name, "description": description}
131
+ for name, (_, description) in self._slash.items()
132
+ ]
133
+
134
+ def event(self, name: str) -> Callable[[Command], Command]:
135
+ """Hook a gateway event: `ready`, `message`, `message_update`, `message_delete`, …"""
136
+
137
+ def register(fn: Command) -> Command:
138
+ self._events.setdefault(name, []).append(fn)
139
+ return fn
140
+
141
+ return register
142
+
143
+ @property
144
+ def commands(self) -> dict[str, str]:
145
+ """Command name -> help text, aliases included."""
146
+ return {name: help for name, (_, help) in sorted(self._commands.items())}
147
+
148
+ # ---------- running ----------
149
+
150
+ async def run(self) -> None:
151
+ """Connect and stay connected. Returns when the token is rejected or `close()` is called."""
152
+ async with aiohttp.ClientSession() as session:
153
+ self.rest = Rest(self.base, self.token, session)
154
+ backoff = 1.0
155
+ while not self._closed:
156
+ try:
157
+ await self._connect()
158
+ backoff = 1.0
159
+ except BotStopped:
160
+ raise
161
+ except GatewayClosed as exc:
162
+ # A rejected, revoked or rotated token closes the socket as unauthorized, and no
163
+ # amount of reconnecting fixes that: stop, so the operator rotates it instead.
164
+ if str(exc) == "unauthorized":
165
+ raise BotStopped(
166
+ "the token was rejected or revoked; rotate it in the developer portal"
167
+ ) from exc
168
+ self.log.info("gateway closed: %s", exc)
169
+ except (OSError, aiohttp.ClientError) as exc:
170
+ self.log.warning("gateway connection failed: %s", exc)
171
+ if self._closed:
172
+ break
173
+ self.log.info("reconnecting in %.0fs", backoff)
174
+ await asyncio.sleep(backoff)
175
+ backoff = min(backoff * 2, 60.0)
176
+
177
+ async def _connect(self) -> None:
178
+ gateway = Gateway(self.gateway_url, self.token, self._handle_frame, logger=self.log)
179
+ self._gateway = gateway
180
+ self.log.info("connecting to %s", self.gateway_url)
181
+ try:
182
+ await gateway.run()
183
+ finally:
184
+ self._gateway = None
185
+
186
+ async def close(self) -> None:
187
+ self._closed = True
188
+ for task in list(self._tasks):
189
+ task.cancel()
190
+ if self._gateway is not None:
191
+ await self._gateway.close()
192
+
193
+ async def send(self, channel_id: int, content: str) -> None:
194
+ """Send through the gateway, so the reply is ordered with what the bot just read."""
195
+ if self._gateway is None:
196
+ raise RuntimeError("not connected")
197
+ await self._gateway.send_message(int(channel_id), content)
198
+
199
+ # ---------- frames ----------
200
+
201
+ async def _handle_frame(self, name: str, op: Any) -> None:
202
+ if name == "ready":
203
+ self.user_id = int(op.user.id)
204
+ self.username = op.user.username
205
+ self.spaces = list(op.spaces)
206
+ self.channel_space = {
207
+ int(c.id): int(s.id) for s in op.spaces for c in s.channels
208
+ }
209
+ self.log.info("ready as %s (%d spaces)", self.username, len(self.spaces))
210
+ await self._publish_slash_commands()
211
+ await self._emit("ready", op)
212
+ elif name == "message_create":
213
+ self._on_message(op.message)
214
+ elif name == "pong":
215
+ # The client's clock is echoed, so the trip is measurable without a synced clock.
216
+ self.latency_ms = max(0, int(time.time() * 1000) - int(op.client_time_ms))
217
+ else:
218
+ await self._emit(name, op)
219
+
220
+ def _on_message(self, message: Any) -> None:
221
+ # The gateway echoes the bot's own messages back with a nonce; never answer yourself.
222
+ # Another bot is not a person either: two bots answering each other's commands would
223
+ # trade them forever, so `author_bot` is skipped exactly like the bot itself.
224
+ if int(message.author_id) == self.user_id or message.author_bot:
225
+ return
226
+ content = message.content
227
+ if content.startswith(SEALED_PREFIX):
228
+ return # end-to-end encrypted: the bot has no key for this space
229
+ if content.startswith(self.prefix):
230
+ self._spawn(self._dispatch(self._commands, message, content[len(self.prefix):]))
231
+ elif content.startswith("/"):
232
+ self._spawn(self._dispatch(self._slash, message, content[1:]))
233
+ self._spawn(self._emit("message", message))
234
+
235
+ async def space_of(self, channel_id: int) -> int:
236
+ """The space a channel belongs to; resolves it when the bot connected before it existed."""
237
+ channel_id = int(channel_id)
238
+ return self.channel_space.get(channel_id) or await self._resolve_space(channel_id)
239
+
240
+ async def _resolve_space(self, channel_id: int) -> int:
241
+ """The space a channel belongs to, from the live space list; 0 when it is not visible.
242
+
243
+ Only Ready fills `channel_space`, so a bot installed after connecting would not know
244
+ where its first messages came from. Asking once and remembering fixes that for good.
245
+ """
246
+ if self.rest is None:
247
+ return 0
248
+ try:
249
+ for space in await self.rest.spaces():
250
+ if any(int(c["id"]) == channel_id for c in space.get("channels", [])):
251
+ space_id = int(space["id"])
252
+ self.channel_space[channel_id] = space_id
253
+ return space_id
254
+ except (YapError, OSError, aiohttp.ClientError) as exc:
255
+ self.log.warning("could not resolve channel %s: %s", channel_id, exc)
256
+ return 0
257
+
258
+ async def _publish_slash_commands(self) -> None:
259
+ """Tell the server what this bot offers, so clients can build their `/` menu.
260
+
261
+ A failure is not fatal: the commands still run when typed, the menu just stays empty.
262
+ """
263
+ if self.rest is None or not self._slash:
264
+ return
265
+ try:
266
+ await self.rest.set_commands(self.user_id, self.slash_commands)
267
+ except (YapError, OSError, aiohttp.ClientError) as exc:
268
+ self.log.warning("could not publish slash commands: %s", exc)
269
+
270
+ async def _dispatch(
271
+ self, table: dict[str, tuple[Command, str]], message: Any, text: str
272
+ ) -> None:
273
+ parts = text.split()
274
+ if not parts:
275
+ return
276
+ entry = table.get(parts[0].lower())
277
+ if entry is None:
278
+ return
279
+ fn, _ = entry
280
+ channel_id = int(message.channel_id)
281
+ space_id = self.channel_space.get(channel_id, 0)
282
+ if not space_id:
283
+ space_id = await self._resolve_space(channel_id)
284
+ ctx = Context(
285
+ bot=self,
286
+ channel_id=channel_id,
287
+ space_id=space_id,
288
+ message_id=int(message.id),
289
+ author_id=int(message.author_id),
290
+ author=message.author_name,
291
+ content=message.content,
292
+ args=parts[1:],
293
+ )
294
+ try:
295
+ result = fn(ctx, *parts[1:])
296
+ if inspect.isawaitable(result):
297
+ await result
298
+ except Exception:
299
+ self.log.exception("command %r failed", parts[0])
300
+ try:
301
+ await ctx.reply("Something went wrong running that command.")
302
+ except Exception:
303
+ self.log.exception("could not report the failure")
304
+
305
+ async def _emit(self, name: str, payload: Any) -> None:
306
+ for fn in self._events.get(name, []):
307
+ try:
308
+ result = fn(payload)
309
+ if inspect.isawaitable(result):
310
+ await result
311
+ except Exception:
312
+ self.log.exception("event %r handler failed", name)
313
+
314
+ def _spawn(self, coro: Awaitable[None]) -> None:
315
+ task = asyncio.ensure_future(coro)
316
+ self._tasks.add(task)
317
+ task.add_done_callback(self._tasks.discard)
yapbot/gateway.py ADDED
@@ -0,0 +1,146 @@
1
+ """Gateway half: one WebSocket, one protobuf Frame per binary message.
2
+
3
+ Mirrors docs/protocol.md: connect, send Hello within 10 s, then Ping at least every
4
+ `heartbeat_ms`; the server drops the socket after 2.5x that in silence. Text frames are a
5
+ protocol error, so everything here is bytes.
6
+
7
+ A bot token is its own credential and needs no proof. A person's session token is refused unless
8
+ `Hello.proof` signs it with the key that sign-in kept (`selfbot/` uses that path).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import time
15
+ from collections.abc import Awaitable, Callable
16
+ from typing import Any
17
+
18
+ import aiohttp
19
+
20
+ from ._proto import gateway_pb2 as pb
21
+
22
+ PROTOCOL_VERSION = 1
23
+ MAX_FRAME_BYTES = 64 * 1024
24
+ MAX_MESSAGE_CHARS = 4000
25
+
26
+ FrameHandler = Callable[[str, Any], Awaitable[None] | None]
27
+
28
+
29
+ def encode(op: str, **fields: Any) -> bytes:
30
+ """Build a client frame (seq 0, ignored by the server) for one op."""
31
+ frame = pb.Frame(seq=0)
32
+ target = getattr(frame, op) # touching the submessage marks the oneof as set
33
+ for key, value in fields.items():
34
+ setattr(target, key, value)
35
+ return frame.SerializeToString()
36
+
37
+
38
+ def op_name(frame: pb.Frame) -> str:
39
+ return frame.WhichOneof("op") or ""
40
+
41
+
42
+ class GatewayClosed(Exception):
43
+ """The socket went away; the bot reconnects with a fresh token."""
44
+
45
+
46
+ class Gateway:
47
+ """A single connection. Construct per attempt; `run` returns when the socket closes."""
48
+
49
+ def __init__(
50
+ self,
51
+ url: str,
52
+ access_token: str,
53
+ handler: FrameHandler,
54
+ *,
55
+ proof: str = "",
56
+ logger: Any = None,
57
+ ):
58
+ self.url = url
59
+ self.access_token = access_token
60
+ self.handler = handler
61
+ # Empty for a bot token; base64url HMAC over the access token for a session token.
62
+ self.proof = proof
63
+ self.log = logger
64
+ self.ready: asyncio.Future | None = None
65
+ self.heartbeat_ms = 30_000
66
+ self._ws: aiohttp.ClientWebSocketResponse | None = None
67
+ self._nonce = 0
68
+
69
+ def _next_nonce(self) -> str:
70
+ self._nonce += 1
71
+ return f"bot-{self._nonce}"
72
+
73
+ async def send(self, op: str, **fields: Any) -> None:
74
+ if self._ws is None:
75
+ raise GatewayClosed("not connected")
76
+ payload = encode(op, **fields)
77
+ if len(payload) > MAX_FRAME_BYTES:
78
+ raise ValueError(f"frame too large ({len(payload)} bytes)")
79
+ await self._ws.send_bytes(payload)
80
+
81
+ async def send_message(self, channel_id: int, content: str) -> str:
82
+ if len(content) > MAX_MESSAGE_CHARS:
83
+ raise ValueError(f"message too long ({len(content)} > {MAX_MESSAGE_CHARS})")
84
+ nonce = self._next_nonce()
85
+ await self.send("send_message", channel_id=channel_id, nonce=nonce, content=content)
86
+ return nonce
87
+
88
+ async def run(self) -> None:
89
+ loop = asyncio.get_running_loop()
90
+ self.ready = loop.create_future()
91
+ async with aiohttp.ClientSession() as session:
92
+ async with session.ws_connect(self.url, max_msg_size=MAX_FRAME_BYTES) as ws:
93
+ self._ws = ws
94
+ await self.send(
95
+ "hello",
96
+ access_token=self.access_token,
97
+ protocol_version=PROTOCOL_VERSION,
98
+ proof=self.proof,
99
+ )
100
+ heartbeat = asyncio.create_task(self._heartbeat())
101
+ try:
102
+ async for message in ws:
103
+ if message.type == aiohttp.WSMsgType.BINARY:
104
+ await self._dispatch(message.data)
105
+ elif message.type in (
106
+ aiohttp.WSMsgType.CLOSE,
107
+ aiohttp.WSMsgType.CLOSED,
108
+ aiohttp.WSMsgType.ERROR,
109
+ ):
110
+ break
111
+ elif message.type == aiohttp.WSMsgType.TEXT:
112
+ raise GatewayClosed("server sent a text frame")
113
+ finally:
114
+ heartbeat.cancel()
115
+ self._ws = None
116
+ # aiohttp's loop ends on close; treat it as a disconnect so the bot reconnects.
117
+ raise GatewayClosed("socket closed")
118
+
119
+ async def _heartbeat(self) -> None:
120
+ while True:
121
+ await asyncio.sleep(max(1.0, self.heartbeat_ms / 1000 / 2))
122
+ try:
123
+ await self.send("ping", client_time_ms=int(time.time() * 1000))
124
+ except (GatewayClosed, ConnectionError):
125
+ return
126
+
127
+ async def _dispatch(self, data: bytes) -> None:
128
+ if len(data) > MAX_FRAME_BYTES:
129
+ raise GatewayClosed("oversize frame")
130
+ frame = pb.Frame.FromString(data)
131
+ name = op_name(frame)
132
+ if not name:
133
+ return
134
+ if name == "ready":
135
+ self.heartbeat_ms = frame.ready.heartbeat_ms or self.heartbeat_ms
136
+ if self.ready and not self.ready.done:
137
+ self.ready.set_result(frame.ready)
138
+ elif name == "error":
139
+ error = frame.error
140
+ if self.log:
141
+ self.log.warning("gateway error %s: %s", error.code, error.message)
142
+ if error.code == pb.ERROR_CODE_UNAUTHORIZED:
143
+ raise GatewayClosed("unauthorized")
144
+ result = self.handler(name, getattr(frame, name))
145
+ if asyncio.iscoroutine(result):
146
+ await result
yapbot/py.typed ADDED
File without changes