Skip to content

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

TypeScriptPythonRuns 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.middlewareEvery update, before the handlers.
bot.catch(fn)bot.catch(fn), @bot.errorA 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) and chosen_inline.
  • Python also: text, media, request, group_message, private_message, inline_chosen, event and *.

In TypeScript, a handler gets (ctx, next). In Python, a handler is an async def that takes ctx. Plain functions work too.

The context

TypeScriptPython
Who wrote, an addressctx.fromctx.from_
Wherectx.chat: { type: 'private' | 'group', id }ctx.chat: Chat(id, type)
The app's language, like elctx.langctx.lang
The textctx.textctx.text
/price solctx.command is price, ctx.args is ['sol']the same
The whole messagectx.messagectx.message
Free space for middlewarectx.statectx.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

TypeScript
bot.command('help', (ctx) => ctx.reply('Send /price and a token, like /price sol.'));

bot.hears(/^gm$/i, (ctx) => ctx.reply('gm', { replyTo: true }));
Python
@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:

TypeScriptPython
keyboardkeyboard=Buttons under the message.
replyKeyboardreply_keyboard=Buttons above the message box.
replyTo: true or a message idquote=True or reply_to=Reply to a message.
noPreview: trueno_preview=TrueNo 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.

TypeScript
bot.command('start', (ctx) =>
  ctx.reply(ctx.payload ? `Welcome! You came from ${ctx.payload}.` : 'Welcome!'),
);
Python
@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.

TypeScript
await bot.setCommands([
  { command: 'start', description: 'Start the bot' },
  { command: 'price', description: 'Price of a token', desc_i18n: { es: 'Precio de un token' } },
]);
Python
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.

TypeScript
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')}`);
Python
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")))
StyleTypeScriptPython
Boldboldbold
Italicitalicitalic
Underlineunderlineunderline
Strikethroughstrikethroughstrike
Inline codecodecode
Code blockprepre
Hidden until tappedspoilerspoiler
Link, https onlylink(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. fmt handles this for you.

Photos and files

Files are end-to-end encrypted with the chat media encryption, like any file in Morsel.

TypeScript
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.`);
  }
});
Python
@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:

TypeScript
await bot.sendMessage(address, 'SOL crossed 150.');
Python
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.

TypeScript
bot.on('blocked', (ctx) => alerts.delete(ctx.from!));
Python
@bot.on("blocked")
async def blocked(ctx: Context) -> None:
    alerts.pop(ctx.from_, None)

Try one of these