> **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)

# Send messages

> Reply to a message from your agent, then have your agent reply to every message.

> [!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.

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](/docs/beta/get-started/receive-messages.md),
then turn the listener into an agent that echoes supported non-Email text
messages.

## 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` and `project:write`.
* A message you sent to your agent. See
  [Receive messages](/docs/beta/get-started/receive-messages.md).

The one-shot reply examples below do not skip Email. If you choose an Email
Message for the one-shot test, read [Replies](/docs/beta/messaging/email.md#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](/docs/beta/get-started/receive-messages.md) printed, and save
three of its IDs as environment variables:

| From the received message | Environment variable | Send it as | What it is |
| - | - | - | - |
| `id` | `PHOTON_MESSAGE_ID` | `parentMessageId` | The message you're replying to. Optional. |
| `space.id` | `PHOTON_SPACE_ID` | `spaceId` | The conversation. |
| `receivedBy.id` | `PHOTON_SENDER_ID` | `senderId` | Your agent's user, so the reply comes from the number or address the person messaged. |

```sh
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:

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

```python Python
import os

from photon_api import Photon
from photon_api.rpc_generated import SendMessageInput

with Photon(headers={"Authorization": f"Bearer {os.environ['PHOTON_API_KEY']}"}) as photon:
    reply = photon.projects.send_message(
        SendMessageInput.model_validate({
            "path": {"id": os.environ["PHOTON_PROJECT_ID"]},
            "headers": {"idempotency-key": f"reply-{os.environ['PHOTON_MESSAGE_ID']}"},
            "body": {
                "spaceId": os.environ["PHOTON_SPACE_ID"],
                "senderId": os.environ["PHOTON_SENDER_ID"],
                "parentMessageId": os.environ["PHOTON_MESSAGE_ID"],
                "content": {"type": "text", "format": "plain", "text": "Hello from your Photon agent!"},
            },
        })
    )
    print(reply.model_dump_json(indent=2))
```

```rust Rust
use photon_ai_api::{Credential, PhotonClientBuilder, SecretString};
use serde_json::json;

#[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 message_id = std::env::var("PHOTON_MESSAGE_ID")?;
    let body = serde_json::from_value(json!({
        "spaceId": std::env::var("PHOTON_SPACE_ID")?,
        "senderId": std::env::var("PHOTON_SENDER_ID")?,
        "parentMessageId": message_id,
        "content": { "type": "text", "format": "plain", "text": "Hello from your Photon agent!" },
    }))?;
    let reply = client
        .send_message(
            std::env::var("PHOTON_PROJECT_ID")?,
            format!("reply-{message_id}"),
            &body,
        )
        .await
        .map_err(|error| format!("{error:?}"))?
        .into_inner();
    println!("{}", serde_json::to_string_pretty(&reply)?);
    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")))
	reply, err := client.Projects.SendMessage(context.Background(), &photonapi.SendMessageParams{
		ID:             os.Getenv("PHOTON_PROJECT_ID"),
		IdempotencyKey: "reply-" + os.Getenv("PHOTON_MESSAGE_ID"),
		Body: photonapi.SendMessageRequest{
			SpaceID:         os.Getenv("PHOTON_SPACE_ID"),
			SenderID:        os.Getenv("PHOTON_SENDER_ID"),
			ParentMessageID: photonapi.Ptr(os.Getenv("PHOTON_MESSAGE_ID")),
			Content: photonapi.SendContent{Union: photonapi.Union{
				Raw: []byte(`{"type":"text","format":"plain","text":"Hello from your Photon agent!"}`),
			}},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	out, _ := json.MarshalIndent(reply, "", "  ")
	fmt.Println(string(out))
}
```

Run it:

```sh TypeScript
node reply.ts
```

```sh Python
python reply.py
```

```sh Rust
cargo run --bin reply
```

```sh Go
go run reply.go
```

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

```json
{
  "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](/docs/beta/get-started/receive-messages.md)
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`:

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

```python Python expandable
import asyncio
import os

import socketio
from photon_api import AsyncPhoton
from photon_api.rpc_generated import SendMessageInput

cursor = 0
deliveries = asyncio.Queue()
sio = socketio.AsyncClient()
photon = AsyncPhoton(headers={"Authorization": f"Bearer {os.environ['PHOTON_API_KEY']}"})


async def reply(event):
    if event["type"] != "message.received":
        return
    message = event["data"]["object"]
    if message["platform"] == "email":
        return
    if message["sentBy"]["kind"] != "human" or message["content"]["type"] != "text":
        return
    await photon.projects.send_message(
        SendMessageInput.model_validate({
            "path": {"id": os.environ["PHOTON_PROJECT_ID"]},
            "headers": {"idempotency-key": f"reply-{message['id']}"},
            "body": {
                "spaceId": message["space"]["id"],
                "senderId": message["receivedBy"]["id"],
                "parentMessageId": message["id"],
                "content": {"type": "text", "format": "plain", "text": f"You said: {message['content']['text']}"},
            },
        })
    )
    print(f"Replied to {message['sentBy']['handle']}")


@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):
    deliveries.put_nowait((event, metadata["seq"]))


async def main():
    global cursor
    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']}"},
    )
    while True:
        event, seq = await deliveries.get()
        await reply(event)
        cursor = seq


asyncio.run(main())
```

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](/docs/beta/messaging/email.md#receive-email) and
[Replies](/docs/beta/messaging/email.md#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`](/docs/beta/api-client/sdk/projects/create-or-get-user.md),
   from their phone number or email address.
2. Get a space for both users with [`createOrGetSpace`](/docs/beta/api-client/sdk/projects/create-or-get-space.md).
3. Send into that space with [`sendMessage`](/docs/beta/api-client/sdk/projects/send-message.md),
   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](/docs/beta/messaging.md).

## 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`](/docs/beta/api-client/sdk/projects/send-message.md)
for every field.

## Troubleshooting

| What you see | What to check |
| - | - |
| An error about a missing environment variable or an invalid ID | Set the three IDs from one received message in this project, as in step 1. |
| `403` | The key lacks `project:write`, or belongs to another project. |
| An error on a shared iMessage line | A shared line replies only in direct conversations, to a person who messaged it after it was assigned. |
| `dispatched` or `accepted`, but no message arrives | Delivery happens later. Check the conversation on your channel's page in the dashboard, and the send in [**API Activities**](https://app.beta.photon.codes/project/activity). |

## Next steps

[Voice](/docs/beta/get-started/voice.md)

Route phone calls to a voice agent.

[Webhooks](/docs/beta/message-delivery/webhook.md)

Receive events on your server instead of a live connection.

[Chat SDK](/docs/beta/integrations/chat-sdk.md)

Build your agent with Chat SDK and the Photon adapter.

[API reference](/docs/beta/api-client/sdk/projects/send-message.md)

Every field of `sendMessage` and the other client methods.
