Receive messages
Read the messages people send your agent, then get each new one as it arrives.
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.
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));
}import os
from photon_api import Photon
from photon_api.rpc_generated import ListMessagesInput
with Photon(headers={"Authorization": f"Bearer {os.environ['PHOTON_API_KEY']}"}) as photon:
page = photon.projects.list_messages(
ListMessagesInput.model_validate({
"path": {"id": os.environ["PHOTON_PROJECT_ID"]},
"query": {"direction": "received", "pageSize": 5},
})
)
for message in page.items:
print(message.model_dump_json(indent=2))use photon_ai_api::types::MessageDirection;
use photon_ai_api::{Credential, ListMessagesParams, PhotonClientBuilder, SecretString};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let key = SecretString::from(std::env::var("PHOTON_API_KEY")?);
let client = PhotonClientBuilder::new()
.credential("projectApiKey", Credential::Bearer(key))
.build()?;
let params = ListMessagesParams::default()
.direction(MessageDirection::Received)
.page_size(5);
let page = client
.list_messages(std::env::var("PHOTON_PROJECT_ID")?, Some(params))
.await
.map_err(|error| format!("{error:?}"))?
.into_inner();
for message in &page.items {
println!("{}", serde_json::to_string_pretty(message)?);
}
Ok(())
}package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
photonapi "github.com/photon-hq/api/packages/go"
)
func main() {
client := photonapi.NewClient(photonapi.WithAPIKey(os.Getenv("PHOTON_API_KEY")))
page, err := client.Projects.ListMessages(context.Background(), &photonapi.ListMessagesParams{
ID: os.Getenv("PHOTON_PROJECT_ID"),
Direction: photonapi.Ptr(photonapi.MessageDirectionReceived),
PageSize: photonapi.Ptr(int64(5)),
})
if err != nil {
log.Fatal(err)
}
for _, message := range page.Items {
out, _ := json.MarshalIndent(message, "", " ")
fmt.Println(string(out))
}
}The program reads the five newest messages your agent received and prints each one as JSON.
Run it:
node list-messages.tspython list_messages.pycargo run --bin list_messagesgo run list_messages.goYou should see the message you sent, newest first. Each message prints in full; this one is trimmed to the fields the next guide uses:
{
"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.
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.3pip install "python-socketio[asyncio_client]==5.18.1"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();import asyncio
import json
import os
import socketio
cursor = 0
sio = socketio.AsyncClient()
@sio.event
async def connect():
result = await sio.call("subscribe", {"startSeq": cursor}, timeout=10)
if result["ok"]:
print("Listening for messages. Press Ctrl+C to stop.")
else:
print("Subscribe failed:", result["error"]["code"])
@sio.on("delivery")
def delivery(event, metadata):
global cursor
if event["type"] == "message.received":
print(json.dumps(event["data"]["object"], indent=2))
cursor = metadata["seq"]
async def main():
await sio.connect(
"https://api.photon.codes",
socketio_path=f"/v1/projects/{os.environ['PHOTON_PROJECT_ID']}/events/ws",
transports=["websocket"],
headers={"Authorization": f"Bearer {os.environ['PHOTON_API_KEY']}"},
)
await sio.wait()
asyncio.run(main())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.
Send a test message
Start the listener:
node listen.tspython listen.pyWait for Listening for messages, then send your agent another message. It appears in your terminal:
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:
- In your project, open Webhooks and select Add a destination.
- Enter your URL and select the
message.receivedevent. - 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 see | What to check |
|---|---|
| Step 1 prints nothing | You messaged a line or domain of another project. Send your agent a message and run it again. |
401 or 403 | The key is wrong or expired, belongs to another project, or lacks project:read. |
Subscribe failed or a connection error | The same key and project checks. See WebSocket errors for each error code. |
| The listener prints nothing | Send the message after Listening for messages appears. Messages sent before that are in step 1's list, not the stream. |
Next: send messages
Reply to the message you just received, then reply to every message.