Skip to content

Your agent sends a message into a conversation, called a space, as one of its own users. The simplest message to send is a reply: the message you're answering already tells you the space and the agent user to send as. In this guide, you reply to the message from Receive messages, then turn the listener into an agent that echoes supported non-Email text messages.

Prerequisites

You need:

The one-shot reply examples below do not skip Email. If you choose an Email Message for the one-shot test, read Replies to understand who can receive the reply.

1

Find what to reply with

Each received message carries the IDs for its reply. Pick a message that Receive messages printed, and save three of its IDs as environment variables:

From the received messageEnvironment variableSend it asWhat it is
idPHOTON_MESSAGE_IDparentMessageIdThe message you're replying to. Optional.
space.idPHOTON_SPACE_IDspaceIdThe conversation.
receivedBy.idPHOTON_SENDER_IDsenderIdYour agent's user, so the reply comes from the number or address the person messaged.
Code
export PHOTON_MESSAGE_ID="pho_msg_REPLACE_WITH_THE_MESSAGE_ID"
export PHOTON_SPACE_ID="pho_spc_REPLACE_WITH_THE_SPACE_ID"
export PHOTON_SENDER_ID="pho_usr_REPLACE_WITH_THE_RECEIVEDBY_ID"

Every send also needs an Idempotency-Key header. If a request times out, send it again with the same key, and Photon sends the message only once. Build the key from the message you're answering, such as reply-<message ID>.

2

Send a reply

Save this as reply.ts, reply.py, src/bin/reply.rs, or reply.go. It replies to the message you picked:

import { Photon } from "@photon-ai/api";

const { PHOTON_API_KEY, PHOTON_PROJECT_ID, PHOTON_MESSAGE_ID, PHOTON_SPACE_ID, PHOTON_SENDER_ID } = process.env;
if (!PHOTON_API_KEY || !PHOTON_PROJECT_ID || !PHOTON_MESSAGE_ID || !PHOTON_SPACE_ID || !PHOTON_SENDER_ID) {
  throw new Error("Set PHOTON_API_KEY, PHOTON_PROJECT_ID, PHOTON_MESSAGE_ID, PHOTON_SPACE_ID, and PHOTON_SENDER_ID");
}

const photon = new Photon({
  headers: { Authorization: `Bearer ${PHOTON_API_KEY}` },
});

const reply = await photon.projects.sendMessage({
  path: { id: PHOTON_PROJECT_ID },
  headers: { "idempotency-key": `reply-${PHOTON_MESSAGE_ID}` },
  body: {
    spaceId: PHOTON_SPACE_ID,
    senderId: PHOTON_SENDER_ID,
    parentMessageId: PHOTON_MESSAGE_ID,
    content: { type: "text", format: "plain", text: "Hello from your Photon agent!" },
  },
});
console.log(JSON.stringify(reply, null, 2));

Run it:

node reply.ts

The program prints the reply, a message like the ones you received. Here it's trimmed:

Code
{
  "content": {
    "format": "plain",
    "text": "Hello from your Photon agent!",
    "type": "text"
  },
  "id": "pho_msg_00000000000000000000000005",
  "parentMessageId": "pho_msg_00000000000000000000000002",
  "status": "dispatched"
}

status is where the send stands when the request returns. Photon delivers the message after that, so dispatched or accepted doesn't confirm delivery. failed means Photon couldn't send it.

3

Check that the reply arrived

Look at the phone or inbox you messaged from. Hello from your Photon agent! appears in the same conversation.

If you run the program again, it uses the same idempotency key, so Photon returns the first reply instead of sending another.

Echo text messages automatically

Put the listener from Receive messages and the reply together, and you have an agent. This example skips Email and echoes other human text messages with You said:. Save it as agent.ts or agent.py:

import { Photon } from "@photon-ai/api";
import { io } from "socket.io-client";

const { PHOTON_API_KEY, PHOTON_PROJECT_ID } = process.env;
if (!PHOTON_API_KEY || !PHOTON_PROJECT_ID) throw new Error("Set PHOTON_API_KEY and PHOTON_PROJECT_ID");

const photon = new Photon({
  headers: { Authorization: `Bearer ${PHOTON_API_KEY}` },
});

let cursor = 0;
let queue = Promise.resolve();
const socket = io("https://api.photon.codes", {
  path: `/v1/projects/${PHOTON_PROJECT_ID}/events/ws`,
  addTrailingSlash: false,
  transports: ["websocket"],
  extraHeaders: { Authorization: `Bearer ${PHOTON_API_KEY}` },
  autoConnect: false,
});

socket.on("connect", () => {
  socket.emit("subscribe", { startSeq: cursor }, (result: { ok: boolean; error?: { code: string } }) => {
    if (result.ok) console.log("Listening for messages. Press Ctrl+C to stop.");
    else console.error(`Subscribe failed: ${result.error?.code}`);
  });
});

socket.on("delivery", (event, { seq }) => {
  queue = queue
    .then(async () => {
      if (event.type !== "message.received") return;
      const message = event.data.object;
      if (message.platform === "email") return;
      if (message.sentBy.kind !== "human" || message.content.type !== "text") return;
      await photon.projects.sendMessage({
        path: { id: PHOTON_PROJECT_ID },
        headers: { "idempotency-key": `reply-${message.id}` },
        body: {
          spaceId: message.space.id,
          senderId: message.receivedBy.id,
          parentMessageId: message.id,
          content: { type: "text", format: "plain", text: `You said: ${message.content.text}` },
        },
      });
      console.log(`Replied to ${message.sentBy.handle}`);
    })
    .then(() => { cursor = seq; })
    .catch((error) => console.error(error));
});

socket.on("connect_error", (error) => console.error(error.message));
socket.connect();

The agent handles one event at a time. If Photon delivers an event twice, the idempotency key stops a second reply.

For received email, sentBy.kind is always human, so it does not identify autoresponders. Before writing an Email agent that replies automatically, define recipient rules and a narrow trigger. A plain-text email body has format: "plain". An HTML body arrives as format: "markdown". If there are several parts, read the text part from content.parts. See Receive email and Replies.

Run it with node agent.ts or python agent.py. Test the echo by sending your agent a text message on a supported non-Email channel. You get the reply in the same conversation. Replace the You said: text with your model's response to build a real agent.

Start a conversation

To message someone who hasn't written first, you need a space that contains them and your agent:

  1. Get the person's user with createOrGetUser, from their phone number or email address.
  2. Get a space for both users with createOrGetSpace.
  3. Send into that space with sendMessage, with your agent's user as senderId.

A shared iMessage line can't start a conversation: the person must message it first. For each channel's requirements, see Messaging.

Channel options

Some channels take extra fields in the request body. email sets fields such as subject, cc, and replyTo, and telegram holds Telegram options. See sendMessage for every field.

Troubleshooting

What you seeWhat to check
An error about a missing environment variable or an invalid IDSet the three IDs from one received message in this project, as in step 1.
403The key lacks project:write, or belongs to another project.
An error on a shared iMessage lineA shared line replies only in direct conversations, to a person who messaged it after it was assigned.
dispatched or accepted, but no message arrivesDelivery happens later. Check the conversation on your channel's page in the dashboard, and the send in API Activities.

Next steps

Voice

Route phone calls to a voice agent.

Webhooks

Receive events on your server instead of a live connection.

Chat SDK

Build your agent with Chat SDK and the Photon adapter.

API reference

Every field of sendMessage and the other client methods.