morsel-bot 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.
- morsel_bot/__init__.py +78 -0
- morsel_bot/_base58.py +32 -0
- morsel_bot/api.py +278 -0
- morsel_bot/auth.py +49 -0
- morsel_bot/bot.py +1105 -0
- morsel_bot/context.py +282 -0
- morsel_bot/crypto.py +203 -0
- morsel_bot/fmt.py +94 -0
- morsel_bot/groups.py +345 -0
- morsel_bot/inline.py +350 -0
- morsel_bot/keyboard.py +193 -0
- morsel_bot/media.py +169 -0
- morsel_bot/payload.py +919 -0
- morsel_bot/payments.py +206 -0
- morsel_bot/py.typed +0 -0
- morsel_bot/queue.py +108 -0
- morsel_bot/store.py +100 -0
- morsel_bot/stream.py +209 -0
- morsel_bot/token.py +110 -0
- morsel_bot/webhook.py +162 -0
- morsel_bot-0.1.0.dist-info/METADATA +343 -0
- morsel_bot-0.1.0.dist-info/RECORD +24 -0
- morsel_bot-0.1.0.dist-info/WHEEL +4 -0
- morsel_bot-0.1.0.dist-info/licenses/LICENSE +21 -0
morsel_bot/__init__.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""
|
|
2
|
+
morsel_bot: run a Morsel Chats bot from your own server. End-to-end encrypted: the Morsel API relays ciphertext
|
|
3
|
+
only; this SDK encrypts and decrypts with the bot's key, byte for byte as the Morsel app does.
|
|
4
|
+
|
|
5
|
+
from morsel_bot import Bot, InlineKeyboard
|
|
6
|
+
|
|
7
|
+
bot = Bot(os.environ["MORSEL_BOT_TOKEN"])
|
|
8
|
+
|
|
9
|
+
@bot.command("start")
|
|
10
|
+
async def start(ctx):
|
|
11
|
+
await ctx.reply("Hi", keyboard=InlineKeyboard().text("Price", "price"))
|
|
12
|
+
|
|
13
|
+
bot.run()
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from .api import DEFAULT_API, Api, ApiError, RateLimited
|
|
17
|
+
from .bot import Bot
|
|
18
|
+
from .context import CallbackQuery, Chat, Context, GroupEvent, Message, SentMessage
|
|
19
|
+
from .fmt import FormattedText, bold, code, fmt, italic, link, pre, spoiler, strike, underline
|
|
20
|
+
from .inline import ChosenInlineResult, InlineQuery, InlineResult
|
|
21
|
+
from .keyboard import InlineKeyboard, KeyboardError, ReplyKeyboard
|
|
22
|
+
from .payments import DEFAULT_RPC, PaymentError, PaymentVerifier, VerifiedPayment
|
|
23
|
+
from .queue import SendQueue
|
|
24
|
+
from .store import FileStore, MemoryStore, SeqStore
|
|
25
|
+
from .stream import StreamStopped
|
|
26
|
+
from .token import BotKeys, TokenError, generate_token, parse_token, registration_proof, rotation_proof, token_of_seed
|
|
27
|
+
from .webhook import WebhookApp, sign_webhook, verify_signature
|
|
28
|
+
|
|
29
|
+
__version__ = "0.1.0"
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"DEFAULT_API",
|
|
33
|
+
"DEFAULT_RPC",
|
|
34
|
+
"Api",
|
|
35
|
+
"ApiError",
|
|
36
|
+
"Bot",
|
|
37
|
+
"BotKeys",
|
|
38
|
+
"CallbackQuery",
|
|
39
|
+
"Chat",
|
|
40
|
+
"ChosenInlineResult",
|
|
41
|
+
"Context",
|
|
42
|
+
"FileStore",
|
|
43
|
+
"FormattedText",
|
|
44
|
+
"GroupEvent",
|
|
45
|
+
"InlineKeyboard",
|
|
46
|
+
"InlineQuery",
|
|
47
|
+
"InlineResult",
|
|
48
|
+
"KeyboardError",
|
|
49
|
+
"MemoryStore",
|
|
50
|
+
"Message",
|
|
51
|
+
"PaymentError",
|
|
52
|
+
"PaymentVerifier",
|
|
53
|
+
"RateLimited",
|
|
54
|
+
"ReplyKeyboard",
|
|
55
|
+
"SendQueue",
|
|
56
|
+
"SentMessage",
|
|
57
|
+
"SeqStore",
|
|
58
|
+
"StreamStopped",
|
|
59
|
+
"TokenError",
|
|
60
|
+
"VerifiedPayment",
|
|
61
|
+
"WebhookApp",
|
|
62
|
+
"bold",
|
|
63
|
+
"code",
|
|
64
|
+
"fmt",
|
|
65
|
+
"generate_token",
|
|
66
|
+
"italic",
|
|
67
|
+
"link",
|
|
68
|
+
"parse_token",
|
|
69
|
+
"pre",
|
|
70
|
+
"registration_proof",
|
|
71
|
+
"rotation_proof",
|
|
72
|
+
"sign_webhook",
|
|
73
|
+
"spoiler",
|
|
74
|
+
"strike",
|
|
75
|
+
"token_of_seed",
|
|
76
|
+
"underline",
|
|
77
|
+
"verify_signature",
|
|
78
|
+
]
|
morsel_bot/_base58.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Base58 (the Bitcoin alphabet, as Solana and bs58 use it). Small and dependency free."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
6
|
+
_INDEX = {c: i for i, c in enumerate(ALPHABET)}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def b58encode(data: bytes) -> str:
|
|
10
|
+
"""Encode bytes as base58 (leading zero bytes become leading '1's, as bs58 does)."""
|
|
11
|
+
n = int.from_bytes(data, "big")
|
|
12
|
+
out = []
|
|
13
|
+
while n > 0:
|
|
14
|
+
n, r = divmod(n, 58)
|
|
15
|
+
out.append(ALPHABET[r])
|
|
16
|
+
zeros = len(data) - len(data.lstrip(b"\0"))
|
|
17
|
+
return "1" * zeros + "".join(reversed(out))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def b58decode(text: str) -> bytes:
|
|
21
|
+
"""Decode base58; raises ValueError on a character outside the alphabet."""
|
|
22
|
+
if not isinstance(text, str):
|
|
23
|
+
raise ValueError("not a string")
|
|
24
|
+
n = 0
|
|
25
|
+
for c in text:
|
|
26
|
+
i = _INDEX.get(c)
|
|
27
|
+
if i is None:
|
|
28
|
+
raise ValueError("not base58")
|
|
29
|
+
n = n * 58 + i
|
|
30
|
+
body = n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b""
|
|
31
|
+
zeros = len(text) - len(text.lstrip("1"))
|
|
32
|
+
return b"\0" * zeros + body
|
morsel_bot/api.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The HTTP side: every call signed by the bot's key (MorselWallet2, exactly the chat auth), JSON in and out, the
|
|
3
|
+
backend's error shape ({ success: false, error, message, retryAfter? }) raised as ApiError. Only ciphertext goes
|
|
4
|
+
up. `bot.api.call(method, path, body=..., query=...)` reaches any endpoint raw.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from typing import Any, Mapping, Sequence
|
|
11
|
+
from urllib.parse import quote
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from .auth import auth_header
|
|
16
|
+
from .crypto import js_json
|
|
17
|
+
from .token import BotKeys
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger("morsel_bot")
|
|
20
|
+
|
|
21
|
+
DEFAULT_API = "https://api.morselwallet.app"
|
|
22
|
+
USER_AGENT = "morsel-bot-py"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ApiError(Exception):
|
|
26
|
+
"""A refused or failed call. `code` is the backend's (BOT_SUSPENDED, BOT_REVOKED, BOT_CANNOT_INITIATE, ...)."""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self, message: str, *, status: int = 0, code: str = "NETWORK", data: Mapping[str, Any] | None = None, retry_after: float | None = None
|
|
30
|
+
) -> None:
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.status = status
|
|
33
|
+
self.code = code
|
|
34
|
+
self.data = dict(data or {})
|
|
35
|
+
self.retry_after = retry_after
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def retryable(self) -> bool:
|
|
39
|
+
return self.status == 0 or self.status >= 500 or self.status == 429
|
|
40
|
+
|
|
41
|
+
def __repr__(self) -> str:
|
|
42
|
+
return f"ApiError({self.status}, {self.code!r}, {str(self)!r})"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class RateLimited(ApiError):
|
|
46
|
+
"""429: wait `retry_after` seconds (the send queue does this for you)."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
#: Codes after which retrying with this token is pointless: the stream stops and says why.
|
|
50
|
+
FATAL_CODES = frozenset({"BOT_SUSPENDED", "BOT_REVOKED", "BOT_AUTH_V2", "BOT_GONE", "NOT_A_BOT", "BOT_NOT_FOUND"})
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _qs(query: Mapping[str, Any] | None) -> str:
|
|
54
|
+
if not query:
|
|
55
|
+
return ""
|
|
56
|
+
parts = [
|
|
57
|
+
f"{quote(str(k), safe='-_.!~*()')}={quote(str(v), safe='-_.!~*()')}"
|
|
58
|
+
for k, v in query.items()
|
|
59
|
+
if v is not None and v != ""
|
|
60
|
+
]
|
|
61
|
+
return ("?" + "&".join(parts)) if parts else ""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _seg(v: str) -> str:
|
|
65
|
+
return quote(str(v), safe="-_.!~*()")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Api:
|
|
69
|
+
"""Raw, signed calls to the Morsel API. One per bot; reuses one HTTP connection pool."""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
keys: BotKeys,
|
|
74
|
+
base_url: str = DEFAULT_API,
|
|
75
|
+
*,
|
|
76
|
+
client: httpx.AsyncClient | None = None,
|
|
77
|
+
timeout: float = 12.0,
|
|
78
|
+
) -> None:
|
|
79
|
+
self.keys = keys
|
|
80
|
+
self.base_url = base_url.rstrip("/")
|
|
81
|
+
self._client = client
|
|
82
|
+
self._own_client = client is None
|
|
83
|
+
self.timeout = timeout
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def client(self) -> httpx.AsyncClient:
|
|
87
|
+
if self._client is None:
|
|
88
|
+
self._client = httpx.AsyncClient(timeout=self.timeout, headers={"User-Agent": USER_AGENT}, follow_redirects=False)
|
|
89
|
+
return self._client
|
|
90
|
+
|
|
91
|
+
async def aclose(self) -> None:
|
|
92
|
+
if self._client is not None and self._own_client:
|
|
93
|
+
await self._client.aclose()
|
|
94
|
+
self._client = None
|
|
95
|
+
|
|
96
|
+
async def call(
|
|
97
|
+
self,
|
|
98
|
+
method: str,
|
|
99
|
+
path: str,
|
|
100
|
+
*,
|
|
101
|
+
body: Mapping[str, Any] | None = None,
|
|
102
|
+
query: Mapping[str, Any] | None = None,
|
|
103
|
+
signed: bool = True,
|
|
104
|
+
timeout: float | None = None,
|
|
105
|
+
) -> dict[str, Any]:
|
|
106
|
+
"""One request: `path` from the API root (/v1/...). Returns the JSON answer; raises ApiError."""
|
|
107
|
+
method = method.upper()
|
|
108
|
+
target = path + _qs(query)
|
|
109
|
+
raw = js_json(body) if body is not None else None
|
|
110
|
+
headers: dict[str, str] = {}
|
|
111
|
+
if raw is not None:
|
|
112
|
+
headers["Content-Type"] = "application/json"
|
|
113
|
+
if signed:
|
|
114
|
+
headers["Authorization"] = auth_header(self.keys, method=method, path=target, body=raw or "")
|
|
115
|
+
try:
|
|
116
|
+
res = await self.client.request(
|
|
117
|
+
method,
|
|
118
|
+
self.base_url + target,
|
|
119
|
+
content=raw.encode("utf-8") if raw is not None else None,
|
|
120
|
+
headers=headers,
|
|
121
|
+
timeout=timeout if timeout is not None else self.timeout,
|
|
122
|
+
)
|
|
123
|
+
except httpx.HTTPError as e:
|
|
124
|
+
raise ApiError(f"The Morsel API can't be reached ({type(e).__name__})", code="NETWORK") from None
|
|
125
|
+
try:
|
|
126
|
+
data = res.json()
|
|
127
|
+
except ValueError:
|
|
128
|
+
data = None
|
|
129
|
+
if not isinstance(data, dict):
|
|
130
|
+
data = {}
|
|
131
|
+
if res.status_code >= 400 or data.get("success") is False:
|
|
132
|
+
code = str(data.get("error") or "HTTP")
|
|
133
|
+
msg = str(data.get("message") or f"Request failed ({res.status_code})")
|
|
134
|
+
if res.status_code == 429:
|
|
135
|
+
ra = data.get("retryAfter")
|
|
136
|
+
if not isinstance(ra, (int, float)) or isinstance(ra, bool):
|
|
137
|
+
try:
|
|
138
|
+
ra = float(res.headers.get("retry-after", "1"))
|
|
139
|
+
except ValueError:
|
|
140
|
+
ra = 1.0
|
|
141
|
+
raise RateLimited(msg, status=429, code=code, data=data, retry_after=max(0.0, float(ra)))
|
|
142
|
+
raise ApiError(msg, status=res.status_code, code=code, data=data)
|
|
143
|
+
return data
|
|
144
|
+
|
|
145
|
+
# ── the bot's own registry record ─────────────────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
async def get_me(self) -> dict[str, Any]:
|
|
148
|
+
return await self.call("GET", "/v1/bots/me")
|
|
149
|
+
|
|
150
|
+
async def set_commands(self, commands: list[dict[str, Any]]) -> dict[str, Any]:
|
|
151
|
+
return await self.call("PUT", "/v1/bots/me/commands", body={"commands": commands})
|
|
152
|
+
|
|
153
|
+
async def set_webhook(self, url: str, secret: str) -> dict[str, Any]:
|
|
154
|
+
return await self.call("PUT", "/v1/bots/me/webhook", body={"url": url, "secret": secret})
|
|
155
|
+
|
|
156
|
+
async def delete_webhook(self) -> dict[str, Any]:
|
|
157
|
+
return await self.call("DELETE", "/v1/bots/me/webhook")
|
|
158
|
+
|
|
159
|
+
async def get_webhook(self) -> dict[str, Any]:
|
|
160
|
+
return await self.call("GET", "/v1/bots/me/webhook")
|
|
161
|
+
|
|
162
|
+
async def update_profile(self, fields: Mapping[str, Any]) -> dict[str, Any]:
|
|
163
|
+
"""PATCH /v1/bots/:address, signed by the bot: name, about, description, avatar, commands,
|
|
164
|
+
groupPrivacy, inline, inlinePlaceholder, inlineFeedback."""
|
|
165
|
+
return await self.call("PATCH", f"/v1/bots/{_seg(self.keys.address)}", body=dict(fields))
|
|
166
|
+
|
|
167
|
+
async def set_avatar(self, data_b64: str) -> dict[str, Any]:
|
|
168
|
+
"""PUT /v1/bots/:address/avatar {data}: the picture (PNG, JPEG or WebP, at most 1 MB, base64), re-encoded by
|
|
169
|
+
the server. Answers {bot, avatar: {url, small}}."""
|
|
170
|
+
return await self.call("PUT", f"/v1/bots/{_seg(self.keys.address)}/avatar", body={"data": data_b64}, timeout=60.0)
|
|
171
|
+
|
|
172
|
+
async def remove_avatar(self) -> dict[str, Any]:
|
|
173
|
+
"""DELETE /v1/bots/:address/avatar: back to no picture."""
|
|
174
|
+
return await self.call("DELETE", f"/v1/bots/{_seg(self.keys.address)}/avatar")
|
|
175
|
+
|
|
176
|
+
async def bot_profile(self, address_or_username: str, *, by_username: bool = False) -> dict[str, Any]:
|
|
177
|
+
path = f"/v1/bots/by-username/{_seg(address_or_username)}" if by_username else f"/v1/bots/{_seg(address_or_username)}"
|
|
178
|
+
return await self.call("GET", path, signed=False)
|
|
179
|
+
|
|
180
|
+
async def pending_inline(self) -> list[dict[str, Any]]:
|
|
181
|
+
"""The bot's inline queries of the last minute (catch-up after a short outage)."""
|
|
182
|
+
res = await self.call("GET", "/v1/bots/me/inline")
|
|
183
|
+
return [q for q in res.get("queries") or [] if isinstance(q, dict)]
|
|
184
|
+
|
|
185
|
+
async def answer_inline(self, qid: str, nonce: str, cipher: str, media: Sequence[str] = ()) -> dict[str, Any]:
|
|
186
|
+
"""`media`: the bot's own chat files its photo results carry (offered to the person who asked, for an hour)."""
|
|
187
|
+
body: dict[str, Any] = {"nonce": nonce, "cipher": cipher}
|
|
188
|
+
if media:
|
|
189
|
+
body["media"] = list(media)
|
|
190
|
+
return await self.call("POST", f"/v1/bots/me/inline/{_seg(qid)}", body=body)
|
|
191
|
+
|
|
192
|
+
# ── chats ─────────────────────────────────────────────────────────────────────────────────
|
|
193
|
+
|
|
194
|
+
async def send(
|
|
195
|
+
self,
|
|
196
|
+
*,
|
|
197
|
+
to: str,
|
|
198
|
+
cid: str,
|
|
199
|
+
nonce: str,
|
|
200
|
+
cipher: str,
|
|
201
|
+
ctl: str | None = None,
|
|
202
|
+
ref: str | None = None,
|
|
203
|
+
media: list[str] | None = None,
|
|
204
|
+
gid: str | None = None,
|
|
205
|
+
) -> dict[str, Any]:
|
|
206
|
+
"""A 1:1 row. `gid` (with ctl 'cba'): the answer to a press in that group, sent to the presser only."""
|
|
207
|
+
body: dict[str, Any] = {"to": to, "cid": cid, "nonce": nonce, "cipher": cipher}
|
|
208
|
+
if ctl:
|
|
209
|
+
body["ctl"] = ctl
|
|
210
|
+
if ref is not None:
|
|
211
|
+
body["ref"] = ref
|
|
212
|
+
if gid:
|
|
213
|
+
body["gid"] = gid
|
|
214
|
+
elif media:
|
|
215
|
+
body["media"] = media
|
|
216
|
+
return await self.call("POST", "/v1/chat/messages", body=body)
|
|
217
|
+
|
|
218
|
+
async def sync(self, since: str, *, limit: int = 200) -> dict[str, Any]:
|
|
219
|
+
return await self.call("GET", "/v1/chat/sync", query={"since": since, "limit": limit, "v": 3})
|
|
220
|
+
|
|
221
|
+
async def thread(self, peer: str, *, after: str | None = None, before: str | None = None, limit: int | None = None) -> dict[str, Any]:
|
|
222
|
+
return await self.call("GET", f"/v1/chat/thread/{_seg(peer)}", query={"before": before, "after": after, "limit": limit, "v": 3})
|
|
223
|
+
|
|
224
|
+
async def ticket(self) -> str:
|
|
225
|
+
res = await self.call("POST", "/v1/chat/stream/ticket", body={})
|
|
226
|
+
t = res.get("ticket")
|
|
227
|
+
if not isinstance(t, str):
|
|
228
|
+
raise ApiError("No stream ticket in the answer", code="BAD_ANSWER")
|
|
229
|
+
return t
|
|
230
|
+
|
|
231
|
+
def stream_url(self, ticket: str) -> str:
|
|
232
|
+
return f"{self.base_url}/v1/chat/stream{_qs({'ticket': ticket, 'v': 3, 'hb': 1})}"
|
|
233
|
+
|
|
234
|
+
async def typing(self, peer: str) -> dict[str, Any]:
|
|
235
|
+
return await self.call("POST", "/v1/chat/typing", body={"peer": peer})
|
|
236
|
+
|
|
237
|
+
async def read(self, peer: str, up_to: str) -> dict[str, Any]:
|
|
238
|
+
return await self.call("POST", "/v1/chat/read", body={"peer": peer, "upTo": up_to})
|
|
239
|
+
|
|
240
|
+
async def unsend(self, message_id: str) -> dict[str, Any]:
|
|
241
|
+
return await self.call("POST", f"/v1/chat/messages/{_seg(message_id)}/unsend", body={})
|
|
242
|
+
|
|
243
|
+
# ── groups ────────────────────────────────────────────────────────────────────────────────
|
|
244
|
+
|
|
245
|
+
async def group_send(
|
|
246
|
+
self,
|
|
247
|
+
gid: str,
|
|
248
|
+
*,
|
|
249
|
+
cid: str,
|
|
250
|
+
epoch: int,
|
|
251
|
+
nonce: str,
|
|
252
|
+
cipher: str,
|
|
253
|
+
ctl: str | None = None,
|
|
254
|
+
ref: str | None = None,
|
|
255
|
+
media: list[str] | None = None,
|
|
256
|
+
) -> dict[str, Any]:
|
|
257
|
+
body: dict[str, Any] = {"cid": cid, "epoch": epoch, "nonce": nonce, "cipher": cipher}
|
|
258
|
+
if ctl:
|
|
259
|
+
body["ctl"] = ctl
|
|
260
|
+
body["ref"] = ref
|
|
261
|
+
elif media:
|
|
262
|
+
body["media"] = media
|
|
263
|
+
return await self.call("POST", f"/v1/chat/groups/{_seg(gid)}/messages", body=body)
|
|
264
|
+
|
|
265
|
+
async def group_detail(self, gid: str) -> dict[str, Any]:
|
|
266
|
+
return await self.call("GET", f"/v1/chat/groups/{_seg(gid)}")
|
|
267
|
+
|
|
268
|
+
async def group_events(self, gid: str, *, after: int = 0, limit: int | None = None) -> dict[str, Any]:
|
|
269
|
+
return await self.call("GET", f"/v1/chat/groups/{_seg(gid)}/events", query={"after": after, "limit": limit})
|
|
270
|
+
|
|
271
|
+
async def group_typing(self, gid: str) -> dict[str, Any]:
|
|
272
|
+
return await self.call("POST", f"/v1/chat/groups/{_seg(gid)}/typing", body={})
|
|
273
|
+
|
|
274
|
+
async def group_leave(self, gid: str, event: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
275
|
+
return await self.call("POST", f"/v1/chat/groups/{_seg(gid)}/leave", body={"event": dict(event)} if event else {})
|
|
276
|
+
|
|
277
|
+
async def group_accept(self, gid: str, event: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
278
|
+
return await self.call("POST", f"/v1/chat/groups/{_seg(gid)}/accept", body={"event": dict(event)} if event else {})
|
morsel_bot/auth.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Request signing, exactly the chat auth (app chat-api.js, backend services/chat/auth.ts, version 2):
|
|
3
|
+
|
|
4
|
+
Authorization: MorselWallet2 <address>:<unix seconds>:<nonce>:<base58 signature>
|
|
5
|
+
signed: morsel-chat-v2\\n<address>\\n<seconds>\\n<nonce>\\n<METHOD>\\n<path and query>\\n<base64url sha-256 of body>
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import hashlib
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
from ._base58 import b58encode
|
|
16
|
+
from .token import BotKeys
|
|
17
|
+
|
|
18
|
+
_NONCE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def chat_auth_message_v2(wallet: str, seconds: int, nonce: str, *, method: str, path: str, body_hash: str) -> str:
|
|
22
|
+
return f"morsel-chat-v2\n{wallet}\n{seconds}\n{nonce}\n{method.upper()}\n{path}\n{body_hash}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def chat_body_hash(body: str | bytes | None) -> str:
|
|
26
|
+
"""SHA-256 of the body exactly as sent, base64url without padding."""
|
|
27
|
+
raw = body.encode("utf-8") if isinstance(body, str) else (body or b"")
|
|
28
|
+
return base64.urlsafe_b64encode(hashlib.sha256(raw).digest()).decode("ascii").rstrip("=")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def new_auth_nonce() -> str:
|
|
32
|
+
"""16 characters of [A-Za-z0-9], as the app makes them."""
|
|
33
|
+
return "".join(_NONCE_CHARS[b % len(_NONCE_CHARS)] for b in os.urandom(16))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def auth_header(
|
|
37
|
+
keys: BotKeys,
|
|
38
|
+
*,
|
|
39
|
+
method: str,
|
|
40
|
+
path: str,
|
|
41
|
+
body: str | bytes | None = None,
|
|
42
|
+
seconds: int | None = None,
|
|
43
|
+
nonce: str | None = None,
|
|
44
|
+
) -> str:
|
|
45
|
+
"""The Authorization header for one request (`path` is the path and query as on the request line)."""
|
|
46
|
+
s = int(time.time()) if seconds is None else int(seconds)
|
|
47
|
+
n = nonce or new_auth_nonce()
|
|
48
|
+
msg = chat_auth_message_v2(keys.address, s, n, method=method or "GET", path=path, body_hash=chat_body_hash(body))
|
|
49
|
+
return f"MorselWallet2 {keys.address}:{s}:{n}:{b58encode(keys.sign(msg.encode('utf-8')))}"
|