---
title: Photon
description: Photon adapter for Chat SDK, built and maintained by Photon. Connects a bot to the iMessage, SMS, WhatsApp, WhatsApp Business, Telegram, and email channels of a Photon Beta project over signed webhooks or a WebSocket gateway.
tagline: Photon adapter for Chat SDK. One adapter reaches every channel connected to a Photon Beta project, including iMessage, SMS, WhatsApp, Telegram, and email, and receives messages through signed webhooks or a WebSocket gateway.
package: @photon-ai/chat-adapter
---

# Photon



<Callout type="warn">
  This adapter runs on Photon's Beta platform, which is a preview and doesn't have every feature of Photon's Stable platform yet. For example, iMessage on Beta supports only text and images. Photon recommends Stable for production agents, so confirm that Beta supports the features you need before you rely on it. The adapter replaces `@photon-ai/chat-adapter-imessage`. See [Migrating from the iMessage adapter](#migrating-from-the-imessage-adapter).
</Callout>

## Create a new bot

Scaffold a Next.js bot with the Photon adapter using [`create-chat-sdk`](/docs/create-chat-sdk):

<CreateChatSdk adapters="photon memory" />

The generated app uses the [Memory state adapter](/adapters/official/memory) for local development. To add the adapter to an existing app, start at [Install](#install).

## Install

<PackageInstall package="@photon-ai/chat-adapter chat @chat-adapter/state-memory" />

## Quick start

Register the adapter as `photon`. It reads `PHOTON_PROJECT_ID` and `PHOTON_API_KEY` from the environment. Direct messages reach `onDirectMessage`. In a group, this bot subscribes when someone mentions `@mybot`, then replies to later messages in that thread.

```typescript title="lib/bot.ts" lineNumbers
import { Chat } from "chat";
import { createMemoryState } from "@chat-adapter/state-memory";
import { createPhotonAdapter } from "@photon-ai/chat-adapter";

export const bot = new Chat({
  userName: "mybot",
  state: createMemoryState(),
  adapters: {
    photon: createPhotonAdapter(),
  },
});

bot.onDirectMessage(async (thread, message) => {
  await thread.post(`You said: ${message.text}`);
});

bot.onNewMention(async (thread) => {
  await thread.subscribe();
  await thread.post({ markdown: "Hi, I'm **here**." });
});

bot.onSubscribedMessage(async (thread, message) => {
  await thread.post(`You said: ${message.text}`);
});
```

For production, use a persistent state adapter such as `@chat-adapter/state-redis`. In-memory state loses subscriptions, deduplication, and the gateway resume cursor on restart, and serverless invocations don't share it.

Route Photon's webhook to the adapter:

```typescript title="app/api/webhooks/photon/route.ts" lineNumbers
import { after } from "next/server";
import { bot } from "@/lib/bot";

export async function POST(request: Request): Promise<Response> {
  return bot.webhooks.photon(request, {
    waitUntil: (task) => after(() => task),
  });
}
```

<Callout type="warn">
  Test an echo bot from your own phone or account, not from another automated line in the same project. Photon can report that line as a human sender, so two echo bots can keep replying to each other.
</Callout>

## Platform setup

1. [Set up a Beta project and API key](https://photon.codes/docs/beta/get-started/project). The project API key needs `project:read` and `project:write` to receive messages and send replies.
2. Connect the channels you want to use in the [Beta dashboard](https://app.beta.photon.codes/project). Photon suggests starting with its [iMessage guide](https://photon.codes/docs/beta/get-started/imessage) or [email guide](https://photon.codes/docs/beta/get-started/email).
3. Set `PHOTON_PROJECT_ID` and `PHOTON_API_KEY` in your server's environment.
4. To receive messages by webhook, [create a webhook destination](https://photon.codes/docs/beta/message-delivery/webhook) that points at your bot's HTTPS route, subscribe it to `message.received`, and save its signing secret as `PHOTON_WEBHOOK_SECRET`. The [WebSocket gateway](#websocket-gateway) needs only the project ID and API key.

## Configuration

Options passed to `createPhotonAdapter()` take precedence over environment variables.

<TypeTable
  type={{
  projectId: {
    type: "string",
    description: "Photon Beta project ID. Falls back to `PHOTON_PROJECT_ID`.",
  },
  apiKey: {
    type: "string",
    description:
      "Project API key (`pho_sk_...`). Falls back to `PHOTON_API_KEY`.",
  },
  webhookSecret: {
    type: "string",
    description:
      "Signing secret (`whsec_...`) of the webhook destination. Falls back to `PHOTON_WEBHOOK_SECRET`.",
  },
  agentUserId: {
    type: "string",
    description:
      "Agent User (`pho_usr_...`) that `openDM` starts conversations from. Falls back to `PHOTON_AGENT_USER_ID`.",
  },
  baseUrl: {
    type: "string",
    description:
      "Photon API origin, without `/v1`. Falls back to `PHOTON_API_URL`, then `https://api.photon.codes`.",
  },
  userName: {
    type: "string",
    description:
      "Bot name matched for @-mentions in group Spaces. Defaults to the Chat instance's `userName`.",
  },
  logger: {
    type: "Logger",
    description:
      "Chat SDK-compatible logger. Defaults to the Chat instance's logger.",
  },
}}
/>

### Environment variables

| Variable                | Required | Description                                                                                    |
| ----------------------- | -------- | ---------------------------------------------------------------------------------------------- |
| `PHOTON_PROJECT_ID`     | Yes      | Photon Beta project ID.                                                                        |
| `PHOTON_API_KEY`        | Yes      | Project API key. This is not a Spectrum project secret.                                        |
| `PHOTON_WEBHOOK_SECRET` | Webhooks | Signing secret (`whsec_...`) of the webhook destination. Not needed for the WebSocket gateway. |
| `PHOTON_AGENT_USER_ID`  | `openDM` | Agent User (`pho_usr_...`) that starts conversations.                                          |
| `PHOTON_API_URL`        | No       | Photon API origin, without `/v1`. Defaults to `https://api.photon.codes`.                      |

## Webhooks

`bot.webhooks.photon` verifies the [Standard Webhooks](https://www.standardwebhooks.com) headers `webhook-id`, `webhook-timestamp`, and `webhook-signature` against the exact request bytes, so pass the original `Request` without parsing or reserializing its body first. The adapter responds with:

* `401` when the signature is invalid or the timestamp is more than 5 minutes off.
* `500` when no signing secret is configured.
* `200` for every verified event. Events other than `message.received` are acknowledged without invoking handlers.

The `200` acknowledges the event. It doesn't mean your handler finished or that its reply was delivered. On serverless hosts, pass the host's background-task hook as `waitUntil` so handlers can finish after the response.

Reactions, edits, and deletions arrive as content inside `message.received`, so they need no separate event subscriptions.

## WebSocket gateway

For a process without a public URL, receive the same `message.received` events over Photon's [Socket.IO event stream](https://photon.codes/docs/beta/message-delivery/websocket). The gateway needs the project ID and API key, but no webhook destination or signing secret.

`startGatewayListener(options, durationMs, abortSignal)` connects, reconnects after transient disconnects, and stores the sequence number of the last event it handled in the Chat SDK state adapter, so a later connection resumes after it. Use a persistent state adapter for the cursor to survive a restart. The listener runs for 3 minutes by default.

On a long-running server, initialize the bot and listen until shutdown:

```typescript title="gateway.ts" lineNumbers
import { bot } from "./lib/bot";

await bot.initialize();

const controller = new AbortController();
process.on("SIGTERM", () => controller.abort());

await bot
  .getAdapter("photon")
  .startGatewayListener({}, Number.POSITIVE_INFINITY, controller.signal);
```

For serverless deployments, prefer webhooks. If you need the gateway there, start it from a cron job that runs more often than the listener lasts, and check the cron secret first so nobody else can start listeners on your API key:

```typescript title="app/api/photon/gateway/route.ts" lineNumbers
import { after } from "next/server";
import { bot } from "@/lib/bot";

export const maxDuration = 800;

export async function GET(request: Request): Promise<Response> {
  const cronSecret = process.env.CRON_SECRET;
  if (!cronSecret) {
    return new Response("CRON_SECRET not configured", { status: 500 });
  }
  if (request.headers.get("authorization") !== `Bearer ${cronSecret}`) {
    return new Response("Unauthorized", { status: 401 });
  }

  await bot.initialize();
  return bot
    .getAdapter("photon")
    .startGatewayListener({ waitUntil: (task) => after(() => task) }, 600_000);
}
```

Overlapping listeners are safe, because Chat SDK drops a message it has already handled.

## Direct messages

Direct Spaces are DMs and reach `onDirectMessage`. To start a conversation, set `PHOTON_AGENT_USER_ID` to a connected Agent User, then pass an existing Photon User ID to the adapter's `openDM`. A phone number doesn't work here.

```typescript
await bot.initialize();

const threadId = await bot
  .getAdapter("photon")
  .openDM("pho_usr_REPLACE_WITH_RECIPIENT_ID");

await bot.thread(threadId).post("Hello from Photon!");
```

Call `openDM` on the adapter, because `bot.openDM()` can't infer the Photon adapter from a Photon User ID. The adapter finds or creates the direct Space between the Agent and that User. Both must be on the same platform, and that platform's messaging rules still apply.

## Message format

Markdown is sent to Photon as Markdown, and each platform renders what it supports. SMS, for example, receives plain text. Raw HTML in Markdown is dropped because Photon rejects it.

Photon content has no buttons or other actions, so a card is sent as its fallback text and modals can't open.

## Streaming

The adapter collects a streamed reply and sends it once as a complete message. It doesn't post a placeholder and edit it, because most platforms behind Photon can't edit messages.

## Attachments

Files attached to a post are uploaded as Photon attachments. The text and each file go out as separate messages, in the order given.

Inbound attachments include the name, type, and size, with `fetchData()` to download the content.

## Reactions, edits, and typing

Support depends on the connected platform. When a platform doesn't support an operation, Photon refuses it and the adapter throws Chat SDK's `NotImplementedError`. Photon's README notes that iMessage doesn't support edits, deletes, or reactions yet, and that Telegram supports edits and deletes.

| Chat SDK                                | Photon adapter behavior                                                     |
| --------------------------------------- | --------------------------------------------------------------------------- |
| `editMessage` / `deleteMessage`         | Sends `message.update` / `message.delete` where the platform supports them. |
| `addReaction`                           | Sends a `reaction` where the platform supports it.                          |
| `onReaction`                            | Receives inbound reactions and reaction removals.                           |
| `onMessageUpdated` / `onMessageDeleted` | Receives inbound edits and deletions, carrying the original message's ID.   |
| `startTyping`                           | Sends Space typing. A no-op on platforms without typing.                    |
| `markAsRead`                            | Sends a read receipt.                                                       |

## Message history

`fetchMessages` reads paginated Space history, and `fetchThread` returns the Space in `metadata.space`.

## Thread IDs

A thread is one Photon Space, as seen by the Agent User that received the message:

```text
photon:<spaceId>:<agentUserId>:<spaceKind>
```

`spaceKind` is the Photon Space kind, such as `direct` or `group`. Because the Agent is part of the ID, a reply goes out from the Agent the message arrived on, including in a later webhook invocation.

## Migrating from the iMessage adapter

`@photon-ai/chat-adapter` is a new adapter with a new API, not a rename of `@photon-ai/chat-adapter-imessage`. For an existing Spectrum integration, Photon keeps a [legacy guide](https://photon.codes/docs/integrations/chat-sdk).

| iMessage adapter                                        | Photon adapter                                             |
| ------------------------------------------------------- | ---------------------------------------------------------- |
| `@photon-ai/chat-adapter-imessage`                      | `@photon-ai/chat-adapter`                                  |
| `createiMessageAdapter()` and `adapters.imessage`       | `createPhotonAdapter()` and `adapters.photon`              |
| Spectrum project ID and secret, `IMESSAGE_*` variables  | Beta project ID and API key, `PHOTON_*` variables          |
| `bot.webhooks.imessage` and Spectrum webhook signatures | `bot.webhooks.photon` and a new `whsec_...` signing secret |
| iMessage-specific thread IDs                            | Photon Space and Agent User IDs                            |

Create a Beta project, connect its channels, replace the credentials and webhook destination, and review [feature support](#feature-support) before you switch traffic. Old thread IDs, subscriptions, and gateway cursors don't carry over, so use a separate state store or namespace for the new bot.

## Limitations

* `removeReaction` is not supported. Photon removes a reaction by deleting the reaction's own message, which can't be looked up from the message it reacts to.
* Cards are sent as fallback text, and modals are not supported.
* Edits, deletes, reactions, and typing depend on the connected platform.
* Beta doesn't have every Stable feature. On iMessage, tapbacks, polls, message effects, and voice notes are available only on Stable for now.
* The adapter requires Node.js 20 or later and runs server-side only.

## Feature support

<FeatureSupport />

## Resources

* [GitHub](https://github.com/photon-hq/chat-adapter)
* [npm](https://www.npmjs.com/package/@photon-ai/chat-adapter)
* [Photon Chat SDK guide](https://photon.codes/docs/beta/integrations/chat-sdk)
* [Beta dashboard](https://app.beta.photon.codes/project)
* [Webhook delivery](https://photon.codes/docs/beta/message-delivery/webhook)
* [WebSocket delivery](https://photon.codes/docs/beta/message-delivery/websocket)
