AI Knowledge & Logic

Event Handlers

Run custom Python code automatically when conversation events occur — close, handoff, and more. Use event handlers for CRM updates, notifications, analytics, and post-conversation workflows.

Event handlers let you run Python code automatically when specific events happen in your conversations. Unlike custom actions (which the AI calls during a conversation), event handlers trigger after key moments — when a conversation is closed, when it's handed off to a human, and more in the future.

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

An event handler can be Python or a webhook. Settings → Automation → Event Handlers covers both: Python (this page) and webhooks. You choose which when you create one. They react to the same events. Reach for Python when the reaction needs logic — deciding, transforming, calling several systems, writing back to the conversation. Reach for a webhook when all you need is "send this event somewhere": it's pure configuration, and comes with signing, automatic retries, a delivery log, and filtering on channel, tags, metadata and handoff state that you'd otherwise write by hand.


Supported events

EventTrigger
Conversation CreatedFires when a new conversation is created
Conversation ClosedFires when a conversation is closed (by agent, bot, or automation)
Conversation Handed OffFires when the bot hands off a conversation to a human agent
CSAT SentFires after a CSAT request email is successfully sent; context["args"]["csat"]["channel"] identifies the channel
Conversation RatedFires when the customer submits a CSAT score; context["args"]["rating"] contains the score and optional comment
Bot Message SentFires each time the bot sends a message
Customer Message SentFires each time the customer sends a message
Agent Message SentFires each time a human agent sends a message
Campaign Recipient UnreachableFires when a phone-campaign recipient goes terminally failed — dial attempts exhausted, or the bot reached voicemail
Campaign Call CompletedFires when a connected phone-campaign call finishes and its transcript is available. Voicemail outcomes fire Campaign Recipient Unreachable instead
Campaign Pre-CallFires before each phone-campaign dial attempt. Can skip the recipient or override its prompt context
Rate Limit HitFires when a rate limit is exceeded and incoming traffic is being dropped
Bot Message QA CompletedFires after a message QA result is stored, including skipped attempts
Tag ModifiedFires when a tag is added to or removed from a conversation
Comment HandledFires when the bot finishes handling a Facebook or Instagram comment, whatever it decided to do with it. See Reacting to comment outcomes
Review Reply HeldFires when a public review reply is written but held for manual review before it auto-posts. See Reacting to reviews
Review Outreach SentFires when a reviewer outreach step happens: a Trustpilot contact request, the initial email or a follow-up. See Reacting to reviews
Review Email Pre-SendRuns 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

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.

Rate Limit Hit is never tied to a conversation — the guards run before one exists. See Reacting to rate limits below.

Tag Modified fires for tag changes made by an agent in the dashboard and through the REST API. context["args"] carries:

FieldDescription
tagThe tag's title
changeadded or removed
sourceWhere 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. Without that, a handler that tags on Tag Modified would trigger itself indefinitely, and each pass costs a real sandbox execution. The trade-off is that one handler cannot chain into another via tags; call the second handler's logic directly, or move the shared part into a Python module.

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.


How it works

  1. You create an event handler — give it a name, select the event type, and write your Python code
  2. When the event occurs on any conversation in your organization, the handler runs automatically
  3. The handler receives full conversation context — messages, metadata, and the event type
  4. Results are logged for debugging and monitoring

You can create multiple handlers for the same event. They all run independently.


Scoping 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. Businesses that aren't in the list are a no-op — the event fires, but the handler's Python code never runs for them.

This is the same business-whitelist mechanism used by custom actions, and it's the recommended way to limit a handler to a single brand (e.g. send Slack notifications for one business only).


Writing 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, and for phone-campaign events where no dial connected — always guard before using it if your handler covers one of those events.


Available helper functions

Event handlers have access to all the same built-in helper functions as custom actions, condition providers, and sidebar widgets — including conversation data, LLM classification, integrations, and more.

See Python Helpers for the full list with documentation links.


Example: 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"}

Example: 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"}

Example: 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"}

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 — it 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"]:

FieldDescription
sourceWhich channel was being protected — see the table below
scopeWhat was being counted: email, domain, business, sender, conversation, browser_session, ip
limitHow many were allowed in the window
window_secondsLength of the window, in seconds
detailsIdentifying details for the specific counter that overflowed. Contents vary by source

Supported source values and what details contains for each:

sourceFires whendetails
inbound_emailAn incoming email was droppedemail, domain
contact_formA contact form submission was droppedemail, domain
meta_inbound_messageA Messenger / Instagram / WhatsApp message was droppedchannel, senderId
web_chat_send_messageA web chat message was rejectedconversationId, browserSessionId
web_chat_new_conversationA new web chat was rejected before it startedbrowserSessionId, 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 shopper 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 bot QA results

Use Bot Message QA Completed to notify your team about message-level 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, and the event payload below for integration details.

The older Bot QA Result event was for conversation-level reviews. It no longer fires from automatic QA. Existing handlers must switch to the new event and payload.


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"]:

FieldDescription
repliedTrue when the bot published a reply — as a public comment, a DM, or both
outcomeWhat 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)
workflowThe 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 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 on both the review workflow path and the legacy category path, for every rating and platform, so filter in your code. Everything arrives under context["args"]["review"]:

FieldDescription
ratingThe star rating, or None when the platform did not send one
channelThe channel the review arrived on, for example trustpilot-reviews
hold_minutesHow long the reply is held before it posts
review_textThe review the reply answers
replyThe reply that will be posted
workflowThe name of the review workflow that wrote the reply. None on the legacy category path

Review Outreach Sent

Fires for each step of private outreach to a reviewer. Everything arrives under context["args"]["review_outreach"]:

FieldDescription
kindWhich 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)
labelA readable description of the step, for example Initial outbound email sent or Follow-up email sent (#2)
step_numberThe 1-based position for sequence_follow_up. None otherwise
reviewer_nameThe reviewer's display name
outbound_conversation_public_idThe email thread with the reviewer. None for reviewer_contact_requested, which sends no email
outbound_conversation_urlDashboard 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 data with 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 under review_outbound.data.
  • Each returned data object is shallow-merged with the saved data. A returned key replaces its previous value, including a whole nested object; None sets the value to JSON null. 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; None greets without a name) and context (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. context applies to that email; put facts needed later in data.
  • Return top-level email_body to 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 returning None keeps the normal email writer. An empty, whitespace-only or non-string value stops the email and hands it off.
  • email_body applies only to the current email and is not carried forward as the next step's body. Recompute it for every invocation using step and email_step; use data for 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_body text 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 return None if you prefer to send with existing data.

The handler is tied to the review conversation. The payload arrives under context["args"]["review_outbound"]:

FieldDescription
step0 for the initial email, n for the nth follow-up
reviewAll 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.
workflowThe 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 for sequences started before this snapshot was available.
email_stepThe current step's delay_days and instructions
dataMerged structured output saved from previous steps, initially {}
review_conversation_idThe review conversation. None in a workflow preview.
outbound_conversation_idThe email thread. None for the initial email.
reviewer_display_nameThe review platform display name
reviewer_emailThe recipient email, retained for follow-ups when available
source, ratingReview platform and star rating, retained for follow-ups when available
review_textThe review text
reviewer_countryTwo-letter country, when known
order_idDeprecated compatibility field for historic sequences and old preview callers. It is not a verified order and is normally absent on new sends. Use the review facts and your own lookup.
testTrue 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. Older sequences may 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 old orderId input remains a deprecated alias for an unverified review reference. It does not trigger an order lookup.


Testing

Event handlers can be tested from the dashboard before they go live.

  1. Open your event handler in the dashboard
  2. Enter a Conversation ID — this loads the real conversation data as context. Use any conversation ID or public ID from your dashboard
  3. Click Run Test
  4. The dashboard executes 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 gives your code a real conversation but no event-specific args, so it can't reproduce a Rate Limit Hit, Bot QA Result, Comment Handled, Review Reply Held, Review Outreach Sent or Review Email Pre-Send payload (for the last, use test_review_workflow as described above). To exercise those handlers, read context["args"].get("rate_limit") / context["args"].get("bot_qa") / context["args"].get("comment") / context["args"].get("review") / context["args"].get("review_outreach") and fall back to a sample value when it's missing.

Tip: Test with conversations that represent different scenarios — short conversations, long ones, ones with file attachments — to make sure your handler is robust.


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_metadata to 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.

Bot message QA

For the concept, dashboard setup and Copilot alert recipes, see Bot 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. Use context["args"]["bot_qa"] to access message_id, evaluation_id, status, skip_reason, overall, action, timing and checks. timing is before_delivery (email, Instagram, Messenger) or after_delivery (web chat, where the customer already has the reply and handoff does not cancel it). 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 requiring conversation investigation.

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"]}

Candidate failures synchronously wait for a bounded verification before the message delivery decision. Only confirmed violations trigger configured reactions. A verdict is pass, violation, na or inconclusive; severity is fixed as critical or improvement. An initial QA failure skips the evaluation and delivery continues. If verification times out, returns invalid output or lacks sufficient evidence, the classifier's suspected violation remains visible with review_status of skipped or inconclusive. It can contribute to the overall grade, but cannot cancel delivery. Filter on verdict == "violation" and review_status == "confirmed" for alerts about verified problems. Other confirmed violations can still trigger their configured reactions. Handlers run asynchronously for notification and reporting. Configure cancellation on the QA check itself with Cancel & hand off; 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.

The older bot_qa_result event belonged to conversation-level QA and is no longer emitted by automatic QA. Update existing listeners to the new event and payload.

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, or None. 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. It never silently switches to the old integration.

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 result

The example covers basic Shopify order fields. Adapt it to the existing selection order and provider data when migrating, 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. The response schema still accepts the old source: "legacy" variant for rollout compatibility, but current readers never return it or fetch old integration data. Existing macro templates and customer messages do not need to change.

On this page