Event handlers
Run Python automatically when something happens, such as a conversation closing or a call ending.
An event handler is Python code that runs automatically when something happens in Octocom. It keeps your other systems and your team up to date, with no one copying data by hand. For example, when a conversation closes, a handler can write the outcome to your CRM. When the AI agent hands a conversation off, another handler can alert the right Slack channel.
Handlers react to new and closed conversations, handoffs, messages, phone calls, ratings, QA results, failed automations and more. See Supported events for the full list. Unlike custom actions, which the AI agent decides to call during a conversation, event handlers run because the event happened.
Common uses:
- Update your CRM when a conversation closes
- Send a Slack notification when a conversation is handed off
- Log conversation data to an external analytics system
- Trigger a follow-up email or survey after resolution
- Alert your team when a rate limit starts dropping incoming traffic
- Ping a Slack channel when an automated QA review flags a bot reply as critical
Create handlers under Settings -> Automation -> Event Handlers.
Python or webhook
An event handler can be Python (this page) or a webhook. You choose when you create one, and both react to the same events. Use Python when the reaction needs logic: deciding, transforming, calling several systems, writing back to the conversation. Use a webhook when you only need to send the event somewhere: it is pure configuration, with signing, automatic retries, a delivery log and filters on channel, tags, metadata and handoff state. For work on a schedule rather than on an event, use a recurring job.
How it works
- You create an event handler: a name, the event type and your Python code.
- When the event occurs in your organization, the handler runs automatically.
- The handler receives the conversation context (messages, metadata, customer) and the event's details in
context["args"]. - Each run is recorded for debugging and monitoring.
You can create several handlers for the same event. They all run independently. Handlers run asynchronously, after the event, except the hooks listed under Supported events, which run before Octocom continues.
Scope a handler to specific businesses
By default a handler runs for every business in your organization. If you only want it to run for some businesses, set its Scope to "Only specific businesses" and pick them. For businesses that aren't in the list, the event still fires but the handler's code never runs.
Custom actions use the same business scoping. It is the recommended way to limit a handler to one brand, for example to send Slack notifications for one business only.
Supported events
| Event | Trigger |
|---|---|
| Conversation Created | Fires when a new conversation is created |
| Conversation Closed | Fires when a conversation is closed (by agent, bot, or automation) |
| Conversation Handed Off | Fires when the bot hands off a conversation to a human agent |
| CSAT Sent | Fires after a CSAT request email is successfully sent; context["args"]["csat"]["channel"] identifies the channel |
| Conversation Rated | Fires when the customer submits a CSAT score; context["args"]["rating"] contains the score and optional comment |
| Bot Message Sent | Fires each time the bot sends a message |
| Customer Message Sent | Fires each time the customer sends a message, except the first message of a conversation, which fires Conversation Created |
| Agent Message Sent | Fires each time a human agent sends a message |
| Campaign Recipient Unreachable | Fires when a phone-campaign recipient can no longer be reached: dial attempts are exhausted, or the bot reached voicemail |
| Campaign Call Completed | Fires when a connected phone-campaign call finishes and its transcript is available. Voicemail outcomes fire Campaign Recipient Unreachable instead |
| Phone Call Completed | Fires when a phone bot call ends and its transcript is saved, for inbound and outbound calls. See Reacting to phone calls |
| Campaign Pre-Call | Runs before each phone-campaign dial attempt. Can skip the recipient or override its prompt context. See Reacting to campaign events |
| Rate Limit Hit | Fires when a rate limit is exceeded and incoming traffic is being dropped. See Reacting to rate limits |
| Bot Message QA Completed | Fires after a message QA result is stored, including skipped attempts. See Reacting to bot QA results |
| Bot Conversation QA Completed | Fires once per conversation after its whole-conversation QA checks are stored. See Reacting to bot QA results |
| Tag Modified | Fires when a tag is added to or removed from a conversation. See Reacting to tag changes |
| Comment Handled | Fires when the bot finishes handling a Facebook or Instagram comment, whatever it decided to do with it. See Reacting to comment outcomes |
| Review Reply Held | Fires when a public review reply is written but held for manual review before it auto-posts. See Reacting to reviews |
| Review Outreach Sent | Fires when a reviewer outreach step happens: a Trustpilot contact request, the initial email or a follow-up. See Reacting to reviews |
| Review Email Pre-Send | Runs before each review workflow email. Python can fetch customer data, skip sending, return structured facts or supply the final email body. See Deciding review emails |
| Macro Data | Runs when an agent applies a macro that uses order or subscription fields, and supplies those values. See Supplying macro data |
| Automation Execution Failed | Fires when a custom action or condition provider fails after it started running. See Reacting to automation failures |
| Metric Alert | Fires when a metric alert changes state: a chart series starts or stops meeting its condition. See Reacting to metric alerts |
Each event handler is configured for exactly one event type. The per-message events (Bot / Customer / Agent Message Sent) fire once for every matching message, so keep their handlers lightweight.
Campaign Pre-Call, Review Email Pre-Send and Macro Data are hooks: Octocom runs the one matching handler synchronously and uses its return value, so at most one active handler of each may cover a business, and they cannot be webhooks. A Metric Alert handler reacts to the metric alerts you define; Copilot can create the alert and its handler together.
Create Tag Modified and Metric Alert handlers through Copilot or MCP (create_event_handler with the event type tag_modified or metric_alert). The dashboard's event picker lists the other events.
Write an event handler
An event handler implements a handle_event function. It receives the same context object as custom actions.
import requests
def handle_event(context):
event_type = context["args"]["event_type"]
conversation = context["conversation"]
# Post to your webhook
requests.post("https://api.example.com/webhook", json={
"event": event_type,
"conversationId": conversation["publicId"],
"subject": conversation["subject"],
"messageCount": len(conversation["messages"]),
}, timeout=30)
return {"status": "notified"}Context structure
The context object contains conversation data, customer profile, business info, and the event type via context["args"]["event_type"]. See Python context for the full reference.
context["conversation"] is present for every conversation event. It is None for Rate Limit Hit, which fires before any conversation exists, for Metric Alert, and for phone-campaign events where no dial connected. Guard before using it if your handler covers one of those events.
Helpers
Event handlers can call every built-in helper, the same as custom actions, condition providers and sidebar widgets: conversation data, LLM classification, integrations and more. Active Python modules and secrets are available too.
See Python helpers for the full list.
Examples
CRM update on conversation close
Update your CRM with conversation summary data when a conversation is resolved.
import requests
def handle_event(context):
conversation = context["conversation"]
messages = conversation["messages"]
customer_messages = [m for m in messages if m["sender"] == "customer"]
requests.post("https://api.example.com/crm/conversations", json={
"externalId": conversation["publicId"],
"subject": conversation["subject"],
"messageCount": len(messages),
"customerMessageCount": len(customer_messages),
"resolvedAt": messages[-1]["timestamp"] if messages else None,
}, timeout=30)
return {"status": "synced"}Slack notification on handoff
Alert your team when a conversation needs human attention.
import requests
def handle_event(context):
conversation = context["conversation"]
messages = conversation["messages"]
# Get last few customer messages for context
recent = [m["content"] for m in messages if m["sender"] == "customer"][-3:]
requests.post("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", json={
"text": f"Conversation {conversation['publicId']} handed off",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"*Handoff:* {conversation['subject']}\n*ID:* {conversation['publicId']}\n*Recent messages:*\n" + "\n".join(f"> {m}" for m in recent)
}
}
]
}, timeout=10)
return {"status": "notified"}Google Sheets logging
Log every closed conversation to a Google Sheet for reporting.
def handle_event(context):
conversation = context["conversation"]
messages = conversation["messages"]
add_google_sheets_row("YOUR_SPREADSHEET_ID", {
"Conversation ID": conversation["publicId"],
"Subject": conversation["subject"],
"Messages": len(messages),
"Closed At": messages[-1]["timestamp"] if messages else "",
"Business": conversation["businessSlug"],
})
return {"status": "logged"}Event reference
The sections below describe what each event delivers in context["args"] and how to use it.
Reacting to tag changes
Tag Modified fires for tag changes made by an agent in the dashboard and through the REST API. context["args"] carries:
| Field | Description |
|---|---|
tag | The tag's title |
change | added or removed |
source | Where the change came from (agent, api, ...) |
One handler covers both directions: branch on change rather than writing a pair.
def handle_event(context):
args = context["args"]
if args["change"] != "added" or args["tag"] != "needs-refund-review":
return None
add_conversation_note(context, "Queued for refund review.")
return {"queued": True}Tag changes made by Python (add_conversation_tag and
remove_conversation_tag) deliberately do not fire this event. Otherwise
a handler that tags on Tag Modified would trigger itself indefinitely. As
a result, one handler cannot chain into another through tags: call the second
handler's logic directly, or move the shared part into a Python
module.
Reacting to campaign events
The phone-campaign events carry a conversation only when a dial actually connected, so Campaign Recipient Unreachable and Campaign Pre-Call handlers must tolerate context["conversation"] being None. The campaign and recipient details arrive in context["args"]["campaign"] regardless. context["args"]["campaign"]["recipient"]["isTest"] is True for test calls placed from the campaign page, so a Campaign Pre-Call handler can return test context for them instead of looking up real data. See Campaign events and hooks for when each campaign event fires, what a Campaign Pre-Call handler can return, and recipes for common campaign setups.
Reacting to rate limits
Octocom applies rate limits to incoming traffic to protect your inbox from floods, mailing-list loops, and abuse. When one of these limits is exceeded, the offending message is dropped or rejected and never becomes a conversation.
The Rate Limit Hit event lets you react to that: page an on-call channel, open a ticket in your own system, or record it for reporting.
The rate_limit object
Everything about the tripped limit arrives under context["args"]["rate_limit"]:
| Field | Description |
|---|---|
source | Which channel was being protected (see the table below) |
scope | What was being counted: email, domain, business, sender, conversation, browser_session, ip |
limit | How many were allowed in the window |
window_seconds | Length of the window, in seconds |
details | Identifying details for the specific counter that overflowed. Contents vary by source |
Supported source values and what details contains for each:
source | Fires when | details |
|---|---|---|
inbound_email | An incoming email was dropped | email, domain |
contact_form | A contact form submission was dropped | email, domain |
meta_inbound_message | A Messenger / Instagram / WhatsApp message was dropped | channel, senderId |
web_chat_send_message | A web chat message was rejected | conversationId, browserSessionId |
web_chat_new_conversation | A new web chat was rejected before it started | browserSessionId, ip |
context["business"] tells you which business was affected. context["conversation"] is always None for this event.
How often it fires
The event is deduplicated per counter and per window, so a sustained flood produces a steady trickle rather than one event per blocked message. There is also a five-minute floor between repeat events for the same counter, so short-window limits can't fire more than about twelve times an hour each.
Some scopes are noisier than others by design. business scope means real volume is being turned away and is almost always worth acting on. The per-visitor scopes (ip, browser_session, conversation) trip during ordinary use (one visitor opening several chats in a minute is enough), so branch on scope rather than alerting on everything.
Example: alert your team when email is being dropped
import requests
def handle_event(context):
rate_limit = context["args"]["rate_limit"]
# Only care about email, and only when it's an org-wide flood
if rate_limit["source"] not in ("inbound_email", "contact_form"):
return {"status": "ignored"}
if rate_limit["scope"] not in ("domain", "business"):
return {"status": "ignored"}
business = context["business"]
details = rate_limit["details"]
hours = rate_limit["window_seconds"] / 3600
requests.post("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", json={
"text": (
f"Incoming email is being dropped for {business['slug']}\n"
f"Scope: {rate_limit['scope']} ({details.get('domain', 'n/a')})\n"
f"Limit: {rate_limit['limit']} per {hours:g}h"
)
}, timeout=10)
return {"status": "notified"}Example: log every trip to a Google Sheet
from datetime import datetime, timezone
def handle_event(context):
rate_limit = context["args"]["rate_limit"]
details = rate_limit["details"]
add_google_sheets_row("YOUR_SPREADSHEET_ID", {
"Time": datetime.now(timezone.utc).isoformat(),
"Business": context["business"]["slug"],
"Source": rate_limit["source"],
"Scope": rate_limit["scope"],
"Limit": rate_limit["limit"],
"Window (s)": rate_limit["window_seconds"],
"Who": details.get("email") or details.get("senderId") or details.get("ip") or "",
})
return {"status": "logged"}Reacting to metric alerts
A metric alert watches a saved chart and decides when something happened. It notifies nobody on its own: a Metric Alert handler decides what happens, such as posting to Slack, emailing a team lead or opening a ticket. The event is never tied to a conversation, so context["conversation"] is None. Everything about the check arrives under context["args"]["metric_alert"]; the alert page describes every field.
def handle_event(context):
alert = context["args"]["metric_alert"]
firing = [s for s in alert["series"] if s["state"] == "firing"]
if not firing:
return {"status": "nothing new"}
lines = [
f"• {s['key'] or 'Total'}: {s['baseline']} -> {s['value']}"
+ (f" (+{s['change_pct']:.0f}%)" if s["change_pct"] is not None else "")
for s in firing
]
send_slack_notification(
get_secret("ALERTS_SLACK_WEBHOOK"),
f"*{alert['alert_name']}*\n" + "\n".join(lines) + f"\n<{alert['chart']['url']}|Open chart>",
)
return {"status": "notified", "series": len(firing)}A handler scoped to every business receives every alert. A handler limited to specific businesses receives only alerts that cover exactly one of its businesses, because an alert over several businesses belongs to the whole organization. In that case context["business"] is a business of your organization, kept so helpers work; read alert["business_ids"] to see what the alert covered.
Reacting to automation failures
Automation Execution Failed fires when a custom action or a condition provider raises an exception or returns an invalid result, so you can alert your team the moment an API your automations depend on starts failing. It does not fire for test conversations, or when your code catches an error and returns it as a normal result. context["conversation"] is the conversation the bot was answering, so context["conversation"]["url"] links to it. The failure arrives under context["args"]["automation_failure"]:
| Field | Description |
|---|---|
execution_type | custom_action or condition_provider |
automation_id | ID of the action or condition provider |
automation_name | Its name |
language | python |
failure_kind | exception, invalid_result or unknown |
reason | The error, up to 2,000 characters. A longer traceback keeps its first lines and its end, which holds the exception that failed (status, host, timeout) |
execution_id | ID of the stored execution record |
The event fires once per failure, so an outage of an API you call can fire it hundreds of times an hour. Throttle the notification with the organization store, for example by posting only the first failure of each automation per hour:
import time
def handle_event(context):
failure = context["args"]["automation_failure"]
# Store keys only allow letters, digits and ._:@+-, so key by ID, not name.
key = failure["automation_id"]
try:
organization_store_create("failure-alerts", key, {"at": time.time()}, ttl_seconds=3600)
except OrganizationStoreConflictError:
return {"status": "already alerted this hour"}
last_line = failure["reason"].strip().splitlines()[-1]
send_slack_notification(
get_secret("ALERTS_SLACK_WEBHOOK"),
f"*{failure['automation_name']}* failed: {last_line}\n<{context['conversation']['url']}|Open conversation>",
)
return {"status": "notified"}Error text can contain customer data, such as an email address in a request URL. Remove it before posting the reason to a chat tool.
Reacting to bot QA results
Use Bot Message QA Completed and Bot Conversation QA Completed to notify your team about Bot QA findings. Copilot can set up event handlers for Slack or email alerts, including filters for confirmed violations, severity or a specific check. See Bot QA for setup and common alert patterns.
Bot message QA
The bot_message_qa_completed event fires after a message and its QA result are stored. It applies to AI-written replies on email, Instagram, Messenger and web chat when automatic QA is enabled. Fixed messages, such as web chat greetings and automation messages, are not checked and do not fire it.
context["args"]["bot_qa"] contains:
| Field | Description |
|---|---|
message_id | The checked message. Match it against id in context["conversation"]["messages"] |
evaluation_id | The QA evaluation |
status, skip_reason | Whether the evaluation ran, and why it was skipped |
overall | The overall grade |
action | The delivery decision: continue, or handoff when a confirmed violation on a Hand off to a person check stopped the reply |
timing | before_delivery (email, Instagram, Messenger) or after_delivery (web chat, where the customer already has the reply and a handoff does not cancel it) |
checks | One entry per check, described below |
Each check includes check_id, check_key, check_title, check_revision, verdict, severity, on_violation, classifier_verdict, review_status and review_decision. Confirmed failures also include summary, explanation and evidence. Evidence contains reference_id, source and an exact excerpt; other outcomes have null failure fields. These findings explain the decision without opening the conversation.
Find the checked message by matching its id in the conversation transcript.
Handlers run asynchronously, so the last bot message may be newer than the one
that triggered this event.
def handle_event(context):
qa = context["args"]["bot_qa"]
message = next(
(m for m in context["conversation"]["messages"] if m["id"] == qa["message_id"]),
None,
)
if message is None:
return {"status": "message_unavailable"}
return {"message_id": message["id"], "content": message["content"], "overall": qa["overall"]}How verdicts work:
- A verdict is
pass,violation,naorinconclusive. Severity iscriticalorimprovement. - A suspected failure is verified before the message is delivered, within a short time limit. Only confirmed violations trigger the reactions configured on the check.
- If verification times out, returns invalid output or lacks sufficient evidence, the suspected violation stays visible with
review_statusofskippedorinconclusive. It can contribute to the overall grade, but cannot cancel delivery. - If the QA run itself fails, the evaluation is skipped and delivery continues.
- For alerts about verified problems, filter on
verdict == "violation"andreview_status == "confirmed".
Handlers are for notification and reporting. To stop a message, configure Hand off to a person on the QA check itself; the event's action reports that decision. continue does not mean the channel has delivered the message yet.
QA uses successful tool execution as evidence for the corresponding action.
A successful transferConversation call supports a handoff confirmation even
when the final message is scheduled for later delivery. A handoff does not prove
that the team has already reviewed the case or completed a refund or cancellation;
those claims require their own evidence.
Whole-conversation QA
The bot_conversation_qa_completed event fires once per conversation, after its
whole-conversation checks are stored: right after a phone bot call ends, or two
days after another conversation closes. Use context["args"]["bot_qa"] to access
evaluation_id, scope (always conversation), trigger (call_ended or
closed), status, skip_reason, overall and checks. Checks carry the same
fields as message QA except on_violation: whole-conversation checks only record
findings. Alert on verdict == "violation" with review_status == "confirmed".
def handle_event(context):
qa = context["args"]["bot_qa"]
confirmed = [
c for c in qa["checks"]
if c["verdict"] == "violation" and c["review_status"] == "confirmed"
]
return {"trigger": qa["trigger"], "confirmed": [c["check_key"] for c in confirmed]}Reacting to comment outcomes
When a customer comments on one of your Facebook or Instagram posts (or mentions your page), the bot runs your comment workflows and either replies, hides or deletes the comment, or hands it to an agent. The Comment Handled event fires once per comment after that decision has been carried out, so you can be told when the bot answered publicly, keep a log of what it did, or alert someone when it gave up.
It fires for every outcome, not just replies, so branch on replied (or outcome) rather than assuming the bot answered.
The comment object
Everything about the outcome arrives under context["args"]["comment"]:
| Field | Description |
|---|---|
replied | True when the bot published a reply: a public comment, a DM, or both |
outcome | What the bot did: response_comment (public reply), response_dm (private reply), response_comment_and_dm (both), hidden_and_dm (hid the comment, replied privately), hidden, deleted, liked (liked the comment, no reply), handed_off (handed to an agent: the workflow chose handoff, declined to reply, Meta refused the DM, or the action is not supported on this channel), or no_relevant (no workflow matched; handed off or closed, per the business's "When no workflow matches" setting) |
workflow | The name of the comment workflow that ran. None when no workflow matched |
context["conversation"] is always present for this event. Its messages carry the customer's comment text, and conversation["url"] links to it in the dashboard. Replies sent by DM live in a separate conversation, linked from this one's activity log.
Example: Slack notification when the bot replies to a comment
import requests
SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
def handle_event(context):
comment = context["args"]["comment"]
if not comment["replied"]:
return {"status": "ignored", "outcome": comment["outcome"]}
conversation = context["conversation"]
customer_text = next(
(m["content"] for m in conversation["messages"] if m["sender"] == "customer"),
"",
)
requests.post(SLACK_WEBHOOK_URL, json={
"text": (
f"Bot replied to a comment for {conversation['businessSlug']} "
f"({comment['outcome']}, workflow: {comment['workflow']})\n"
f"> {customer_text[:300]}\n"
f"<{conversation['url']}|Open conversation>"
)
}, timeout=10)
return {"status": "notified"}Reacting to phone calls
Phone Call Completed fires once per call the phone bot took, after the call ends and its transcript, language and workflow usage are saved. It covers inbound and outbound calls, including campaign calls (which also fire the campaign events). If the voice AI can't take a call, the call goes straight to your team and the event still fires, with an empty transcript and duration_seconds of 0. Calls to lines answered only by your team do not fire it.
context["conversation"] is always present: its messages are the call transcript and conversation["url"] links to it in the dashboard. Everything about the call arrives under context["args"]["phone_call"]:
| Field | Description |
|---|---|
call_id | Octocom's ID for the call |
direction | inbound or outbound |
from_number | The number that placed the call |
to_number | The number that was called. For inbound calls this is your phone line |
duration_seconds | How long the bot was on the call. 0 when the bot never answered |
language | The conversation language code as stored, for example en, de-DE or GR. It is not normalised to ISO codes. None when unknown |
workflows | Titles of the workflows the bot used during the call, in the order it first used them. Empty when it used none |
handed_off | True when the call was handed to a person |
ended_by | customer (the caller hung up), bot (the bot ended the call) or None when not reported |
transfer_destination | Where the call was transferred: the dialled number or SIP address, self for a transfer to the same line's team, or None when it was not transferred |
is_test_call | True for calls from a test number or the playground. Most notification handlers should return early when this is set |
Example: Slack ping for every real phone call
SLACK_WEBHOOK_SECRET = "PHONE_CALLS_SLACK_WEBHOOK"
def handle_event(context):
call = context["args"].get("phone_call")
if not call:
return {"status": "skipped", "reason": "no phone_call payload (test run)"}
if call["is_test_call"]:
return {"status": "ignored", "reason": "test call"}
conversation = context["conversation"]
send_slack_notification(
get_secret(SLACK_WEBHOOK_SECRET),
f"New phone call for {context['business']['name']} "
f"({call['duration_seconds']}s, workflows: {', '.join(call['workflows']) or 'none'})\n"
f"<{conversation['url']}|{conversation['publicId']}>",
)
return {"status": "notified"}Reacting to reviews
Two events cover what the review bot does with Trustpilot and other review platforms. Both are tied to the review conversation, so context["conversation"] is always present: its messages carry the review text, and conversation["url"] links to the review in the dashboard. context["business"] has the business name and slug.
They fire whether or not the business has a Slack webhook configured in its review settings, so you can route notifications per brand, filter by rating, or log to a sheet.
Review Reply Held
Fires when the bot has written a public reply but your review settings hold replies for manual review. The reply posts automatically after the hold window unless an agent edits or cancels it. It fires for every rating and platform, whether or not a review workflow wrote the reply, so filter in your code. Everything arrives under context["args"]["review"]:
| Field | Description |
|---|---|
rating | The star rating, or None when the platform did not send one |
channel | The channel the review arrived on, for example trustpilot-reviews |
hold_minutes | How long the reply is held before it posts |
review_text | The review the reply answers |
reply | The reply that will be posted |
workflow | The name of the review workflow that wrote the reply. None when no review workflow wrote it |
Review Outreach Sent
Fires for each step of private outreach to a reviewer. Everything arrives under context["args"]["review_outreach"]:
| Field | Description |
|---|---|
kind | Which step: reviewer_contact_requested (Trustpilot was asked for an unidentified reviewer's contact details), initial_email, follow_up_1, follow_up_2, or sequence_follow_up (a review workflow's email sequence) |
label | A readable description of the step, for example Initial outbound email sent or Follow-up email sent (#2) |
step_number | The 1-based position for sequence_follow_up. None otherwise |
reviewer_name | The reviewer's display name |
outbound_conversation_public_id | The email thread with the reviewer. None for reviewer_contact_requested, which sends no email |
outbound_conversation_url | Dashboard link to that email thread, or None |
Example: Slack alert for held low-star Trustpilot replies
SLACK_WEBHOOK_SECRET = "REVIEW_ALERTS_SLACK_WEBHOOK"
def handle_event(context):
review = context["args"].get("review")
if not review:
return {"status": "skipped", "reason": "no review payload (test run)"}
if review["channel"] != "trustpilot-reviews":
return {"status": "ignored", "channel": review["channel"]}
if review["rating"] is not None and review["rating"] > 3:
return {"status": "ignored", "rating": review["rating"]}
business = context["business"]
conversation = context["conversation"]
send_slack_notification(
get_secret(SLACK_WEBHOOK_SECRET),
f"*{business['name']}* {review['rating']} star reply held for "
f"{review['hold_minutes']} min: <{conversation['url']}|review, edit, or cancel>",
)
return {"status": "notified"}Deciding review emails
Review Email Pre-Send (review_outbound_pre_send) runs before each private email in a review workflow, including every follow-up. Python receives the review facts and selected workflow, looks up any customer data it needs, and returns structured facts for the email writer or a finished email body. Octocom does not perform an order lookup or require an order number. Your handler can work with orders, subscriptions, customers or any other records.
- At most one active handler may cover a business. Saving a second one that overlaps is refused.
- Return
None(or{}) to send with the data already available. - Return
{"skip": True, "reason": "..."}to stop the email. The review is handed to your team with the reason. For a follow-up, the sequence ends and the email thread comes back to the queue. - Return
datawith any JSON key-value pairs, including nested objects and arrays. The email writer receives this as structured data. Octocom saves it for follow-ups and passes it to the next invocation underreview_outbound.data. - Each returned
dataobject is shallow-merged with the saved data. A returned key replaces its previous value, including a whole nested object;Nonesets the value to JSONnull. Omitted keys keep their previous values. The merged object may contain up to 20,000 JSON characters. - You can also return
customer_name(the greeting name, up to 100 characters;Nonegreets without a name) andcontext(extra instructions for the email writer, up to 2,000 characters). The greeting name is retained for follow-ups unless a later hook overrides it.contextapplies to that email; put facts needed later indata. - Return top-level
email_bodyto supply the complete plain-text body, including its greeting and sign-off, already in the intended recipient's language. Octocom uses it verbatim, without model rewriting or translation. Omitting it or returningNonekeeps the normal email writer. An empty, whitespace-only or non-string value stops the email and hands it off. email_bodyapplies only to the current email and is not carried forward as the next step's body. Recompute it for every invocation usingstepandemail_step; usedatafor reusable facts. A later step that omits it uses the normal writer.- The normal writer's initial emails, follow-ups and previews receive a separate translation pass based on the review text. English or undetermined review language, or a translation failure, keeps the generated body unchanged. Finished
email_bodytext bypasses this pass. - Exceptions, timeouts, invalid output, unexpected top-level keys and oversized data stop the email and hand it off. Put custom output keys inside
data. Catch your own exceptions and returnNoneif you prefer to send with existing data.
The handler is tied to the review conversation. The payload arrives under context["args"]["review_outbound"]:
| Field | Description |
|---|---|
step | 0 for the initial email, n for the nth follow-up |
review | All stored review metadata and normalized review facts, with the original provider payload under platform_data when available. Keys use camelCase, such as reviewId, reviewText, reviewRating, source, contactable, reviewerName, reviewerEmail, reviewerCountry, orderReference, trustpilotSource and trustpilotReviewType. Available fields depend on the platform and review. |
workflow | The selected workflow configuration, using its usual camelCase field names, including id, name, whenToFollow, botInstructions, action, emailSteps and filters. Follow-ups receive the saved configuration. Database timestamps are omitted. None when the sequence has no saved workflow. |
email_step | The current step's delay_days and instructions |
data | Merged structured output saved from previous steps, initially {} |
review_conversation_id | The review conversation. None in a workflow preview. |
outbound_conversation_id | The email thread. None for the initial email. |
reviewer_display_name | The review platform display name |
reviewer_email | The recipient email, retained for follow-ups when available |
source, rating | Review platform and star rating, retained for follow-ups when available |
review_text | The review text |
reviewer_country | Two-letter country, when known |
test | True in test_review_workflow, which sends nothing. Your Python should avoid side effects when this is set. |
The review and workflow snapshots remain available across the email sequence. Some sequences have fewer facts: handle missing values and use your own API to refresh customer state when needed.
For example, this handler looks up a subscription using the reviewer's email or the unverified reference supplied with the review. Replace the example endpoint and secret with your own API:
import requests
def handle_event(context):
outbound = context["args"].get("review_outbound")
if not outbound:
return None # event-handler test without a review payload
review = outbound["review"]
email = outbound.get("reviewer_email") or review.get("reviewerEmail")
reference = review.get("orderReference")
if not email and not reference:
return {"skip": True, "reason": "no customer lookup details"}
response = requests.get(
"https://api.example.com/subscriptions/find",
headers={"Authorization": f"Bearer {get_secret('CUSTOMER_API_TOKEN')}"},
params={"email": email, "reference": reference},
timeout=15,
)
response.raise_for_status()
subscription = response.json()
if not subscription:
return {"skip": True, "reason": "subscription not found"}
return {
"customer_name": subscription.get("customer_name"),
"data": {
"customer_id": subscription["customer_id"],
"subscription_id": subscription["id"],
"subscription_status": subscription["status"],
"latest_renewal": subscription.get("latest_renewal"),
},
"context": "Use the subscription facts when following the email instructions.",
}A later step can read outbound["data"].get("subscription_id") to refresh the same subscription or use the other saved facts. Python decides whether a record is required and which record relates to the review.
When Python has rendered the final text for the current step, it can instead return a complete body. For example, for a Spanish-speaking recipient:
return {
"email_body": "Hola,\n\n¿Necesitas ayuda con tu suscripción? Responde a este correo para que podamos ayudarte.\n\nEquipo de atención",
"data": {"subscription_id": subscription["id"]},
}The body's paragraph breaks and text are preserved. customer_name, context and workflow email instructions do not rewrite a supplied email_body; render all required details into it yourself.
Preview with test_review_workflow, passing reviewerEmail, an optional reviewReference and any additional reviewData. The handler receives the same payload with test set; the result includes its decision, merged preSendHook.data and the email it would produce. The review reference is unverified and does not trigger an order lookup.
Supplying macro data
Macro Data (macro_data) runs synchronously when an agent applies a saved reply that uses lastOrder or lastSubscription variables. It is a code handler, not a webhook. At most one active handler may cover a business. Limit the handler to the businesses whose integrations it reads.
Use read-only lookups. context["customer"] provides the current customer's email and phone. context["args"]["macro_data"] contains:
resources:['order'],['subscription'], or both. Only look up the requested resources.order_id: the order selected on the conversation, orNone. Prefer it to an email lookup to keep the agent's selected order.
Return an object with lastOrder and/or lastSubscription. Supported string fields are lastOrder.orderPlacedAt, trackingId, trackingUrl, orderId, statusPageUrl, and lastSubscription.nextChargeDate. Dates are inserted as supplied. Each string is limited to 4,096 characters; other fields are discarded. Missing or null fields become empty strings. Return {} for no matching records. A handler failure or invalid result blocks applying the macro and leaves the draft unchanged.
def handle_event(context):
requested = context["args"].get("macro_data") or {"resources": ["order", "subscription"], "order_id": None}
result = {}
email = (context.get("customer") or {}).get("email")
if "order" in requested["resources"]:
order = None
if requested.get("order_id"):
order = shopify_get_order(context, requested["order_id"])
if not order and email:
orders = shopify_find_orders(context, email)
order = orders[0] if orders else None
if order:
fulfillment = (order.get("fulfillments") or [{}])[0]
tracking = (fulfillment.get("trackingInfo") or [{}])[0]
result["lastOrder"] = {
"orderId": order.get("name") or "",
"orderPlacedAt": order.get("createdAt") or "",
"trackingId": tracking.get("number") or "",
"trackingUrl": tracking.get("url") or "",
}
return resultThe example covers basic Shopify order fields. Adapt it to your own order source and the fields your saved replies use, including a status-page URL if any saved reply needs one. Shopify's general order helpers omit that URL. Subscription providers can use recharge_find_subscriptions/recharge_next_charge_date or loop_find_subscriptions/loop_next_charge_date to populate lastSubscription.nextChargeDate.
Saved replies with order or subscription variables require an active Macro Data handler for their business. A missing handler returns a precondition error (HTTP 412 in REST); the dashboard leaves the draft unchanged and asks an administrator to configure the automation. Macros using only customer, agent, business or metadata fields need no handler and make no lookup calls.
Use test_event_handler with an existing conversation (the example defaults to both resources in test runs), then verify the active provider with get_macro_data or GET /rest/v1/conversations/{publicId}/macro-data?resource=both. MCP and REST return the same source: "provider" shape.
Testing
Event handlers can be tested from the dashboard before they go live.
- Open your event handler in the dashboard.
- Enter a Conversation ID. This loads the real conversation data as context. Use any conversation ID or public ID from your dashboard.
- Click Run Test.
- The dashboard runs your code and shows the result, stdout and stderr.
The test simulates the event without actually triggering it. The selected event type from the form is passed as context["args"]["event_type"].
Note: Testing from the dashboard gives your code a real conversation but no event-specific
args, so it can't reproduce a Rate Limit Hit, Bot Message QA Completed, Bot Conversation QA Completed, Comment Handled, Phone Call Completed, Review Reply Held, Review Outreach Sent or Review Email Pre-Send payload (for the last, usetest_review_workflowas described above). To exercise those handlers, readcontext["args"].get("rate_limit")/context["args"].get("bot_qa")/context["args"].get("comment")/context["args"].get("phone_call")/context["args"].get("review")/context["args"].get("review_outreach")and fall back to a sample value when it's missing.Through MCP and Copilot,
test_event_handlertakes an optionaleventArgsand no conversation for conversation-less events. For a Metric Alert handler, runtest_metric_alertfirst and pass itseventArgsas{"metric_alert": ...}. The handler really runs, so a test Slack message is really sent.
Tip: Test with conversations that represent different scenarios (short conversations, long ones, ones with file attachments) to make sure your handler is robust.
Manage handlers with Copilot or MCP
| Tool | Purpose |
|---|---|
list_event_handlers, get_event_handler | Find handlers and read their code |
create_event_handler, update_event_handler | Create or change a handler |
test_event_handler | Run a handler with a conversation and optional eventArgs |
archive_event_handler, restore_event_handler | Archive a handler or bring it back |
Limits and best practices
- Keep handlers fast. Event handlers run asynchronously with a five-minute elapsed-time timeout, including network waits, and a separate 30-second CPU budget that excludes network waits. Campaign pre-call handlers keep a 60-second deadline because they gate call dispatch. Paginate or batch I/O-bound work; avoid heavy computation and make external effects idempotent.
- Handle errors gracefully. If your external API is down, catch the exception and return an error status rather than crashing. Failed executions are logged for debugging.
- Use metadata for state. If you need to track whether a handler has already processed a conversation, use
set_conversation_metadata/get_conversation_metadatato avoid duplicate processing. - Be idempotent. Events may occasionally trigger more than once. Design your handlers so running them twice on the same conversation produces the same result.
- Check the event type. If you plan to reuse similar logic across events, check
context["args"]["event_type"]to branch behavior. - Stay inside the REST API budget. Event handlers and recurring jobs of an organization share 1,000 REST API requests a minute, and any one of them can make at most 300. Helpers such as the organization store count too. See REST API rate limits.