How to Give Your Chat Bot Memory of the Conversation
Store recent messages per user so your Discord, Slack, WhatsApp or Viber bot remembers context.
Out of the box, most bots forget everything between messages because each request sends only the latest line. Adding short-term memory means your bot can follow up, remember names, and stay on topic. This platform-agnostic pattern works the same for Discord, Slack, WhatsApp, and Viber.
What you need
- Any working AI chat bot from the other guides
- A stable per-user identifier (Discord user id, Slack user, phone number, Viber sender id)
- Node 18+ installed
Step 1: Keep a history map
Store an array of past messages keyed by the user id. An in-memory Map is fine to start. Trim it to the last several turns so you do not overflow the context window or your token budget.
const history = new Map(); // userId -> messages[]
const MAX_TURNS = 8; // user + assistant pairs
export function remember(userId, role, content) {
const log = history.get(userId) || [];
log.push({ role, content });
// keep system prompt out of the trim window
while (log.length > MAX_TURNS * 2) log.shift();
history.set(userId, log);
return log;
}Step 2: Send the history with each request
Before calling the model, push the new user message into memory and prepend a system prompt. After the model answers, store its reply too so the next turn includes it.
import { remember } from "./memory.js";
async function reply(userId, text) {
const log = remember(userId, "user", text);
const res = await ai.chat.completions.create({
model: "gpt-5-mini",
messages: [
{ role: "system", content: "You are a helpful assistant with memory." },
...log,
],
});
const answer = res.choices[0].message.content;
remember(userId, "assistant", answer);
return answer;
}Result
Your bot now follows the thread of a conversation instead of treating every message as the first. Swap the Map for Redis when you deploy more than one instance and you have production-ready memory.
Watch related tutorials
12:05
5:42
24:16
33:42
41:18
28:05