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
mkdir my-bot && cd my-bot
python3 -m venv .venv
. .venv/bin/activate
pip install morsel-botOn 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:
pip install "morsel-bot @ git+https://github.com/rugruts/morsel-bot#subdirectory=python"2. Write the bot
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
export MORSEL_BOT_TOKEN='mbot1_...'
python bot.pyPaste 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
- In Morsel, open Chats and search for your bot's
@username. - Tap Start. The bot says hi.
- 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 see | What to do |
|---|---|
TokenError when it starts | The token is incomplete or mistyped. Copy it again from where you saved it. |
It stops with StreamStopped and BOT_REVOKED | The token was regenerated. Use the new one. |
It stops with BOT_SUSPENDED | Morsel suspended the bot. It can't send or receive messages. |
| The bot answers twice | Two copies are running with the same token. Run one. |
KeyError: 'MORSEL_BOT_TOKEN' | The variable isn't set in this terminal. Export it again. |