Skip to content
Point72Public

Repository files navigation

csp-bot logo, overlapping blue speech bubbles

Build Status codecov GitHub issues License PyPI

Features

csp-bot is a framework for building chat bots. It is built on csp, csp-gateway, ccflow, and chatom.

csp-bot makes it easy to build extensible command-driven bots, and has some key features:

  • connect to multiple backend chat platforms from the same instance
  • supports Slack, Symphony, Discord, Telegram, Zulip, IRC, and Matrix
  • register custom commands across backends
  • create scheduled commands
  • create asynchronous commands
  • tag users
  • redirect commands across rooms/channels
  • and more!

For a detailed overview and examples, see our Documentation.

Community-supported commands can be found in the csp-bot-commands project.

Legacy command classes can set raw_args = True to receive the argument text as one token, preserving quotes, internal spaces, and line breaks. Mentions and /room directives within that text are treated as data. Outer whitespace is trimmed. Commands using the default argument parser retain their existing behavior. This supports JSON and text-processing commands without reparsing their payloads as bot arguments.

Installation

Install with pip:

pip install csp csp-bot

Install with conda

conda install csp csp-bot -c conda-forge

Scheduling commands

Scheduling options precede a standalone --; the text after it is the command to run. Cron expressions have five fields and use UTC. Delays accept a positive number with ms, s, m, h, or d units.

/schedule add --cron "0 9 * * 1-5" -- /echo Morning update
/delay 20m -- /help schedule
/schedule list
/schedule remove <id>

Creation returns an ID and the next execution time. The inner command, including its preparation hooks, runs when due. Tokens such as /schedule or /delay after the boundary belong to the inner command. Quotes and raw JSON arguments use that command's normal parser. Missing boundaries, invalid timing, unknown commands, and nested scheduling commands return an error without creating a job or executing the inner command. Legacy inline timing flags and hyphen-separated cron fields are rejected; cron ranges such as 1-5 remain valid.

Users can list/remove their own schedules on the current backend. Bot admins and admins of /schedule can also list/remove other users' schedules. Removing a schedule prevents subsequent occurrences even if an alarm is already armed. Removing a recurring schedule does not cancel an occurrence that has already started.

Existing state stores persist schedules. On restart, future one-off jobs are re-armed, overdue one-off jobs are removed, and overdue recurring jobs advance to their next future occurrence. Missed occurrences are not replayed. Each recurring run has a separate invocation ID so its async polling does not overwrite the recurring schedule or another run.

Repeated-command gate

At most three matching executions are allowed in a rolling five-second window. The fourth is stopped before preparation/execution. Matching includes backend, user ID, destination channel, command name, arguments, and mentioned-user IDs. Preparation and execution count once together; queued continuations and async polls are also checked. The default two-second agent polling interval fits within this limit.

A blocked burst reports one error, removes matching schedules and delayed work, and cancels matching in-flight agents. Pending alarms for removed jobs cannot restart them. Further blocked attempts are silent until another execution is allowed by the window. Other users, rooms, and arguments have separate budgets. The gate is in memory per running bot; removed schedules remain removed in a configured persistent state store.

Management commands

The default configuration includes /whoami, /logs, /messages, /perms, and /link.

Command Access Behavior
/whoami Any authorized bot user Show backend, user ID, channel ID, management role, and identity.
/logs [lines] [filters] Admin, in a DM with the bot or a configured log channel Show the last 50 lines by default; accept 1-200 lines, reading at most 64 KiB and displaying at most 3,000 characters of log text. With filters, the line count applies after filtering and up to 4 MiB is read.
/messages list [before-id] [filters] Admin, in a DM with the bot or a configured message management channel Browse recent bot sends across rooms on the invoking backend, five per page.
/messages edit <id> <text> Admin, in a DM with the bot or a configured message management channel Replace the text of a recorded message.
/messages delete <id> Admin, in a DM with the bot or a configured message management channel Delete one recorded message.
/perms [command] Bot admin, or an admin of the command List admins, allowed users, and denied users for the bot or one command.
/perms <kind> <add|remove> <users> [command] Bot admin, or an admin of the command Change permissions. kind is admin, allow, or deny; users are mentions or user IDs.
/perms identities, /perms link, /perms unlink Bot admin List identities, or link and unlink accounts and email addresses.
/link [code|remove] Anyone, with the code issued in a direct message Link this account to another of yours.

/logs and /messages list accept these options. When you give more than one, an entry must match all of them.

  • --level <level> (/logs only): keep entries at debug, info, warning, error, or critical and above. Traceback lines stay with the entry they follow.
  • --from <user>: on /logs, keep entries that mention the user's ID; on /messages, keep replies to commands the user ran.
  • --to <user>: on /logs, the same as --from; on /messages, keep replies to commands that mentioned the user.

Give a user by tagging them or by their user ID. A tag that does not match a user, such as a Telegram @username the bot has not seen, is reported as an error. The message catalog records who ran a command and whom it mentioned only for replies to commands, and only from csp-bot 2.1 on, so other messages match neither user option.

Admins and other permissions are described under Permissions.

Any command can be made admin-only by setting admin: true on its command model. Admin-only commands follow the same rules as /logs and /messages: only admins can run them, they reject reply-destination redirects, and /help lists them only for admins. admin: false lifts the restriction from /logs or /messages, though they still require a configured channel.

gateway:
  commands:
    - /commands/help
    - _target_: csp_bot.commands.ScheduleCommandModel
      admin: true

With a packaged gateway configuration, management settings belong under modules.bot.config:

modules:
  bot:
    config:
      management:
        log_channels:
          slack: ["C01234567"]
        message_channels:
          slack: ["C01234567"]
        log_file: ${hydra.runtime.output_dir}/csp_bot.log

log_file is an operator-configured path; /logs cannot select another file. Log retrieval is disabled until a file is configured. An admin can retrieve logs in a one-to-one DM with the bot or in a channel listed in log_channels. Group DMs do not count. Logs can include chat content and operational details, so configured log channels should be private. A permitted channel controls the destination; each caller must still be an admin.

/logs and /messages reject reply-destination redirects. Admin access is checked before command preprocessing and again at execution. Attempts are recorded in the bot log. The existing user_access_channels gate still applies to bot interactions.

/messages replaces the standalone /delete command. Each entry shows a stable catalog ID, native message ID, room name/ID, recorded UTC send time, status, and text preview. Edit/delete accepts the catalog ID shown after ID:, not a native ID or a position within a page. The stored backend, room, and native ID identify the target; identical native IDs in different rooms remain distinct.

/messages list
/messages list <before-id-from-Next>
/messages edit <catalog-id> Replacement text
/messages delete <catalog-id>

Pagination uses the last entry's stable ID as a cursor. New sends and edits do not shift the next page. Deleted entries retain their status and cursor until evicted. An expired cursor returns an error with instructions to restart listing.

The catalog records successful adapter sends and separate attachment uploads, plus local agent sends and uploads, including generated files, images, and GIFs. It retains the latest 1,000 entries across backends. It starts empty and does not backfill platform history. It is in memory by default and is kept in the state_store when one is configured. Observing sends does not depend on a platform message-history API.

Message management requires a configured admin, in a one-to-one DM with the bot or a permitted destination in message_channels. Listings can include previews from private rooms and DMs, so permitted destinations should be private. An admin on one backend does not gain access to another backend's records. These are bot-wide administrators within that backend, rather than room-only moderators.

Actions target the recorded room, while their responses stay in the management channel. Capability checks and native API permissions still apply. Text editing does not replace attachments; unsupported edits, expired platform permissions, and externally removed messages can fail. Successful management edits update the preview and native ID if changed; successful deletes mark the entry deleted. Changes made through other clients or tools are not automatically reconciled. Only the selected message is affected; associated replies and recurring schedules remain separate.

Backend Native edit/delete routing
Slack Channel ID and message timestamp through chat.update / chat.delete.
Discord Channel ID and message ID through message edit/delete.
Telegram Chat ID and message ID through text edit/delete; catalog management requires no history retrieval.
Symphony Stream/message IDs for updates and message ID for suppression.
Zulip Message ID through message update/delete.
Matrix Room ID and event ID; an edit sends an m.replace event and a delete redacts the event.
IRC Not supported, because IRC messages cannot be edited or deleted.

Local agent commands, including /ask, also expose delete_message only to bot admins and admins of that command. Existing channel and authorship checks still apply. External MCP services enforce their own authorization.

Custom command lists can register these models from csp_bot.commands: WhoamiCommandModel, LogsCommandModel, and MessagesCommandModel.

Permissions

Permissions name people and accounts, never display names. /whoami shows the IDs to use. An entry in a permission list is one of:

  • "backend:user_id", such as "slack:U01234567", for one account;
  • "backend:*", for everyone on that backend;
  • the name of an identity, for one person's accounts on every backend;
  • _target_: chatom.Account with backend and id, the typed form of "backend:user_id";
  • _target_: chatom.LinkedIdentity with refs, an unnamed person written inline.

The bot and each command have three lists:

  • admins: bot admins may run every command, including admin-only ones, and change any permission. An admin of a command may run it and change its permissions.
  • denied: these people may not use the bot, or the command. Admins are not affected.
  • allowed: if the list is not empty, only these people may use the bot, or the command. Add "discord:*" to keep a backend open to everyone.

Admins are checked first, then denied users, then allowed users. Bot-wide allowed users combine with the members of user_access_channels. /help lists only the commands a user may run.

modules:
  bot:
    config:
      identities:
        alice:
          refs: ["slack:U01234567", "discord:123456789012345678", "irc:alice"]
          email: alice@example.com
      trusted_email_backends: [slack]
      permissions:
        admins: [alice]
        denied: ["slack:U07654321"]
        commands:
          schedule:
            allowed:
              - alice
              - _target_: chatom.Account
                backend: symphony
                id: "349026222366053"
      state_store:
        _target_: csp_bot.FsspecStateStore
        url: file:///var/lib/csp-bot/state

Identities

An identity groups one person's accounts, so a permission given to the identity applies on every backend. An account belongs to at most one identity. Accounts are linked in four ways:

  • in identities in the configuration;
  • by a bot admin, with /perms link <name> <users or emails>;
  • by the person, with /link: it returns a one-time code in a direct message with the bot, and sending /link <code> from another account links the two. Whoever sends the code is linked, so it must stay private. It expires after ten minutes. /link remove unlinks the current account;
  • by email: on a backend listed in trusted_email_backends, an account whose email address matches an identity's email belongs to that identity. List only backends that verify email addresses.

IRC user IDs are nicknames, which anyone can take while they are free. Give an IRC account admin rights only on a network that protects nicknames.

Changing permissions from chat

Configured permissions and identities are fixed. Admins can add to them from chat, and those changes are kept in the bot's state_store. csp_bot.FsspecStateStore needs the persistence extra: pip install 'csp-bot[persistence]'. Without a state store, /perms and /link can only list. Entries from the configuration cannot be removed from chat. A mentioned user who belongs to an identity is added by the identity's name.

/perms
/perms admin add @alice
/perms deny add @bob schedule
/perms allow remove discord:123456789012345678 schedule
/perms identities
/perms link alice @alice-on-this-backend alice@example.com
/perms unlink alice slack:U01234567

A command can check whether the caller is a bot admin or an admin of that command, through ctx.is_admin for Command subclasses or command.is_admin for BaseCommand subclasses. That allows a command where anyone may list but only admins may submit; see the wiki's Writing Commands page.

License

This software is licensed under the Apache 2.0 license. See the LICENSE file for details.