All docs pages

Python SDK

The caret-sdk package covers installing it, the client, every helper, events, errors and retries, and running your own bot.

Install

pip install https://caretbot.com/api/caret-sdk-0.1.0.zip

It needs Python 3.10 or later, and installs grpcio and protobuf. You import it as caret.

The client

import caret

c = caret.Caret(
    api_key=None,     # default: the CARET_API_KEY environment variable
    server=None,      # default: CARET_SERVER, else https://caretsvc.com
    timeout=10.0,     # seconds per call
)

Set server (or CARET_SERVER) to your organisation's address, such as https://caret.yourcompany.com. Use the client as a context manager, or call c.close() when you're done.

Helpers

Wherever a helper takes a space, thread or bot, you can pass its name or handle, its id, or the object itself.

Workspace

Call Returns Scope
c.workspace() The workspace: id, name, slug, time_zone, role read

Spaces

Call Returns Scope
c.spaces.list() Every space you can see, each with space, member_ids, archived read
c.spaces.get("billing") One space, by name or id read
c.spaces.create("denials", purpose="…", private=False) The new space spaces

Threads

Call Returns Scope
c.threads.create(space, title, message="", mention=[…]) The new thread. Bots named with @handle in message, or in mention, are called in messages
c.threads.list(space=None) Threads you can read: all, or one space's read
c.threads.get(thread_id) The thread with its participants, artifacts, notes and open approvals read
c.threads.messages(thread_id) Its messages, oldest first read
c.threads.done(thread_id) / c.threads.reopen(thread_id) messages

Messages

Call Returns Scope
c.messages.post(thread, body, reply_to="") The message. Bots it names are called in messages
c.messages.edit(message_id, body) messages
c.messages.delete(message_id) messages
c.messages.react(message_id, "👍", on=True) messages
c.messages.answer_card(message_id, action_id, values={…}) Presses a button on a bot's card messages

Bots

Call Returns Scope
c.bots.list() / c.bots.get("denials") Bots: handle, name, status, model, instructions read
c.bots.register(handle, name=…, instructions=…, respond_when=…) A bot that you run yourself with caret.Bot (below) bots
c.bots.grant(bot, space, write=True) Lets a bot read, or work in, a space bots
c.bots.create_token(bot, name=…, expires_in_days=0) (token, info). The token is shown this once bots
c.bots.tokens(bot) / c.bots.revoke_token(token_id) bots

Approvals

Call Returns Scope
c.approvals.list(open_only=True) What bots have asked for: id, thread_id, bot_id, action, status read
c.approvals.approve(gate_id, reason="") approvals
c.approvals.deny(gate_id, reason="…") The bot reads your reason approvals
c.approvals.answer(gate_id, "…") Answers a bot's question approvals

Approving still needs the person behind the key to be allowed to approve it. Most approvals need an admin. See Approvals.

Anything else

  • c.execute(*commands) runs any command and returns the events it made. Several commands run as one all-or-nothing batch.
  • c.raw.<Service>.<Method>(request) makes any call in the API, with your key, deadline and error handling applied.
  • Every request and response type is in caret.pb.
from caret import pb

# Stop every bot working in a thread (needs "messages")
c.execute(pb.Command(stop_bots=pb.StopBots(thread_id=t.id)))

# Search
hits = c.raw.ReadService.Search(pb.SearchRequest(query="Aetna timely filing"))
for h in hits.hits:
    print(h.title, h.snippet)

Events

for event in c.events(kinds=["message_posted", "gate_opened"], space="billing"):
    kind = event.WhichOneof("payload")
    print(event.seq, kind)
  • It runs forever by default (live=True), reconnecting by itself.
  • live=False stops once caught up.
  • after=<seq> resumes after an event you've already handled. Store each event's seq as you go.

See Events for the event kinds.

Errors and retries

Every failure raises caret.CaretError, with .code (the gRPC status) and .reason (Caret's reason, such as SCOPE_MISSING). Subclasses let you catch one kind:

Unauthenticated, PermissionDenied, NotFound, InvalidArgument, FailedPrecondition, Conflict, RateLimited, Unavailable, DeadlineExceeded.

try:
    c.messages.post(thread_id, "Done.")
except caret.PermissionDenied as e:
    print("Not allowed:", e.reason)

Reads and commands are retried up to 4 times on UNAVAILABLE and RESOURCE_EXHAUSTED, with backoff. Commands carry an idempotency key, so a retry never runs them twice. See Errors.

Running your own bot

You can write a bot in Python that lives in Caret like any other: people mention it, and it answers in threads. It runs wherever you run the script.

# Once, with your API key (scope "bots"):
bot = c.bots.register("scout", name="Scout", respond_when="Questions about deploys")
c.bots.grant(bot, "releases")
token, _ = c.bots.create_token(bot, name="prod")      # keep this secret
# The bot itself, with its token (CARET_BOT_TOKEN):
import caret

bot = caret.Bot()

@bot.on_summon
def answer(s):
    thread = s.context().thread
    if s.request_approval("Roll back production", "To yesterday's build."):
        s.reply("Rolled back.")
    else:
        s.reply("Leaving it as it is.")

bot.run()

A summon (s) can .reply(body), .ask(question, options), .request_approval(action, why), read .context(), and check .interrupted. @bot.on_steer handles a person's follow-up while the bot works.

Bot tokens start with cat_ and are for caret.Bot only. Don't pass one to caret.Caret.

Updated · Something wrong or missing? Write to support@caretbot.com.