Bot from scratch

From yanacuti1121/Yana-AI · View interactive version

Bot from scratch is an AI agent skill from the GitHub repository yanacuti1121/Yana-AI. Use when building a chat-platform bot (Discord/Telegram/Slack/Twitter-style) from first principles — the event loop, command routing, and platform API integration, not an LLM agent framework. Triggers on: 'build a discord bot from scratch', 'implement a telegram bot event loop', 'webhook vs polling

How to use this skill

Skill file

/bot-from-scratch

When to Use

Do NOT use for


Architecture Decision: Polling vs Webhook

Simple deployment, no public HTTPS endpoint available, low message volume?
  → Polling (Step 1) — bot repeatedly asks the platform "any new events?"

Production deployment with a reachable HTTPS endpoint, want lower latency
and lower request volume?
  → Webhook (Step 2) — platform pushes events to your endpoint as they happen

Most platform bot APIs (Telegram, Discord's gateway, Slack) support both; polling is simpler to get running locally, webhooks are what real deployments typically use.

Step 1: Polling Architecture

loop:
  events = GET platform_api/get_updates?offset=last_seen_id
  for event in events:
    handle(event)
    last_seen_id = event.id + 1
  sleep(poll_interval)   # or use long-polling if the platform supports it

Long-polling (the request itself blocks server-side for up to N seconds waiting for a new event, rather than returning immediately with an empty list) is far more efficient than short-polling with a fixed sleep — it gets near-webhook latency without needing a public endpoint. Telegram's getUpdates supports this via a timeout parameter; check whether your target platform does before defaulting to fixed-interval short polling.

Idempotency via offset/cursor: always track the last-processed event ID and request only events after it (offset=last_seen_id) — without this, a restart re-delivers already-handled events, causing duplicate responses/actions.

Step 2: Webhook Architecture

The platform makes an HTTP POST to your public endpoint whenever an event occurs. Requirements this introduces that polling doesn't have:

Step 3: Command Parsing & Routing

Most chat bots follow a command-router pattern regardless of platform:

parse: "!ban @user 3d spamming" → command="ban", args=["@user", "3d", "spamming"]
route: lookup "ban" in a command table → call ban_handler(event, args)
COMMANDS = {
    "ban": handle_ban,
    "help": handle_help,
}

def route(event):
    if not event.text.startswith(PREFIX):
        return
    command, *args = event.text[len(PREFIX):].split()
    handler = COMMANDS.get(command.lower())
    if handler:
        handler(event, args)
    else:
        reply(event, f"Unknown command: {command}")

For platforms with native slash-command support (Discord interactions, Slack slash commands), the platform does the parsing and delivers structured (command, args) directly — prefer that over text parsing when available, since it also gets you free autocomplete/validation in the client UI.

Step 4: State Management

Bots are usually stateless per-message but need memory across messages (conversation context, per-user settings, rate-limit counters, active game/session state). Keep state keyed by the smallest scope that's actually correct for the feature — per-user, per-channel, or per-guild/workspace are different scopes with different lifetimes, and conflating them is a common bug (e.g. a "current game" keyed globally instead of per-channel breaks the moment two channels play simultaneously).

For anything beyond a single-process toy bot, back state with persistent storage (Redis for ephemeral/fast-expiring state like rate limits, a real database for anything that must survive a restart) rather than in-memory dicts — an in-memory-only bot loses all state on every deploy/crash.

Step 5: Rate Limiting Against the Platform API

Every chat platform enforces its own rate limits (Discord: per-route limits with X-RateLimit-* response headers; Telegram: ~30 messages/second global, 1/second per chat). Two directions to handle:

What NOT to Do

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.