Skip to main content

Python campaign reference

This page is the structural reference for code-based Python campaigns: the campaign statuses, the channels a stage can use, the strategy types and the objects your code receives, and the contact, communication, and result fields. For the task-based walkthrough — creating a campaign, uploading contacts and strategy files, starting it, and reviewing outcomes — see Python Campaigns.

Two campaign builders

Flows is the visual builder and the default choice for most outbound scenarios — its visual editor covers most needs without programming and can still run custom Python in individual steps. Python campaigns are the code-based builder for scenarios that need code-level control the flow editor doesn't offer. Choose by task complexity — neither builder replaces the other.

Campaign status

A campaign moves through four statuses. The status drives the Start / Stop button and shows as a tag in the Python list. To read the message behind a status, open the campaign and use Show Logs in the more-actions menu.

StatusMeaning
CreatedThe campaign exists but is not ready to run — it has no contacts, or no Data Load strategy.
ConfiguredThe campaign has contacts and a Data Load strategy, and is ready to start.
RunningThe campaign is processing contacts and sending communications.
ErrorThe campaign cannot proceed. Find the cause with Show Logs in the more-actions menu.

A campaign becomes Configured only when it has at least one contact and exactly one Data Load strategy. Without both it stays in or returns to Created.

Stages

A stage describes one kind of communication: a channel, the agent that handles it (for channels that use one), and channel-specific settings. Each stage has a Name, an optional Description, and one or more configurations. A configuration always carries a Label, a Weight, and a Channel; the remaining fields depend on the channel. A single stage holds several configurations when you set up A/B testing — see Test variants with A/B testing.

Stages don't run in a fixed order — strategy code sets a contact's current stage by name, so name stages clearly.

Channels and their fields

ChannelChannel-specific fields
TelegramAgent, optional Agent channel, optional start phrase
WhatsAppAgent, optional Agent channel, Template Name (required), Start state (required)
TwilioAgent, Start state (required)
Email NotificationIntegration, Email subject, Email template
Email CommunicationAgent, optional Agent channel, Email subject, Email template
MessageBird (Whatsapp)Agent, optional Agent channel, optional Project ID, optional Version, Start state (required)
SIP (Session Initiation Protocol)Agent
InfobipAgent, optional Agent channel, optional start phrase
Mobile PushAgent
HumanAgent
No CommunicationNone — a terminal configuration with no contact

Start state refers to a state in the agent's workflow (see Advanced mode).

A stage configuration can also carry a list of result form field names, used to map an agent's conversation result into the campaign's results — see Conversation result field types.

Strategy scripts

Strategies are Python functions the campaign engine calls at fixed points in the campaign lifecycle. You write each one as a self-contained .py file and upload it on the Strategies tab; the Function name field names the function to call. There are three strategy types, and a campaign can have one strategy of each.

TypeRunsReceivesReturns
Data LoadWhen contacts are loaded or updated, once per contactcontact, existing_contactThe updated contact, or None to skip it
AggregationWhen a communication finishescontact, session_resultsThe updated contact
Contact answer intermediate analysisAfter each message from the contact during a conversationcontact, messageThe updated contact

A Data Load strategy is required for the campaign to run. Aggregation is needed for any multi-step sequence — it reads the conversation results and decides what happens next.

Function signatures

Each strategy is a function (synchronous or async) named to match the strategy's Function name. The required parameters differ by type:

from flametree.api.marketing.types import Contact


# Data Load
async def run(contact: Contact, existing_contact: Contact) -> Contact | None:
return contact


# Aggregation
async def run(contact: Contact, session_results: dict) -> Contact | None:
return contact


# Contact answer intermediate analysis
async def run(contact: Contact, message) -> Contact | None:
return contact

The engine inspects the function signature and supplies these two optional helpers when you declare a parameter for them (or when the function accepts **kwargs):

ParameterWhat it provides
loggerThe campaign logger. Output appears in Show Logs.
call_sql_functionCalls a PostgreSQL function scoped to the campaign. It takes the function name and an optional dict of named parameters; the campaign is bound automatically, so the function can't reach another campaign.

The strategy returns the contact to persist its changes; a Data Load strategy that returns None skips that contact. If a strategy raises an exception, the contact is left unchanged (a Data Load error sets the contact's status to Error), so log generously and handle errors in code.

Execution constraints

  • Each strategy is one self-contained .py file. The file runs with only Python's built-ins available — no custom modules and no external packages beyond the standard library.
  • The file can hold several functions; only the one named in Function name is called.
  • Aggregation runs without a time limit. Data Load and Contact answer intermediate analysis are bound by a strategy run timeout that defaults to 60 seconds.

The contact object

Strategies read and change the contact through these fields:

FieldTypeDescription
idstringThe contact's identifier, or None before it is first saved.
external_idstringIdentifier of the person in your system, from the imported file.
object_idstringIdentifier of the campaign subject — for example, a contract or order.
name, email, phonestringThe imported contact details.
current_stagestringThe name of the stage the contact is in. Set this to move the contact between stages.
external_datadictThe extra columns from the imported file.
internal_datadictA scratch area your strategies own — for example, a flag that the first communication was planned.
communicationslistThe contact's communications. Append a planned communication to schedule a send.
statusenumThe contact outcome (see Contact outcome status). Defaults to NotProcessed.
campaign_resultsdictNamed result values your code stores (see Campaign result definition).
global_heapdictCampaign-wide data shared across contacts.
summarystringA free-text summary of the contact.

To schedule a send, a strategy appends a Communication to contact.communications with a stage_name that matches a stage, a start_date and finish_date window, and a PLANNED status. The data-load example strategies that ship with the engine do exactly this.

The message object

A Contact answer intermediate analysis strategy also receives a message for the contact's latest reply, with its text, the running session_results, the message number, optional meta, and any attachments.

Contact outcome status

The status on a contact is its outcome, shown in the Outcome column on the Contacts tab. Your strategies set it.

StatusMeaning
NotProcessedThe initial value, before any strategy sets an outcome.
SuccessThe campaign goal was achieved for this contact.
PositiveProgress toward the goal.
UncertainNo clear outcome yet.
NegativeThe campaign was unsuccessful for this contact.
ErrorA technical error occurred.

Communication status

Each communication a contact goes through carries one of these statuses, shown in the communication history.

StatusMeaning
PlannedScheduled to start in its time window.
StartedThe communication is in progress.
CompletedThe communication finished.
InterruptedThe communication was stopped before it finished.
ErrorA technical error occurred.
MissedThe planned start window passed without the communication starting; it is not sent late.

Campaign result definition

Campaign results map the named values your strategy code writes into contact.campaign_results to fields shown in the portal and in 360 View. You define them in the Campaign Results section of the Settings tab. Each result has three keys:

KeyDescription
codeThe key your strategy writes into campaign_results.
nameThe display name shown in the portal.
descriptionA description of the result.

Campaign definition structure

A campaign is exported and imported as a single archive — Export campaign produces a ZIP and a secret key, and Import campaign consumes them. The archive carries one definition with these top-level keys:

KeyHolds
name, descriptionThe campaign name and description.
is_inboundWhether the campaign handles inbound contacts.
resultsThe campaign result definitions (code, name, description).
session_analysis_yamlThe YAML analytics configuration (see Deep analysis YAML).
global_heapThe campaign-wide shared data.
stagesThe stages, each with its name, description, and channel configurations.
strategiesThe strategy definitions — name, type, function_name, and the script file.
resourcesFiles uploaded for the campaign to use.
bots, additional_integrationsThe agents and integrations the stages reference, bundled so the campaign can be rebuilt in another environment.

Was this article helpful?