Skip to content

Run a bot in production

Keep a bot running on a VPS, Docker, Railway or Fly, or serverless with signed webhooks. Persist its position, run one copy, and handle rate limits.

Bots always run on your own infrastructure. Morsel hosts nothing of yours. There are two ways to get updates:

Live streamWebhook
HowThe bot connects out to Morsel and keeps the connection open.Morsel POSTs each update to your https URL, signed.
NeedsA process that keeps running. No port, no domain.A public https URL. No long-running process.
Good forA VPS, Docker, Railway, FlyCloudflare Workers, Vercel, any ASGI host
Start itbot.start(), bot.run() in Pythonbot.webhook(...), bot.asgi_webhook(...) in Python

The stream is the easiest. Use a webhook where nothing can stay running.

The live stream

bot.start() opens the stream and keeps it alive:

  • It catches up from the last update it handled, page by page: on start, on every reconnect, and whenever the stream skips a number. Nothing is missed while the bot is down, as long as its store survives the restart.
  • It watches heartbeats and replaces a silent connection. Reconnects back off from 1 to 30 seconds, with jitter.
  • It drops updates it has already handled. Handling is at least once, so write handlers that are safe to run twice if the bot crashes mid-handler.
  • It stops for good, with the error, when the bot is revoked, suspended or deleted: BOT_REVOKED, BOT_SUSPENDED, BOT_GONE. It doesn't retry those.

Keep the position: the store

The SDK remembers how far it got, its seq, in a store. The default keeps it in memory, so a restart starts from the newest messages and skips what arrived while the bot was down. In production, use a store that survives restarts.

TypeScript
import { Bot, FileStore } from '@morsel/bot';

const bot = new Bot(process.env.MORSEL_BOT_TOKEN!, { store: new FileStore(process.env.BOT_STORE ?? 'bot.json') });
Python
bot = Bot(os.environ["MORSEL_BOT_TOKEN"], store=FileStore(os.environ.get("MORSEL_BOT_SEQ_FILE", "bot.seq")))

Put the file on a volume. Or bring your own store, backed by Redis, KV or a database:

  • TypeScript: any { get(key), set(key, value) }, sync or async. It also keeps payment bookkeeping, so signatures are never counted twice.
  • Python: any object with async get() and async set(seq).

To read the whole backlog the very first time, pass firstStart: 'all' in TypeScript or catch_up_on_first_run=True in Python.

Run one copy

Run one process per bot. Two copies with the same token would both answer every message. To handle more load, put a queue behind your handlers, or use the webhook, which delivers in order for each bot.

Rate limits

Limit
All chats30 messages a second
One chata burst of 5, then about 1 a second
One group20 messages a minute

Past a limit, Morsel answers 429 with BOT_RATE_LIMIT, a retryAfter in seconds in the body, and a Retry-After header.

You rarely see it. Every send goes through a queue for its chat, in order, paced under these limits. A 429 pauses that chat for retryAfter, then the send is retried with the same client id, so it's never sent twice.

Raw calls with bot.api.call(...) don't go through the queue. Errors there are MorselApiError in TypeScript and ApiError in Python, with status, code and retryAfter (retry_after in Python).

TypeScript
import { MorselApiError } from '@morsel/bot';

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

try {
  await bot.api.call('GET', '/v1/bots/me');
} catch (e) {
  if (e instanceof MorselApiError && e.status === 429) await sleep((e.retryAfter ?? 1) * 1000);
  else throw e;
}

Deploy

A VPS with systemd

Run the bot as its own user, with the token in a root-only file:

/etc/systemd/system/morsel-bot.service
[Unit]
Description=Morsel bot
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=morselbot
WorkingDirectory=/opt/morsel-bot
EnvironmentFile=/etc/morsel-bot.env
Environment=NODE_ENV=production BOT_STORE=/var/lib/morsel-bot/bot.json
StateDirectory=morsel-bot
ExecStart=/usr/bin/node --import tsx index.ts
Restart=always
RestartSec=5
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/morsel-bot

[Install]
WantedBy=multi-user.target
Terminal
echo 'MORSEL_BOT_TOKEN=mbot1_...' | sudo tee /etc/morsel-bot.env >/dev/null
sudo chmod 600 /etc/morsel-bot.env
sudo systemctl daemon-reload && sudo systemctl enable --now morsel-bot
journalctl -u morsel-bot -f

For Python, set ExecStart to your virtualenv, like /opt/morsel-bot/venv/bin/python bot.py, and the store path with MORSEL_BOT_SEQ_FILE. Both SDK repos ship this unit in examples/deploy/.

Docker

The bot only connects out, so publish no port. Keep the store on a volume.

Dockerfile
FROM node:22-slim
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev --no-audit --no-fund
COPY . .
ENV NODE_ENV=production BOT_STORE=/data/bot.json
VOLUME /data
USER node
CMD ["node", "--import", "tsx", "index.ts"]
Dockerfile
FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 MORSEL_BOT_SEQ_FILE=/data/bot.seq
RUN useradd --create-home --uid 10001 bot && mkdir /data && chown bot /data
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY bot.py .
USER bot
VOLUME ["/data"]
CMD ["python", "bot.py"]

With the TypeScript image, keep tsx in your dependencies, or compile to JavaScript and run node index.js.

docker-compose.yml
services:
  bot:
    build: .
    restart: unless-stopped
    env_file: .env   # MORSEL_BOT_TOKEN=..., chmod 600, never committed
    volumes:
      - bot-data:/data
volumes:
  bot-data:
Terminal
docker compose up -d

Railway

  1. Create a service from your repo. It's a worker: give it no domain and no port.
  2. Under Variables, set MORSEL_BOT_TOKEN, and BOT_STORE=/data/bot.json for TypeScript or MORSEL_BOT_SEQ_FILE=/data/bot.seq for Python.
  3. Add a volume mounted at /data.
  4. Keep one replica.

Fly.io

fly.toml
app = "my-morsel-bot"
primary_region = "ams"

[build]
  dockerfile = "Dockerfile"

[env]
  BOT_STORE = "/data/bot.json"

[mounts]
  source = "bot_data"
  destination = "/data"

[[vm]]
  size = "shared-cpu-1x"
  memory = "256mb"
Terminal
fly launch --no-deploy
fly volumes create bot_data --size 1
fly secrets set MORSEL_BOT_TOKEN=mbot1_...
fly deploy && fly scale count 1

There's no [http_service]: the bot is a worker that connects out.

Webhooks

With a webhook, Morsel POSTs every update to your URL. Set it once, from anywhere the token is:

TypeScript
await bot.setWebhook('https://bot.example.com/morsel', process.env.WEBHOOK_SECRET!);
Python
await bot.set_webhook("https://bot.example.com/morsel", os.environ["MORSEL_WEBHOOK_SECRET"])
  • The URL must be https on a public host, up to 512 characters. Redirects aren't followed.
  • The secret is 16 to 128 printable characters. Make it long and random: openssl rand -hex 32. Morsel stores it sealed and never shows it again.
  • Remove the webhook with bot.deleteWebhook() or bot.delete_webhook(). Your bot's page in My bots shows its state.

What Morsel sends

HTTP
POST /morsel
Content-Type: application/json
User-Agent: MorselBots/1.0 (+https://morselwallet.app)
X-Morsel-Bot-Seq: 1234
X-Morsel-Bot-Signature: t=1763400000,v1=5f2b...

{ "seq": "1234", "event": { "type": "message", ... } }
  • event is exactly what the stream would send. seq is null for events without one, like inline queries.
  • Answer 2xx within 5 seconds. Anything else is retried with backoff, from 5 seconds doubling up to an hour, for 24 hours. Then it's dropped, and the error shows on your bot's page.
  • Deliveries are in order for each bot. The next waits until the one before it was delivered or dropped. Up to 10,000 can wait.
  • A gap in seq means you missed something. The SDKs catch up for you.

The SDK handlers check the signature, skip deliveries they've already handled, run your handlers, and answer 200. If handling takes longer than 4.5 seconds, they answer 200 anyway and finish in the background.

Cloudflare Workers

worker.ts
import { Bot, type BotStore } from '@morsel/bot';

interface Env {
  MORSEL_BOT_TOKEN: string;
  WEBHOOK_SECRET: string;
  BOT_KV: { get(k: string): Promise<string | null>; put(k: string, v: string): Promise<void>; delete(k: string): Promise<void> };
}

let handler: ((req: Request) => Promise<Response>) | null = null;

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    if (!handler) {
      const store: BotStore = { get: (k) => env.BOT_KV.get(k), set: (k, v) => env.BOT_KV.put(k, v), delete: (k) => env.BOT_KV.delete(k) };
      const bot = new Bot(env.MORSEL_BOT_TOKEN, { store, username: 'my_bot' });
      bot.command('start', (ctx) => ctx.reply('Hi from the edge'));
      handler = bot.webhook({ secret: env.WEBHOOK_SECRET });
    }
    return handler(req);
  },
};

Set the secrets with wrangler secret put MORSEL_BOT_TOKEN and wrangler secret put WEBHOOK_SECRET. Passing username saves a lookup on cold starts.

Vercel and Next.js

app/api/morsel/route.ts
import { Bot } from '@morsel/bot';

const bot = new Bot(process.env.MORSEL_BOT_TOKEN!, { username: 'my_bot' });
bot.command('start', (ctx) => ctx.reply('Hi from Vercel'));

export const POST = bot.webhook({ secret: process.env.WEBHOOK_SECRET! });

Give it a durable store, like Vercel KV or Upstash Redis, through the store interface.

Express and Hono

TypeScript
import express from 'express';
import { expressAdapter, honoAdapter } from '@morsel/bot';

const app = express();
// The signature covers the raw body: never let express.json() parse it first.
app.post('/morsel', express.raw({ type: '*/*', limit: '64kb' }), expressAdapter(bot.webhook({ secret: SECRET })));

// Hono: app.post('/morsel', honoAdapter(bot.webhook({ secret: SECRET })))

Python: any ASGI server

webhook.py
import os

from morsel_bot import Bot, Context

bot = Bot(os.environ["MORSEL_BOT_TOKEN"])


@bot.command("start")
async def start(ctx: Context) -> None:
    await ctx.reply("Hello from a webhook")


app = bot.asgi_webhook(secret=os.environ["MORSEL_WEBHOOK_SECRET"])
Terminal
uvicorn webhook:app --host 0.0.0.0 --port 8080

Run it behind your TLS proxy, or mount it in FastAPI or Starlette with api.mount("/morsel", bot.asgi_webhook(secret=SECRET)). On serverless platforms, wrap the ASGI app with the platform's adapter, such as Mangum on AWS Lambda, and give the bot a store on persistent storage.

Verify a webhook yourself

The SDKs check signatures for you. If you receive webhooks without them, check every delivery before you parse it:

X-Morsel-Bot-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>

Compute the HMAC over the raw body, compare in constant time, and refuse a timestamp more than 5 minutes from your clock.

verify.ts
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verifyMorselWebhook(secret: string, header: string | null, rawBody: string, maxAgeSeconds = 300): boolean {
  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? '');
  if (!m) return false;
  const t = Number(m[1]);
  if (Math.abs(Math.floor(Date.now() / 1000) - t) > maxAgeSeconds) return false;
  const want = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest();
  const got = Buffer.from(m[2], 'hex');
  return got.length === want.length && timingSafeEqual(want, got);
}
verify.py
import hashlib
import hmac
import re
import time


def verify_morsel_webhook(secret: str, header: str | None, raw_body: bytes, max_age_seconds: int = 300) -> bool:
    m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")
    if not m:
        return False
    t = int(m.group(1))
    if abs(int(time.time()) - t) > max_age_seconds:
        return False
    want = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(want, m.group(2))

The SDKs export the same check: verifyWebhookSignature(header, rawBody, secret) in TypeScript and verify_signature(secret, header, body) in Python.

Then skip any seq you've already handled, answer 2xx quickly, and do slow work after.

Try one of these