IntegrationsIntermediate

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.

8 minIntermediate

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.

memory.js
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.

handler.js
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;
}
Chat - follow up works
You
My dog is named Pixel.
Agent
Nice to meet Pixel! How can I help?
You
What did I just name my dog?
Agent
You named your dog Pixel.
The second question relies on the first answer.
A Map resets on restart
In-memory history vanishes when the process restarts and does not scale across multiple instances. For production, store history in Redis or a database keyed by user id with a time-to-live.
Add a reset command
Give users a way to clear their own history, for example a /reset command or the keyword forget, by deleting their key from the map. It prevents stale context from derailing a new topic.

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

Tags
#memory#context#bot#ai#history