const ANSWERS = {
hours: "We're available Monday–Friday, 9am–6pm CET.",
return: "You can start a return at example.com/returns. Need anything else?",
shipping: "Standard shipping takes 3–5 business days.",
};
function matchAnswer(text) {
const lower = text.toLowerCase();
return Object.entries(ANSWERS).find(([keyword]) =>
lower.includes(keyword),
)?.[1];
}
async function botRequest(path, body) {
const res = await fetch(
`https://api.livechat.com/v3.6/agent/action/${path}`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.BOT_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
},
);
return res.json();
}
async function sendMessage(chatId, text) {
return botRequest("send_event", {
chat_id: chatId,
event: { type: "message", text, visibility: "all" },
});
}
async function transferToHuman(chatId) {
return botRequest("transfer_chat", {
id: chatId,
target: { type: "group", ids: [Number(process.env.HUMAN_GROUP_ID)] },
});
}
app.post("/webhooks/text", async (req, res) => {
const { action, payload } = req.body;
if (action === "incoming_chat") {
const chatId = payload.chat.id;
const name =
payload.chat.users.find((u) => u.type === "customer")?.name ?? "there";
await sendMessage(
chatId,
`Hi ${name}! I can help with orders, returns, and shipping. What do you need?`,
);
}
if (action === "incoming_event") {
const { chat_id: chatId, event } = payload;
if (event.type !== "message") return res.sendStatus(200);
const answer = matchAnswer(event.text);
if (answer) {
await sendMessage(chatId, answer);
} else {
await sendMessage(
chatId,
"Let me connect you with a team member who can help.",
);
await transferToHuman(chatId);
}
}
res.sendStatus(200);
});