Send messages
Reply to a message from your agent, then have your agent reply to every message.
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 environment variables and client from
Set up your project. Your API key needs
project:readandproject:write. - A message you sent to your agent. See Receive messages.
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.
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 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. |
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>.
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));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))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(())
}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:
node reply.tspython reply.pycargo run --bin replygo run reply.goThe program prints the reply, a message like the ones you received. Here it's trimmed:
{
"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.
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:
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:
- Get the person's user with
createOrGetUser, from their phone number or email address. - Get a space for both users with
createOrGetSpace. - Send into that space with
sendMessage, with your agent's user assenderId.
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 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. |