> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/examples/echo-bot/javascript-typescript.md).

# JavaScript / TypeScript

```js
import WebSocket from "ws";
import { DNotifier } from "@dnotifier-realtime/dnotifier";

const BOT_ID = "echo-bot";

function extractSenderId(prefixedSender, appId) {
  const prefix = `${appId}_`;
  return prefixedSender.startsWith(prefix)
    ? prefixedSender.slice(prefix.length)
    : prefixedSender;
}

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET,
  transport: "ws",
  userId: BOT_ID,
  WebSocketImpl: WebSocket,
  onConnected: () => console.log("Echo bot ready"),
  onMessage: async (msg) => {
    const body = msg.payload.toJSON();
    if (body?.type !== "text" || !body.text) return;

    const senderUserId = extractSenderId(msg.metadata.sender, notifier.appId);

    await notifier.send({
      senderId: BOT_ID,
      receiverId: senderUserId,
      data: { type: "text", text: `Echo: ${body.text}` },
    });
    console.log(`Echoed to ${senderUserId}:`, body.text);
  },
  onDisconnected: () => console.log("Echo bot disconnected"),
});

await notifier.connect();
```

## Test

Run the bot, then send a message from another client to `echo-bot`:

```js
await notifier.send({
  senderId: "user-alice",
  receiverId: "echo-bot",
  data: { type: "text", text: "ping" },
});
```

Expected reply on `user-alice`: `{ type: "text", text: "Echo: ping" }`.
