Skip to content

Every message someone sends your agent is stored in your project. In this guide, you read those messages with the API. Then you open a live connection, so each new message reaches your code as it arrives.

Prerequisites

You need:

  • The environment variables and client from Set up your project. Your API key needs project:read.
  • A connected channel, and a message you sent to your agent. See Choose a channel.
1

Read your agent's messages

Save this as list-messages.ts, list_messages.py, src/bin/list_messages.rs, or list_messages.go. For Rust, run cargo add serde_json first.

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

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}` },
});

const page = await photon.projects.listMessages({
  path: { id: PHOTON_PROJECT_ID },
  query: { direction: "received", pageSize: 5 },
});

for (const message of page.items) {
  console.log(JSON.stringify(message, null, 2));
}

The program reads the five newest messages your agent received and prints each one as JSON.

Run it:

node list-messages.ts

You should see the message you sent, newest first. Each message prints in full; this one is trimmed to the fields the next guide uses:

Code
{
  "content": {
    "format": "plain",
    "text": "hi",
    "type": "text"
  },
  "id": "pho_msg_00000000000000000000000002",
  "platform": "imessage",
  "receivedBy": {
    "handle": "+14155550188",
    "id": "pho_usr_00000000000000000000000002",
    "kind": "agent"
  },
  "sentBy": {
    "handle": "+14155550123",
    "id": "pho_usr_00000000000000000000000001",
    "kind": "human"
  },
  "space": {
    "id": "pho_spc_00000000000000000000000002",
    "kind": "direct"
  },
  "status": "received"
}

content holds what the person sent. A text message has content.text. An email usually arrives as a group, with its text and attachments in content.parts. Typing indicators, reactions, and read receipts are messages too, each with its own content.type, so they can appear in the list.

2

Listen for new messages

Reading a list is fine for a test, but an agent should answer when a message arrives. Photon streams your project's events over a Socket.IO connection that your code opens, so you don't need a public URL.

Install a Socket.IO client:

npm install socket.io-client@4.8.3

Save this as listen.ts or listen.py:

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");

let cursor = 0;
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 }) => {
  if (event.type === "message.received") console.log(JSON.stringify(event.data.object, null, 2));
  cursor = seq;
});

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

Photon sends a message.received event for each new message, and the program prints the message in it, the same object step 1 printed. Each delivery carries a cursor, seq. When the connection drops, Socket.IO reconnects and the program subscribes again from the last event it handled, so it doesn't skip any.

For Go, Rust, Java, and .NET, see the WebSocket client examples.

3

Send a test message

Start the listener:

node listen.ts

Wait for Listening for messages, then send your agent another message. It appears in your terminal:

Code
Listening for messages. Press Ctrl+C to stop.
{
  "content": {
    "type": "text",
    "format": "plain",
    "text": "are you there?"
  },
  "id": "pho_msg_00000000000000000000000004",
  ...
}

Receive with a webhook instead

If your agent runs on a server with a public HTTPS URL, Photon can send each event to it as an HTTP POST:

  1. In your project, open Webhooks and select Add a destination.
  2. Enter your URL and select the message.received event.
  3. Save the signing secret, and verify each request with Standard Webhooks before you handle it.

The request body is the same event your listener receives. See Webhook for verification, retries, and duplicate deliveries.

Troubleshooting

What you seeWhat to check
Step 1 prints nothingYou messaged a line or domain of another project. Send your agent a message and run it again.
401 or 403The key is wrong or expired, belongs to another project, or lacks project:read.
Subscribe failed or a connection errorThe same key and project checks. See WebSocket errors for each error code.
The listener prints nothingSend the message after Listening for messages appears. Messages sent before that are in step 1's list, not the stream.

Next: send messages

Send messages

Reply to the message you just received, then reply to every message.