Messages, commands and formatting
Handle commands and text, read who wrote and in which language, set the commands menu, format text with entities, and send photos and files.
A bot is a list of handlers. Each update, a message, a button press, a payment, runs through them in the order you registered them. The first one that matches handles it. In TypeScript, call next() to pass it on.
Updates from one chat run in order. Different chats run in parallel.
Handlers
| TypeScript | Python | Runs for |
|---|---|---|
bot.command('start', h) | @bot.command("start") | /start, and /start@yourbot in groups. Case doesn't matter. |
bot.hears('gm', h), bot.hears(/gm/i, h) | @bot.hears("gm"), @bot.hears(re.compile(...)) | Text equal to a string, or matching a regex. The match is in ctx.match. |
bot.callback('data', h) | @bot.callback("data") | A button press. See Keyboards. |
bot.inline(h) | @bot.inline() | An inline query. See Inline mode. |
bot.on('message', h) | @bot.on("message") | Any update of that type. |
bot.use(mw) | bot.use(mw), @bot.middleware | Every update, before the handlers. |
bot.catch(fn) | bot.catch(fn), @bot.error | A handler that threw. |
Update types you can pass to on:
- Both SDKs:
message,edited,callback,payment,payment_failed,blocked,unblocked,bot_added,bot_removed,inline_query. - TypeScript also:
decline(someone declined a payment request) andchosen_inline. - Python also:
text,media,request,group_message,private_message,inline_chosen,eventand*.
In TypeScript, a handler gets (ctx, next). In Python, a handler is an async def that takes ctx. Plain functions work too.
The context
| TypeScript | Python | |
|---|---|---|
| Who wrote, an address | ctx.from | ctx.from_ |
| Where | ctx.chat: { type: 'private' | 'group', id } | ctx.chat: Chat(id, type) |
The app's language, like el | ctx.lang | ctx.lang |
| The text | ctx.text | ctx.text |
/price sol | ctx.command is price, ctx.args is ['sol'] | the same |
| The whole message | ctx.message | ctx.message |
| Free space for middleware | ctx.state | ctx.state |
In a private chat, ctx.chat.id is the person's address. In a group, it's the group's id.
ctx.lang is the language the person's app uses, sent with every message to a bot, never to people. Use it to answer in their language.
Everything in ctx comes from the person. The SDK checks every payload against the row Morsel delivered, but treat text and callback data as untrusted input anyway.
Reply
bot.command('help', (ctx) => ctx.reply('Send /price and a token, like /price sol.'));
bot.hears(/^gm$/i, (ctx) => ctx.reply('gm', { replyTo: true }));@bot.command("help")
async def help_(ctx: Context) -> None:
await ctx.reply("Send /price and a token, like /price sol.")
@bot.hears(re.compile(r"^gm$", re.IGNORECASE))
async def gm(ctx: Context) -> None:
await ctx.reply("gm", quote=True)Reply options:
| TypeScript | Python | |
|---|---|---|
keyboard | keyboard= | Buttons under the message. |
replyKeyboard | reply_keyboard= | Buttons above the message box. |
replyTo: true or a message id | quote=True or reply_to= | Reply to a message. |
noPreview: true | no_preview=True | No link preview. |
The /start payload
A bot link can carry a payload: morsel://bot/price_bot?start=ref_42. When the person taps Start, the app sends /start ref_42, and ctx.payload is ref_42.
bot.command('start', (ctx) =>
ctx.reply(ctx.payload ? `Welcome! You came from ${ctx.payload}.` : 'Welcome!'),
);@bot.command("start")
async def start(ctx: Context) -> None:
await ctx.reply(f"Welcome! You came from {ctx.payload}." if ctx.payload else "Welcome!")Anyone can write any payload. Don't trust it for anything that matters.
Commands menu
The commands you set show behind the / button in your bot's chat. Set them in the app under My bots, or from code. Code can add a description for each language: the app shows the one for its own language.
await bot.setCommands([
{ command: 'start', description: 'Start the bot' },
{ command: 'price', description: 'Price of a token', desc_i18n: { es: 'Precio de un token' } },
]);await bot.set_commands([
("start", "Start the bot"),
{"command": "price", "description": "Price of a token", "desc_i18n": {"es": "Precio de un token"}},
])Up to 100 commands. A command is 1 to 32 characters of a to z, 0 to 9 and _, and a description 1 to 256 characters.
Formatting
Formatting is a list of entities over plain text. It is never HTML or Markdown, so nothing a person types can turn into formatting. Build it with fmt and its helpers.
import { fmt, bold, italic, code, link, spoiler } from '@morsel/bot';
await ctx.reply(fmt`SOL ${code('142.50')} USD, ${italic('+4.2% today')}. ${link('Chart', 'https://example.com/sol')}`);
await ctx.reply(fmt`Your code: ${spoiler('ABC-123')}`);from morsel_bot import bold, code, fmt, italic, link, spoiler
await ctx.reply(fmt("SOL ", code("142.50"), " USD, ", italic("+4.2% today"), ". ", link("Chart", "https://example.com/sol")))
await ctx.reply(fmt("Your code: ", spoiler("ABC-123")))| Style | TypeScript | Python |
|---|---|---|
| Bold | bold | bold |
| Italic | italic | italic |
| Underline | underline | underline |
| Strikethrough | strikethrough | strike |
| Inline code | code | code |
| Code block | pre | pre |
| Hidden until tapped | spoiler | spoiler |
| Link, https only | link(text, url) | link(text, url) |
Links open after the app shows the person their domain. Styles nest: bold(link('docs', url)).
Text rules
- A message holds up to 1000 characters. A longer one throws an error in your code.
- Text is cleaned the way the app cleans it: control and direction-override characters are removed, line endings are normalized, and the ends are trimmed. Entities move with the text, so they always match what people see.
- Up to 100 entities a message. Offsets count UTF-16 code units, as in JavaScript strings.
fmthandles this for you.
Photos and files
Files are end-to-end encrypted with the chat media encryption, like any file in Morsel.
import { readFile } from 'node:fs/promises';
bot.command('chart', async (ctx) => {
await ctx.replyWithPhoto(await readFile('chart.png'), { caption: 'SOL, 24 h' });
});
bot.on('message', async (ctx) => {
if (ctx.message?.media) {
const bytes = await ctx.download(); // decrypted and checked
await ctx.reply(`Got ${bytes.length} bytes.`);
}
});@bot.command("chart")
async def chart(ctx: Context) -> None:
with open("chart.png", "rb") as f:
await ctx.reply_with_photo(f.read(), caption="SOL, 24 h")
@bot.on("media")
async def got_file(ctx: Context) -> None:
data = await ctx.download() # decrypted and checked
await ctx.reply(f"Got {len(data)} bytes.")A bot sends photos: PNG, JPEG or WebP. It can download any file people send it.
Typing
await ctx.typing() shows "typing…" in a private chat for a few seconds. Bots show no typing in groups, so there it does nothing.
Send outside a handler
To send later, for example when a price alert fires, keep the person's address and use the bot:
await bot.sendMessage(address, 'SOL crossed 150.');await bot.send_message(address, "SOL crossed 150.")A bot can only write to people who wrote to it first and haven't stopped it. Anyone else answers 403 BOT_CANNOT_INITIATE or 403 BLOCKED.
Stopped and started again
When someone taps Stop bot, your bot gets blocked. If they start it again, it gets unblocked. Stop sending to them in between.
bot.on('blocked', (ctx) => alerts.delete(ctx.from!));@bot.on("blocked")
async def blocked(ctx: Context) -> None:
alerts.pop(ctx.from_, None)