Skip to content

Bot quick start in Python

Run an echo bot for Morsel Chats on your own computer with the morsel-bot package, asyncio and a token from the app, in about five minutes.

You'll run a bot that answers /start and repeats what people send it. It runs on your computer and connects out to Morsel, so you don't need a domain or an open port.

You need Python 3.10 or later and a bot token. To get one, see Create a bot.

1. Install

Terminal
mkdir my-bot && cd my-bot
python3 -m venv .venv
. .venv/bin/activate
pip install morsel-bot

On Windows, activate with .venv\Scripts\activate. The package depends on PyNaCl and httpx, and is fully typed.

To install straight from the GitHub repo instead:

Terminal
pip install "morsel-bot @ git+https://github.com/rugruts/morsel-bot#subdirectory=python"

2. Write the bot

bot.py
import logging
import os

from morsel_bot import Bot, Context, FileStore

logging.basicConfig(level=logging.INFO)

bot = Bot(
    os.environ["MORSEL_BOT_TOKEN"],
    # Remembers where the bot got to, so a restart catches up instead of missing messages.
    store=FileStore("bot.seq"),
)


@bot.command("start")
async def start(ctx: Context) -> None:
    await ctx.reply("Hi! Send me anything and I will send it back.")


@bot.on("text")
async def echo(ctx: Context) -> None:
    await ctx.reply(ctx.text or "", quote=True)


if __name__ == "__main__":
    bot.run()

Handlers run in the order they were registered, and the first one that matches handles the update. That's why /start goes to start, and every other text to echo.

3. Run it

Terminal
export MORSEL_BOT_TOKEN='mbot1_...'
python bot.py

Paste your own token. On Windows PowerShell, use $env:MORSEL_BOT_TOKEN='mbot1_...'.

bot.run() blocks, and stops cleanly on Ctrl+C and SIGTERM. Inside your own event loop, use await bot.start() instead.

4. Talk to it

  1. In Morsel, open Chats and search for your bot's @username.
  2. Tap Start. The bot says hi.
  3. Send it anything. It replies with the same text.

Messages sent while the bot is down wait for it: when it starts again, it catches up from bot.seq.

If it doesn't work

What you seeWhat to do
TokenError when it startsThe token is incomplete or mistyped. Copy it again from where you saved it.
It stops with StreamStopped and BOT_REVOKEDThe token was regenerated. Use the new one.
It stops with BOT_SUSPENDEDMorsel suspended the bot. It can't send or receive messages.
The bot answers twiceTwo copies are running with the same token. Run one.
KeyError: 'MORSEL_BOT_TOKEN'The variable isn't set in this terminal. Export it again.

Next

Try one of these