> **Photon Beta documentation**
> Browse all pages: https://photon.codes/docs/beta/llms.txt
> Search Beta docs via MCP: https://photon.codes/docs/beta/mcp (OAuth REST API MCP: https://mcp.photon.codes/mcp)

# Receive messages

> Read the messages people send your agent, then get each new one as it arrives.

> [!WARNING]
>
> **Beta is a preview.** The Beta (2.0) platform does not have all the features
> of [Stable](https://photon.codes/docs/spectrum-ts/introduction) yet. For example, iMessage on Beta
> supports text, attachments, voice messages, replies, read receipts, and typing
> indicators, but tapbacks, polls, and message effects are
> [only on Stable](https://photon.codes/docs/spectrum-ts/providers/imessage/messaging-features) for now.
> Use Stable for production agents, and confirm that Beta supports the features
> you need before you buy a plan.

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](/docs/beta/get-started/project.md). Your API key needs
  `project:read`.
* A connected channel, and a message you sent to your agent. See
  [Choose a channel](/docs/beta/get-started/introduction.md#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.

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

```python Python
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))
```

```rust Rust
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(())
}
```

```go Go
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:

```sh TypeScript
node list-messages.ts
```

```sh Python
python list_messages.py
```

```sh Rust
cargo run --bin list_messages
```

```sh Go
go run list_messages.go
```

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:

```json
{
  "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:

```sh TypeScript
npm install socket.io-client@4.8.3
```

```sh Python
pip install "python-socketio[asyncio_client]==5.18.1"
```

Save this as `listen.ts` or `listen.py`:

```typescript TypeScript
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();
```

```python Python
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](/docs/beta/api-reference/websocket/example.md).

## 3. Send a test message

Start the listener:

```sh TypeScript
node listen.ts
```

```sh Python
python listen.py
```

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

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

> [!NOTE]
>
> The listener keeps its cursor in memory, so after a restart it starts with new
> messages. In production, save the cursor after you handle each event. See
> [Resume without skipping work](/docs/beta/message-delivery/websocket.md#resume-without-skipping-work).

## 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**](https://app.beta.photon.codes/project/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](/docs/beta/message-delivery/webhook.md) 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](/docs/beta/api-reference/websocket/errors.md) 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

[Send messages](/docs/beta/get-started/send-messages.md)

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