morsel-bot 0.1.0__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.
- morsel_bot-0.1.0/.gitignore +10 -0
- morsel_bot-0.1.0/CHANGELOG.md +28 -0
- morsel_bot-0.1.0/LICENSE +21 -0
- morsel_bot-0.1.0/PKG-INFO +343 -0
- morsel_bot-0.1.0/README.md +310 -0
- morsel_bot-0.1.0/examples/deploy/Dockerfile +12 -0
- morsel_bot-0.1.0/examples/deploy/docker-compose.yml +11 -0
- morsel_bot-0.1.0/examples/deploy/env.example +5 -0
- morsel_bot-0.1.0/examples/deploy/fly.toml +18 -0
- morsel_bot-0.1.0/examples/deploy/morsel-bot.service +27 -0
- morsel_bot-0.1.0/examples/deploy/requirements.txt +1 -0
- morsel_bot-0.1.0/examples/echo.py +23 -0
- morsel_bot-0.1.0/examples/group_bot.py +54 -0
- morsel_bot-0.1.0/examples/inline_bot.py +49 -0
- morsel_bot-0.1.0/examples/inline_pictures.py +29 -0
- morsel_bot-0.1.0/examples/pay.py +49 -0
- morsel_bot-0.1.0/examples/price.py +62 -0
- morsel_bot-0.1.0/examples/webhook_asgi.py +29 -0
- morsel_bot-0.1.0/pyproject.toml +57 -0
- morsel_bot-0.1.0/src/morsel_bot/__init__.py +78 -0
- morsel_bot-0.1.0/src/morsel_bot/_base58.py +32 -0
- morsel_bot-0.1.0/src/morsel_bot/api.py +278 -0
- morsel_bot-0.1.0/src/morsel_bot/auth.py +49 -0
- morsel_bot-0.1.0/src/morsel_bot/bot.py +1105 -0
- morsel_bot-0.1.0/src/morsel_bot/context.py +282 -0
- morsel_bot-0.1.0/src/morsel_bot/crypto.py +203 -0
- morsel_bot-0.1.0/src/morsel_bot/fmt.py +94 -0
- morsel_bot-0.1.0/src/morsel_bot/groups.py +345 -0
- morsel_bot-0.1.0/src/morsel_bot/inline.py +350 -0
- morsel_bot-0.1.0/src/morsel_bot/keyboard.py +193 -0
- morsel_bot-0.1.0/src/morsel_bot/media.py +169 -0
- morsel_bot-0.1.0/src/morsel_bot/payload.py +919 -0
- morsel_bot-0.1.0/src/morsel_bot/payments.py +206 -0
- morsel_bot-0.1.0/src/morsel_bot/py.typed +0 -0
- morsel_bot-0.1.0/src/morsel_bot/queue.py +108 -0
- morsel_bot-0.1.0/src/morsel_bot/store.py +100 -0
- morsel_bot-0.1.0/src/morsel_bot/stream.py +209 -0
- morsel_bot-0.1.0/src/morsel_bot/token.py +110 -0
- morsel_bot-0.1.0/src/morsel_bot/webhook.py +162 -0
- morsel_bot-0.1.0/tests/conftest.py +253 -0
- morsel_bot-0.1.0/tests/test_avatar.py +49 -0
- morsel_bot-0.1.0/tests/test_groups.py +192 -0
- morsel_bot-0.1.0/tests/test_inline.py +93 -0
- morsel_bot-0.1.0/tests/test_inline_media.py +114 -0
- morsel_bot-0.1.0/tests/test_media.py +65 -0
- morsel_bot-0.1.0/tests/test_payload.py +155 -0
- morsel_bot-0.1.0/tests/test_payments.py +108 -0
- morsel_bot-0.1.0/tests/test_queue.py +103 -0
- morsel_bot-0.1.0/tests/test_routing.py +200 -0
- morsel_bot-0.1.0/tests/test_shared_vectors.py +192 -0
- morsel_bot-0.1.0/tests/test_stream.py +186 -0
- morsel_bot-0.1.0/tests/test_vectors.py +159 -0
- morsel_bot-0.1.0/tests/test_webhook.py +105 -0
- morsel_bot-0.1.0/tests/vectors/README.md +7 -0
- morsel_bot-0.1.0/tests/vectors/app-vectors.json +1128 -0
- morsel_bot-0.1.0/tests/vectors/shared/app-notify-vectors.json +685 -0
- morsel_bot-0.1.0/tests/vectors/shared/auth.json +79 -0
- morsel_bot-0.1.0/tests/vectors/shared/crypto.json +1100 -0
- morsel_bot-0.1.0/tests/vectors/shared/group.json +142 -0
- morsel_bot-0.1.0/tests/vectors/shared/media.json +61 -0
- morsel_bot-0.1.0/tests/vectors/shared/payload.json +2817 -0
- morsel_bot-0.1.0/tests/vectors/shared/token.json +62 -0
- morsel_bot-0.1.0/tests/vectors/shared/webhook.json +19 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- `bot.set_avatar(bytes | path, mime=None)` and `bot.remove_avatar()`: upload the bot's picture (PUT / DELETE
|
|
8
|
+
`/v1/bots/:address/avatar`).
|
|
9
|
+
|
|
10
|
+
- `Bot` (asyncio): `command`, `hears`, `callback`, `on`, `inline`, `chosen_inline`, `middleware` / `use`,
|
|
11
|
+
`error` / `catch`; `run()` / `start()` with stream, sync catch-up from a saved `seq`, named heartbeats,
|
|
12
|
+
reconnect with backoff; `asgi_webhook()` (HMAC-SHA256 signatures, 5 minute skew, duplicate deliveries dropped).
|
|
13
|
+
- End-to-end encryption byte for byte as the Morsel app: ed25519 to X25519, pair key `morsel-chat-v1`,
|
|
14
|
+
XSalsa20-Poly1305, 512-byte padding; `MorselWallet2` request signing; payload sanitization and row checks.
|
|
15
|
+
- Bot payloads: `fmt` entities (`fmt`, `bold`, `italic`, `underline`, `strike`, `code`, `pre`, `link`,
|
|
16
|
+
`spoiler`), `InlineKeyboard` (callback, url, mini app, copy, pay), `ReplyKeyboard`, edits, button answers.
|
|
17
|
+
- Groups: epoch keys unwrapped locally, signed group messages, signature checks, privacy mode, answers to the
|
|
18
|
+
presser only, signed leave.
|
|
19
|
+
- Inline mode: queries and answers sealed under the pair key, paging, cache, switch to bot, chosen results.
|
|
20
|
+
- Inline media: `InlineResult.photo` (encrypted, uploaded and offered to the person who asked; `media` beside the
|
|
21
|
+
answer) and `InlineResult.gif` (GIPHY only); media payloads keep `thumb`, `round`, `wave` and `via` as the app does.
|
|
22
|
+
- Payments: requests, and `payment` events only after the transaction is finalized on chain (Solana, Cookie
|
|
23
|
+
Chain and the other networks the app knows; RPCs configurable).
|
|
24
|
+
- Photos and files: the app's media encryption (Padmé, 64 KiB chunks), upload and download.
|
|
25
|
+
- Per-chat send queue honouring 429 `retryAfter`; `MemoryStore` and `FileStore` for `seq`.
|
|
26
|
+
- Token parsing with checksum (`mbot1_`), registration (username signed lowercase, as stored) and rotation proofs.
|
|
27
|
+
- Matches the committed backend: sync `events`, `bot_added` / `bot_removed` with `gid`, group press answers 1:1 with
|
|
28
|
+
`gid`, fatal BOT_REVOKED / BOT_SUSPENDED / BOT_AUTH_V2 / BOT_GONE, no group typing; end-to-end test against it.
|
morsel_bot-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Morsel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: morsel-bot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Run end-to-end encrypted Morsel Chats bots from your own server (asyncio).
|
|
5
|
+
Project-URL: Homepage, https://morselwallet.app
|
|
6
|
+
Project-URL: Repository, https://github.com/Morsel-Labs/morsel-bot
|
|
7
|
+
Project-URL: Issues, https://github.com/Morsel-Labs/morsel-bot/issues
|
|
8
|
+
Author: Morsel
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: asyncio,bot,chat,e2ee,morsel,solana
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Communications :: Chat
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Requires-Dist: httpx>=0.25
|
|
26
|
+
Requires-Dist: pynacl>=1.5
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: build>=1; extra == 'dev'
|
|
29
|
+
Requires-Dist: mypy>=1.8; extra == 'dev'
|
|
30
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# morsel-bot
|
|
35
|
+
|
|
36
|
+
Bots for [Morsel](https://morselwallet.app) Chats, in Python (asyncio). End-to-end encrypted: the Morsel API
|
|
37
|
+
only relays ciphertext. Your bot runs on **your** server, holds its own key, and encrypts and decrypts every
|
|
38
|
+
message itself, byte for byte as the Morsel app does.
|
|
39
|
+
|
|
40
|
+
```py
|
|
41
|
+
import os
|
|
42
|
+
from morsel_bot import Bot, InlineKeyboard
|
|
43
|
+
|
|
44
|
+
bot = Bot(os.environ["MORSEL_BOT_TOKEN"])
|
|
45
|
+
|
|
46
|
+
@bot.command("start")
|
|
47
|
+
async def start(ctx):
|
|
48
|
+
await ctx.reply("Hi", keyboard=InlineKeyboard().text("Price", "price"))
|
|
49
|
+
|
|
50
|
+
@bot.callback("price")
|
|
51
|
+
async def price(ctx):
|
|
52
|
+
await ctx.answer("Updated")
|
|
53
|
+
await ctx.edit_text("1 SOL = 100 USD")
|
|
54
|
+
|
|
55
|
+
bot.run()
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Python 3.10 or newer. Dependencies: PyNaCl and httpx. Fully typed (`py.typed`, mypy `--strict` clean).
|
|
59
|
+
|
|
60
|
+
## Quick start
|
|
61
|
+
|
|
62
|
+
1. In the Morsel app: **Settings > Chats > My bots > Create bot**. Pick a username ending in `bot`.
|
|
63
|
+
2. Copy the token (`mbot1_...`). It is shown once. It is the bot's private key: see [Security](#security).
|
|
64
|
+
3. Install and run:
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
python -m venv .venv && . .venv/bin/activate
|
|
68
|
+
pip install morsel-bot
|
|
69
|
+
export MORSEL_BOT_TOKEN='mbot1_...'
|
|
70
|
+
python echo.py # examples/echo.py
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
4. Open the bot in Morsel (search `@yourbot`) and tap **Start**.
|
|
74
|
+
|
|
75
|
+
The bot connects out to the Morsel API (a live stream; no inbound port, no public IP needed), catches up on
|
|
76
|
+
anything it missed since it last ran, and reconnects by itself.
|
|
77
|
+
|
|
78
|
+
## Handlers
|
|
79
|
+
|
|
80
|
+
| Decorator | Runs for |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| `@bot.command("start", "help")` | `/start`, `/help` (and `/start@yourbot` in groups). `ctx.args`, `ctx.payload` |
|
|
83
|
+
| `@bot.hears("gm")` / `@bot.hears(re.compile(...))` | a message equal to / matching it (`ctx.match`) |
|
|
84
|
+
| `@bot.callback("data")` / `@bot.callback(re.compile(...))` / `@bot.callback()` | a button press |
|
|
85
|
+
| `@bot.inline()` / `@bot.inline(re.compile(...))` | an inline query; the handler gets the `InlineQuery` |
|
|
86
|
+
| `@bot.chosen_inline()` | which inline result was picked (inline feedback on) |
|
|
87
|
+
| `@bot.on("message" \| "text" \| "media" \| "request" \| "group_message" \| "private_message" \| "edited" \| "callback" \| "payment" \| "payment_failed" \| "blocked" \| "unblocked" \| "bot_added" \| "bot_removed" \| "inline_query" \| "inline_chosen" \| "event" \| "*")` | those updates |
|
|
88
|
+
| `@bot.middleware` / `bot.use(fn)` | every update: `async def mw(ctx, next): ...; await next()` |
|
|
89
|
+
| `@bot.error` / `bot.catch(fn)` | a handler raised: `async def on_error(err, ctx)` |
|
|
90
|
+
|
|
91
|
+
Handlers run in the order they were registered; the first one that matches handles the update. Plain functions
|
|
92
|
+
work too (not only `async def`).
|
|
93
|
+
|
|
94
|
+
### Context
|
|
95
|
+
|
|
96
|
+
- What it is: `ctx.update_type`, `ctx.chat` (`Chat(id, type)`: the user's address, or a group id), `ctx.from_`
|
|
97
|
+
(the sender's address; also `ctx.sender`), `ctx.lang` (the app's language, e.g. `el`), `ctx.text`,
|
|
98
|
+
`ctx.command`, `ctx.args`, `ctx.payload` (the `/start` deep-link parameter: `morsel://bot/<you>?start=ref_42`),
|
|
99
|
+
`ctx.message`, `ctx.callback` / `ctx.data`, `ctx.match`, `ctx.payment`, `ctx.inline_query`, `ctx.state` (a dict
|
|
100
|
+
for middleware).
|
|
101
|
+
- Answering: `reply(text, keyboard=, reply_keyboard=, no_preview=, quote=)`, `reply_with_photo(bytes, caption=)`,
|
|
102
|
+
`edit(message_id=None, text=, keyboard=)`, `edit_text(text, keyboard=)`, `edit_keyboard(kb)`,
|
|
103
|
+
`answer(text=None, alert=False, url=None)` (a button press), `request_payment(mint=, chain=, amount=, decimals=,
|
|
104
|
+
symbol=, text=)`, `typing()`, `download()` (a file the user sent), `leave()` (a group).
|
|
105
|
+
- Raw: `ctx.api` / `bot.api.call("GET", "/v1/bots/me")` reaches any endpoint, signed.
|
|
106
|
+
|
|
107
|
+
### Keyboards and formatting
|
|
108
|
+
|
|
109
|
+
```py
|
|
110
|
+
from morsel_bot import InlineKeyboard, ReplyKeyboard, fmt, bold, italic, code, link
|
|
111
|
+
|
|
112
|
+
kb = (InlineKeyboard()
|
|
113
|
+
.text("Refresh", "refresh") # callback data, 1-64 bytes
|
|
114
|
+
.url("Docs", "https://example.com") # https only; the app confirms the domain
|
|
115
|
+
.row()
|
|
116
|
+
.app("Open app", "https://app.example.com") # a mini app in the in-app browser
|
|
117
|
+
.copy("Copy address", bot.address)
|
|
118
|
+
.pay("Pay 1 USDC", mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", chain="solana", amount="1", decimals=6, symbol="USDC"))
|
|
119
|
+
|
|
120
|
+
await ctx.reply(fmt("Price: ", bold("1.23 SOL"), " ", link("chart", "https://example.com")), keyboard=kb)
|
|
121
|
+
await ctx.reply("Pick one", reply_keyboard=ReplyKeyboard([["Yes", "No"]]).once().placeholder("Yes or no?"))
|
|
122
|
+
await ctx.reply("Done", reply_keyboard=ReplyKeyboard.remove())
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Text is never markup: `fmt` entities (bold, italic, underline, strike, code, pre, link, spoiler) carry UTF-16
|
|
126
|
+
offsets. Text is cleaned exactly as the app cleans it (control and direction-override characters removed,
|
|
127
|
+
trimmed, at most 1000 characters) and every entity moves with it. Keyboards are checked as you build them (8
|
|
128
|
+
rows of 8, 64 buttons), so a mistake raises in your code instead of disappearing in the app.
|
|
129
|
+
|
|
130
|
+
Edits (`edit_text`, `edit_keyboard`) change the bot's own message in place, keyboard included (for 48 hours, up
|
|
131
|
+
to 100 edits a message). Every button
|
|
132
|
+
press shows a spinner in the app until it is answered: `ctx.answer(...)` does that (a toast, or an alert dialog);
|
|
133
|
+
a press your handler did not answer is answered silently for you (`auto_answer_callbacks=False` turns that off).
|
|
134
|
+
|
|
135
|
+
### Payments
|
|
136
|
+
|
|
137
|
+
```py
|
|
138
|
+
@bot.command("buy")
|
|
139
|
+
async def buy(ctx):
|
|
140
|
+
await ctx.request_payment(mint="native", chain="solana", amount="0.01", decimals=9, symbol="SOL", text="One coffee")
|
|
141
|
+
|
|
142
|
+
@bot.on("payment")
|
|
143
|
+
async def paid(ctx):
|
|
144
|
+
p = ctx.payment # VerifiedPayment: sig, chain, mint, amount (Decimal), amount_base, payer, for_request
|
|
145
|
+
await ctx.reply(f"Received {p.amount} SOL")
|
|
146
|
+
|
|
147
|
+
@bot.on("payment_failed")
|
|
148
|
+
async def failed(ctx):
|
|
149
|
+
await ctx.reply(f"Could not confirm it: {ctx.payment_error.code}")
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
A `payment` event fires only after the SDK checked the transaction on chain through the network's RPC:
|
|
153
|
+
**finalized**, not failed, paid the bot's own address, and (when it answers a request the bot sent) at least the
|
|
154
|
+
amount asked in the token asked. SOL / gas tokens from the balance change, SPL tokens from the token balances the
|
|
155
|
+
bot's address owns. Default RPCs are the app's (public Solana, Cookie Chain's `rpc.morselwallet.app`, Fogo, X1,
|
|
156
|
+
Sonic SVM, Solayer); pass your own with `Bot(token, rpc={"solana": "https://..."})` for anything busy. A
|
|
157
|
+
signature is counted once per process: record `p.sig` in your own database before you deliver anything.
|
|
158
|
+
|
|
159
|
+
### Groups
|
|
160
|
+
|
|
161
|
+
A group manager adds the bot from the group's members screen. The bot gets `bot_added` / `bot_removed`, receives
|
|
162
|
+
the group's epoch keys wrapped for its address (opened locally), and replies with signed group messages, exactly
|
|
163
|
+
as a member's app does. Every incoming group message's signature is checked before a handler sees it.
|
|
164
|
+
|
|
165
|
+
- The bot accepts the group by itself (a join event signed by its key) when it is added; `Bot(...,
|
|
166
|
+
auto_join_groups=False)` to decide yourself with `await bot.join_group(gid)`.
|
|
167
|
+
- **Privacy mode** (on by default): the server delivers only commands, mentions of the bot, replies to it, and
|
|
168
|
+
presses of its buttons. `await bot.set_group_privacy(False)` to receive everything (members are told).
|
|
169
|
+
- A press in a group reaches only the presser and the bot; `ctx.answer()` goes back to the presser alone (a 1:1
|
|
170
|
+
row naming the group), never to the group. Bots don't show "typing" in groups (`typing()` is a no-op there).
|
|
171
|
+
- `ctx.request_payment()` in a group names the member asked (the sender).
|
|
172
|
+
- `await ctx.leave()` / `await bot.leave_group(gid)` leaves, with a membership event signed by the bot.
|
|
173
|
+
|
|
174
|
+
### Inline mode
|
|
175
|
+
|
|
176
|
+
```py
|
|
177
|
+
from morsel_bot import InlineResult
|
|
178
|
+
|
|
179
|
+
@bot.inline()
|
|
180
|
+
async def search(q):
|
|
181
|
+
results = [InlineResult.article("sol", "Solana", fmt(bold("SOL"), " is up"), description="Share SOL")]
|
|
182
|
+
await q.answer(results, next_offset=None, cache_time=60, switch_to_bot=("Open the bot", "from_inline"))
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Turn it on once with `await bot.set_inline(True, placeholder="Search a token", feedback=True)`. The query and the
|
|
186
|
+
answer travel sealed under the pair key; the bot never learns which chat the user is typing in. Answer within 30
|
|
187
|
+
seconds; up to 50 results per page (`next_offset` for more).
|
|
188
|
+
|
|
189
|
+
Photos and GIFs (a grid in the app):
|
|
190
|
+
|
|
191
|
+
```py
|
|
192
|
+
@bot.inline()
|
|
193
|
+
async def pictures(q):
|
|
194
|
+
await q.answer([
|
|
195
|
+
InlineResult.photo("chart", open("chart.png", "rb").read(), caption="SOL, 24 h", thumb=tiny_jpeg_b64),
|
|
196
|
+
InlineResult.gif("party", {"id": "xT9IgG50Fb7Mi0prBC", "mp4": {"u": "https://media.giphy.com/media/xT9IgG50Fb7Mi0prBC/giphy.mp4", "w": 480, "h": 270}}),
|
|
197
|
+
])
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
No result ever makes the person's phone load anything from a server you pick (that would give it their IP address).
|
|
201
|
+
A photo is a chat file: the SDK encrypts it with the app's media encryption and uploads it when the answer goes (the
|
|
202
|
+
same bytes once per process for 20 hours), and the answer names it so the server lets the person who asked fetch it
|
|
203
|
+
and send it as their own message ("via @yourbot"). `thumb`: an optional tiny preview (base64, at most 2400
|
|
204
|
+
characters) shown blurred until the picture loads; a media ref you uploaded yourself works too. A GIF is GIPHY's
|
|
205
|
+
(GIPHY's media hosts only), as everywhere in Morsel.
|
|
206
|
+
|
|
207
|
+
### Other calls
|
|
208
|
+
|
|
209
|
+
`bot.get_me()`, `bot.set_commands([("start", "Start"), {"command": "price", "description": "Price", "desc_i18n":
|
|
210
|
+
{"el": "Τιμή"}}])`, `bot.set_webhook(url, secret)`, `bot.delete_webhook()`, `bot.get_webhook()`,
|
|
211
|
+
`bot.set_group_privacy(on)`, `bot.set_inline(...)`, `bot.update_profile(name=, about=, description=)`,
|
|
212
|
+
`await bot.set_avatar("avatar.png")` (or bytes; PNG, JPEG or WebP up to 1 MB, re-encoded by the server to a square
|
|
213
|
+
256 and 64 px WebP; returns `{"url", "small"}`, at most 10 an hour), `await bot.remove_avatar()`,
|
|
214
|
+
`bot.send_message(chat, text, ...)` (a user who already wrote to the bot, or a group), `bot.send_photo(...)`,
|
|
215
|
+
`bot.edit_message(...)`, `bot.request_payment(...)`, `bot.typing(chat)`, `bot.download_media(media)`.
|
|
216
|
+
|
|
217
|
+
Token helpers: `parse_token`, `generate_token`, `token_of_seed`, `registration_proof`, `rotation_proof`.
|
|
218
|
+
|
|
219
|
+
## Receiving updates
|
|
220
|
+
|
|
221
|
+
**Stream (default)**: `bot.run()` (blocking, stops cleanly on Ctrl+C and SIGTERM) or `await bot.start()` inside
|
|
222
|
+
your own event loop. A one-use ticket opens the live stream; on connect the bot syncs everything after its saved
|
|
223
|
+
position; named heartbeats tell a live connection from a dead one (a silent one is replaced); drops reconnect
|
|
224
|
+
with exponential backoff and jitter. A suspended or revoked bot stops with `StreamStopped(code)`.
|
|
225
|
+
|
|
226
|
+
**Where the position is kept**: `Bot(token, store=FileStore("bot.seq"))` survives restarts (put it on a volume
|
|
227
|
+
in Docker). The default `MemoryStore` starts from "now" after a restart. Anything with async `get()` / `set(seq)`
|
|
228
|
+
works (Redis, a database row). Rows are deduplicated by id, so an overlap between sync and stream is harmless.
|
|
229
|
+
|
|
230
|
+
**Webhook**: an ASGI app.
|
|
231
|
+
|
|
232
|
+
```py
|
|
233
|
+
app = bot.asgi_webhook(secret=os.environ["MORSEL_WEBHOOK_SECRET"]) # uvicorn module:app
|
|
234
|
+
# FastAPI / Starlette: api.mount("/morsel", bot.asgi_webhook(secret=SECRET))
|
|
235
|
+
await bot.set_webhook("https://bot.example.com/morsel", SECRET) # once
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Each delivery's `X-Morsel-Bot-Signature` (`t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>`) is checked in
|
|
239
|
+
constant time, at most 5 minutes from your clock; a repeated delivery is acknowledged and not handled twice.
|
|
240
|
+
Handlers get 4.5 seconds (`max_wait=`) before the delivery is acknowledged anyway and finishes in the background
|
|
241
|
+
(the server waits 5 seconds and retries anything that is not 2xx, in order, for 24 hours).
|
|
242
|
+
|
|
243
|
+
**Sending politely**: every send goes through a per-chat queue: in order per chat, paced under the server's
|
|
244
|
+
limits (30 messages a second overall, a burst of 5 then about 1 a second per chat, 20 a minute per group), and a
|
|
245
|
+
`429` is retried after the `retryAfter` it names, with the same client id (a retry never doubles a message).
|
|
246
|
+
|
|
247
|
+
## Self-hosting
|
|
248
|
+
|
|
249
|
+
Bots always run on your own infrastructure; Morsel hosts nothing of yours. Templates are in `examples/deploy/`.
|
|
250
|
+
|
|
251
|
+
### Any VPS with systemd
|
|
252
|
+
|
|
253
|
+
```sh
|
|
254
|
+
sudo useradd --system --create-home --home-dir /opt/morsel-bot morselbot
|
|
255
|
+
sudo -u morselbot python3 -m venv /opt/morsel-bot/venv
|
|
256
|
+
sudo -u morselbot /opt/morsel-bot/venv/bin/pip install morsel-bot
|
|
257
|
+
sudo cp bot.py /opt/morsel-bot/ && sudo chown morselbot /opt/morsel-bot/bot.py
|
|
258
|
+
echo 'MORSEL_BOT_TOKEN=mbot1_...' | sudo tee /etc/morsel-bot.env >/dev/null && sudo chmod 600 /etc/morsel-bot.env
|
|
259
|
+
sudo cp examples/deploy/morsel-bot.service /etc/systemd/system/
|
|
260
|
+
sudo systemctl daemon-reload && sudo systemctl enable --now morsel-bot
|
|
261
|
+
journalctl -u morsel-bot -f
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
The unit restarts the bot if it exits and runs it with no write access outside its folder.
|
|
265
|
+
|
|
266
|
+
### Docker
|
|
267
|
+
|
|
268
|
+
```sh
|
|
269
|
+
cp examples/deploy/{Dockerfile,requirements.txt,docker-compose.yml} . && cp examples/deploy/env.example .env
|
|
270
|
+
# put your bot in bot.py, the token in .env (chmod 600)
|
|
271
|
+
docker build -t my-morsel-bot .
|
|
272
|
+
docker run -d --restart=always --env-file .env -v morsel-bot:/data my-morsel-bot
|
|
273
|
+
# or: docker compose up -d
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
The image runs as a non-root user and keeps `bot.seq` on the `/data` volume. No port is published: the bot only
|
|
277
|
+
connects out.
|
|
278
|
+
|
|
279
|
+
### Railway
|
|
280
|
+
|
|
281
|
+
New project > Deploy from your repo (with the Dockerfile) > Variables: `MORSEL_BOT_TOKEN`, and
|
|
282
|
+
`MORSEL_BOT_SEQ_FILE=/data/bot.seq` > add a Volume mounted at `/data`. No domain or port is needed in stream mode.
|
|
283
|
+
One replica only (two replicas would both answer every message).
|
|
284
|
+
|
|
285
|
+
### Fly.io
|
|
286
|
+
|
|
287
|
+
```sh
|
|
288
|
+
fly launch --no-deploy # with examples/deploy/fly.toml
|
|
289
|
+
fly secrets set MORSEL_BOT_TOKEN=mbot1_...
|
|
290
|
+
fly volumes create bot_data --size 1
|
|
291
|
+
fly deploy && fly scale count 1
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
### Webhook on any host (ASGI)
|
|
295
|
+
|
|
296
|
+
Any ASGI server works: `uvicorn webhook_asgi:app` behind your TLS proxy, Hypercorn, Daphne, or mounted inside an
|
|
297
|
+
existing FastAPI / Starlette app. On serverless platforms, wrap the ASGI app with the platform's adapter (for
|
|
298
|
+
example Mangum on AWS Lambda) and use `FileStore` on persistent storage or your own store; a webhook needs no
|
|
299
|
+
long-running process. The URL must be public https.
|
|
300
|
+
|
|
301
|
+
### Errors worth knowing
|
|
302
|
+
|
|
303
|
+
`ApiError.code` is the backend's: `BOT_CANNOT_INITIATE` (nobody wrote to the bot yet), `BLOCKED`, `BOT_RATE_LIMIT`
|
|
304
|
+
(429, retried for you), `BOT_FORBIDDEN` (a route bots may not call: groups management, accept, block, ...),
|
|
305
|
+
`BOT_REVOKED` (this token was replaced: the bot stops), `BOT_SUSPENDED`, `BOT_AUTH_V2`. After a token rotation,
|
|
306
|
+
people who write to the old address get `410 BOT_MOVED` with the new `address`; the new key may write to everyone
|
|
307
|
+
who wrote to any previous one.
|
|
308
|
+
|
|
309
|
+
## Security
|
|
310
|
+
|
|
311
|
+
- **The token is the key.** It is the bot's ed25519 seed: whoever has it can read the bot's chats, write as the
|
|
312
|
+
bot, and move any funds sent to its address. Keep it in an environment variable or a secret store (chmod 600
|
|
313
|
+
files, platform secrets), never in code or a repository. If it leaks, regenerate it in the app (**My bots >
|
|
314
|
+
Regenerate token**): the old key is refused from then on.
|
|
315
|
+
- **Keep the bot wallet's balance low.** The bot's address is a wallet on Solana and Cookie Chain; sweep what it
|
|
316
|
+
receives to a wallet whose key is not on a server.
|
|
317
|
+
- The SDK never logs the token, keys or message contents. `Bot(debug=True)` logs decrypted payloads: for local
|
|
318
|
+
development only.
|
|
319
|
+
- Payments count only once finalized on chain, checked through an RPC you choose; never trust a message that
|
|
320
|
+
only says it paid.
|
|
321
|
+
- Every incoming payload is checked against the row the server delivered (sender, recipient, client id); group
|
|
322
|
+
messages also against their sender's signature. Anything that does not check out is dropped, never handled.
|
|
323
|
+
- Webhook signatures are compared in constant time and refused past 5 minutes of skew. Use a long random secret
|
|
324
|
+
(`openssl rand -hex 32`).
|
|
325
|
+
|
|
326
|
+
## Byte compatibility
|
|
327
|
+
|
|
328
|
+
`tests/` replays vectors produced by the Morsel app's own chat code (key conversion, pair keys, padding,
|
|
329
|
+
secretbox, payload sanitization, `MorselWallet2` headers, group keys and signatures, membership events) and the
|
|
330
|
+
vectors shipped with the TypeScript SDK (`@morsel-wallet/bot`), so the two SDKs and the app agree on every byte.
|
|
331
|
+
|
|
332
|
+
`tests/e2e/` runs the whole flow against the real backend (its chat, group and bot routes, started locally with
|
|
333
|
+
tsx from a backend checkout: `MORSEL_BACKEND_DIR=/path/to/backend`; skipped when it isn't there): register, a
|
|
334
|
+
message and the reply, a press with its answer and edit, a group with privacy mode and a press answered to the
|
|
335
|
+
presser only, signed join and leave, an inline query and answer, and a token rotation.
|
|
336
|
+
|
|
337
|
+
```sh
|
|
338
|
+
pip install -e ".[dev]" && pytest && mypy
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
## License
|
|
342
|
+
|
|
343
|
+
MIT
|