Put a bot in a group chat and two things go wrong first. It answers every message, so people stop talking to each other. And when your server is slow to answer the webhook, the same event arrives again and the bot posts its answer twice.
In TalkJS the agent is a user like the others: you add it to the conversation, TalkJS sends your server a webhook for each new message, your server asks your model for an answer, and posts it with the REST API as the agent. It shows up in the chat your users already have, with its own name and photo, and people @mention it the way they mention each other. You work on the AI; the chat around it, from message history to mentions and notifications, is already there.
This guide builds an agent that avoids both problems, in one Node.js file we've run. You need a TalkJS app, Node.js 22 or later, and an API key for the model you use: OpenAI, Anthropic, Gemini or your own.
How do I set up an AI agent in TalkJS?
Four steps, each one call or setting:
- Create a user for the agent. Call create or update a user with the name and photo people should see, for example the ID
assistantand the name "Assistant". Give it a role of its own if its permissions should differ from your users'. - Add the agent to a conversation with join conversation. It can read the messages sent before it joined.
- Turn on webhooks. On the Settings page of your TalkJS dashboard, add your server's URL and subscribe to the
message.sentevent. - Reply as the agent. Send a message with the agent's ID as the
sender. The sender has to be a participant in the conversation.
What does the webhook handler look like?
One file, no packages, only what ships with Node. Set TALKJS_APP_ID and TALKJS_SECRET_KEY, and fill in askModel with a call to your model.
// agent.mjs: an AI agent in TalkJS conversations. Node.js 22 or later, no packages.
import http from 'node:http';
import { createHmac, timingSafeEqual } from 'node:crypto';
const APP_ID = process.env.TALKJS_APP_ID;
const SECRET_KEY = process.env.TALKJS_SECRET_KEY; // marked "use for webhooks"
const AGENT_ID = 'assistant';
// Call OpenAI, Anthropic or your own model here and return the reply text
async function askModel(history) {}
const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
function adminToken() {
const data = `${b64url({ alg: 'HS256', typ: 'JWT' })}.${b64url({
tokenType: 'admin', iss: APP_ID, exp: Math.floor(Date.now() / 1000) + 30,
})}`;
return `${data}.${createHmac('sha256', SECRET_KEY).update(data).digest('base64url')}`;
}
async function talkjs(method, path, body) {
const res = await fetch(`https://api.talkjs.com/v1/${APP_ID}${path}`, {
method,
headers: { Authorization: `Bearer ${adminToken()}`, 'Content-Type': 'application/json' },
body: body && JSON.stringify(body),
});
if (!res.ok) throw new Error(`${method} ${path}: ${res.status}`);
return res.status === 200 ? res.json().catch(() => null) : null;
}
function isValidSignature(rawBody, timestamp, signature) {
if (!timestamp || !signature) return false;
const expected = createHmac('sha256', SECRET_KEY)
.update(`${timestamp}.${rawBody}`).digest('hex').toUpperCase();
return expected.length === signature.length &&
timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
}
async function answer({ conversation, message, sender, mentionedUserIds }) {
if (sender.id === AGENT_ID) return; // never answer itself
if (!(AGENT_ID in conversation.participants)) return; // not a conversation the agent is in
const isGroup = Object.keys(conversation.participants).length > 2;
if (isGroup && !mentionedUserIds.includes(AGENT_ID)) return; // in groups, only when mentioned
// The last 20 user messages. The API lists newest first, so reverse them.
const filter = encodeURIComponent(JSON.stringify({ type: ['==', 'UserMessage'] }));
const { data } = await talkjs('GET',
`/conversations/${conversation.id}/messages?limit=20&filter=${filter}`);
const history = data.reverse().map((m) => ({
role: m.senderId === AGENT_ID ? 'assistant' : 'user',
content: m.senderId === AGENT_ID ? m.text : `${m.senderId}: ${m.text}`,
}));
const reply = await askModel(history);
await talkjs('POST', `/conversations/${conversation.id}/messages`, [{
text: reply,
sender: AGENT_ID,
type: 'UserMessage',
referencedMessageId: message.id,
idempotencyKey: message.id, // a retried webhook can't post twice
}]);
}
http.createServer((req, res) => {
const chunks = [];
req.on('data', (c) => chunks.push(c));
req.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
if (!isValidSignature(raw, req.headers['x-talkjs-timestamp'], req.headers['x-talkjs-signature'])) {
res.writeHead(401).end();
return;
}
res.writeHead(200).end(); // answer TalkJS first, then do the slow work
const event = JSON.parse(raw);
if (event.type === 'message.sent') answer(event.data).catch(console.error);
});
}).listen(3000);The signature check follows TalkJS's webhook signing rule: an HMAC-SHA256 of the X-TalkJS-Timestamp header, a dot and the raw request body, in uppercase hexadecimal. Check the raw bytes before you parse them. The handler also builds the admin token the REST API asks for and signs it with Node's built-in crypto.
We ran this handler on Node.js 22.23.4 against a TalkJS test project in October 2026, with message.sent events our own script signed and a fake model that returned fixed text. In a three-person chat, a message that didn't mention the agent got no reply. A message that did got one, and the model saw the earlier messages from both people but not a system message. A request with a bad signature got a 401.
How do I make the agent answer only when someone mentions it?
Every message.sent event has a mentionedUserIds list: the users mentioned in the message, in the order they first appear. It's empty when nobody was mentioned. The handler reads it in the last of three checks at the top of answer(), and the agent answers only if it gets past all three. In a 1-on-1 chat, it answers every message, mention or not.
answer(), in order.For people to mention the agent, turn on Allow mentions on the Chat UI page of your dashboard. They type @ and pick the agent's name from the list. You can allow mentions for some roles and not others. If a conversation gets busy, set a participant's notify to MentionsOnly, and they'll get a notification only when they're mentioned.
How does the model know what was said?
The handler lists the conversation's messages and asks for the last 20, filtered to the type UserMessage so system messages stay out. One request can return up to 100. The API returns them newest first, so reverse the list before it goes to the model.
In a group, the model also needs to know who said what. The handler puts the sender's user ID in front of each message; if your user IDs aren't readable names, use the names from your own user records. Send your own instructions to the model separately from this history, and treat what people type as text to read, not orders to follow.
What if the model takes longer than five seconds?
By default, TalkJS waits 5 seconds for your server to answer a webhook. If it doesn't get a 200 OK, it retries a small number of times. A model call can take longer than that, so the handler answers TalkJS first and calls the model afterwards.
The reply uses the incoming message's ID as its idempotencyKey. TalkJS creates a message with a given key only once, however many times you send the request. When we sent the same event twice, as a retry would, the model ran twice and TalkJS stored one reply. To avoid paying for the second model call too, keep a record of the message IDs you've already answered.
How do I show that the agent is working on an answer?
While the model thinks, a silent chat looks broken. Two ways to show that an answer is on its way:
- Post a placeholder, then edit it. Send a short message such as "Looking that up…" as the agent, then edit the message with the answer. An edit fires
message.updated, notmessage.sent, so the answer doesn't come back to your handler as a new message. - Show a typing indicator. If the agent is also connected through the Data API,
markAsTypingshows it as typing for 10 seconds. The indicator ends when the agent's message arrives.
With the webhook handler above, we'd go with the placeholder: it's the REST API you're already calling, and the typing indicator needs a second connection.
Can the agent listen without a webhook?
Yes. The agent can connect to TalkJS as itself with the JavaScript Data API, which runs in Node.js, and react to new messages with subscribeConversations. Your server then needs no public URL, but it has to stay running. Our Node.js chat guide has the code. In our test there, one subscription heard new messages in two conversations 134 to 257 ms after we started sending them through the REST API, and both replies were stored.
What can the agent send besides plain text?
- Formatting and links. Messages support text formatting, and messages sent with the REST API can show a link with your own link text, written as
<https://example.com|Read more>. - Action buttons. Action buttons and links, such as
<actionbutton:confirm|Confirm>, let people reply with one click. The click reaches your frontend as an event, and your app decides what happens next. - System messages. A system message shows a status line such as "The assistant left the conversation". It looks different from user messages and doesn't trigger notifications.
How do I hand the conversation to a person?
Add them to the conversation, and they'll see everything so far, including the agent's messages. To take the agent out, remove it as a participant. From then on, it doesn't see new messages.
Next steps
- AI agent and chatbot integration in the TalkJS docs, with links to each reference page
- Example projects for OpenAI, Claude and Gemini
- How to integrate a chatbot into your TalkJS chat with the OpenAI API, for a chatbot that talks to each user on their own
- AI agents in conversations between users