GPChat Developers
FR
Tutorial · step by step

Build “Anne”, an AI bot, from A to Z

This guide has you build, test and deploy a real AI-powered GPChat bot in Node.js and TypeScript — leaving nothing out: project setup, receiving messages, calling an AI model, conversation memory, risk-free testing, then going live for real. Allow about 45 minutes and under 200 lines of code in total.

This tutorial assumes you know the platform basics (application, bot, API key, webhook). If a term is unclear, the Key concepts section of the documentation defines them all in one table. Prefer a ready-made starting point? Clone the official bot template.

There is no separate test environment (“staging”) for third-party developers — the GPChat app distributed on the stores only talks to production. This whole tutorial therefore takes place directly in production, from the first step, and that is perfectly safe: see the box in step 1.

Prerequisites

ToolVersionWhy
Node.js≥ 18native fetch, no extra HTTP dependency
A GPChat account—To create your application and your bot
A terminal + a code editor—VS Code or similar
A free Gemini key—The bot's “intelligence” (step 2, free, 2 minutes)

No database, no paid cloud account, no superfluous framework: the goal is to show you that the essentials fit in very little code.

How it fits together

Five actors, a single round trip per message:

  1. A user writes to Anne from the GPChat app (mobile or web).
  2. GPChat calls your server: a signed POST to your webhook URL, with the received message.
  3. Your server verifies the signature, acknowledges immediately (even before answering the user — mandatory, see Webhooks), then processes the message.
  4. Your server queries Gemini with the user's message and the recent conversation history.
  5. Your server sends the answer back to the user through the GPChat API (POST /v1/messages).
User → GPChat app → [signed webhook] → Your server → [prompt] → Gemini
                                                  ↓
User ← GPChat app ← [POST /v1/messages] ← Your server ← [answer] ← Gemini

Your server stores nothing durable in this tutorial: the conversation history lives in memory (a Map), which is plenty for a personal bot or a demo. The Going further section explains how to make it persistent.

1Create your bot

There is no separate “sandbox” at GPChat: the mobile app distributed on the stores only talks to production, so there is nothing else to connect to. We create the bot directly in production, right now.

This is completely risk-free. A freshly created bot is a draft: only you and the users you explicitly authorize can use it, others do not see it in search and their messages are never forwarded to you (see Draft and publication). A bot can also only answer someone who has already written to it first (see anti-spam rules) — so you can develop, break, fix and retest as much as you like, discreetly, with your own usual GPChat account.

  1. Open the developer console and sign in (QR code from the GPChat app, or Google).
  2. Create an application named for example Anne, with Create the bot ticked.
  3. Copy right away the two values shown only once:
    • the API key: gpk_live_… (64 hexadecimal characters after the prefix);
    • the webhook secret: needed to verify that received requests really come from GPChat.
  4. Give your bot a username in the console's Bot tab, for example annebot (must end with bot, 5 to 32 characters, lowercase/digits/_). Do not share it yet — we only publish the bot in step 13 (until then it stays a draft, usable by you alone).

If you lose the API key before copying it, don't panic: use the Regenerate button in the console's Credentials tab (or /token with @gpchat_forge on mobile). The old key is revoked immediately.

2Get a free Gemini key

Gemini (Google) offers a free tier that is more than enough to develop and test a personal bot.

  1. Go to aistudio.google.com/apikey and sign in with a Google account.
  2. Click Create API key, choose or create a Google Cloud project, then copy the generated key (starts with AIza…).
  3. Keep it aside: it will join your .env file in the next step.

The exact name of the available model may change over time. This tutorial uses gemini-flash-latest (fast, inexpensive, more than enough for a conversational bot); check Google AI Studio if you want to change it.

3Initialize the project

One folder, five files, four dependencies.

mkdir anne-bot && cd anne-bot
npm init -y
npm install express dotenv
npm install -D typescript tsx @types/express @types/node

Create tsconfig.json:

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "CommonJS",
    "outDir": "dist",
    "rootDir": "src",
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}

Open package.json and add these scripts (next to the ones generated by npm init):

package.json (excerpt)
"scripts": {
  "dev": "tsx watch src/index.ts",
  "build": "tsc",
  "start": "node dist/index.js"
}

Create the file tree:

mkdir src
touch src/gpchat.ts src/gemini.ts src/memory.ts src/index.ts .env .env.example .gitignore
.gitignore
node_modules/
dist/
.env
.env.example
# Copy this file to .env and fill in the real values.
# NEVER commit the .env file (see docs.html#security).

# --- GPChat (step 1) ---
GPCHAT_API_KEY=gpk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GPCHAT_WEBHOOK_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GPCHAT_SEND_URL=https://api.gpchat.app/v1/messages

# --- Gemini (step 2) ---
GEMINI_API_KEY=AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
GEMINI_MODEL=gemini-flash-latest

# --- Server ---
PORT=3000

Copy this file to .env and fill it with your real values (API key and webhook secret from step 1, Gemini key from step 2). We won't touch it again until deployment (step 12).

cp .env.example .env
# then edit .env with your real values

4Verify webhook signatures

Before processing any message, you must make sure it really comes from GPChat and not from a third party who guessed your URL. GPChat signs every request with HMAC-SHA256 (full details: Verify the signature) — here is the implementation, isolated in its own file to stay reusable.

src/gpchat.ts
import crypto from 'node:crypto';

const { GPCHAT_API_KEY, GPCHAT_WEBHOOK_SECRET, GPCHAT_SEND_URL } = process.env;

if (!GPCHAT_API_KEY || !GPCHAT_WEBHOOK_SECRET || !GPCHAT_SEND_URL) {
  throw new Error(
    'Missing variables: GPCHAT_API_KEY, GPCHAT_WEBHOOK_SECRET, GPCHAT_SEND_URL (see .env.example)',
  );
}

/**
 * Checks that a webhook request really comes from GPChat.
 * `rawBody` MUST be the raw request body (never already re-serialized JSON:
 * the slightest different byte invalidates the signature).
 */
export function verifyWebhookSignature(
  rawBody: string,
  signatureHeader: string | undefined,
  toleranceSeconds = 300,
): boolean {
  // Several "v1=" possible during a secret rotation (see the docs, "Secret rotation")
  const match = /^t=(\d+)((?:,v1=[0-9a-f]{64})+)$/.exec(signatureHeader || '');
  if (!match) return false;

  const [, timestamp, signatures] = match;
  const ageSeconds = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (ageSeconds > toleranceSeconds) return false; // replay protection

  const expected = crypto
    .createHmac('sha256', GPCHAT_WEBHOOK_SECRET!)
    .update(`${timestamp}.${rawBody}`)
    .digest();

  return signatures.split(',').filter(Boolean).some((part) => {
    const provided = Buffer.from(part.slice(3), 'hex');
    return provided.length === expected.length && crypto.timingSafeEqual(expected, provided);
  });
}

/** Sends a text message to a user through the GPChat API. */
export async function sendTextMessage(to: string, content: string): Promise<void> {
  // GPChat allows 4096 characters max — we cut with margin so it never fails.
  const truncated = content.length > 4000 ? content.slice(0, 3997) + '…' : content;

  const res = await fetch(GPCHAT_SEND_URL!, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${GPCHAT_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ to, type: 'text', content: truncated }),
  });

  if (!res.ok) {
    const body = await res.text().catch(() => '');
    throw new Error(`GPChat send failed (${res.status}): ${body}`);
  }
}

fetch is native from Node 18: no extra HTTP dependency is needed.

5The Express server

The most important point of this tutorial: acknowledge within 10 seconds, even before you have finished processing the message (see Webhooks). The request body must stay raw (not parsed as JSON by Express) so the signature can be verified.

src/index.ts (version 1 — skeleton)
import 'dotenv/config';
import express from 'express';
import { verifyWebhookSignature, sendTextMessage } from './gpchat';

const app = express();
const PORT = Number(process.env.PORT) || 3000;

app.get('/', (_req, res) => res.send('Anne is online 👋'));

app.post(
  '/webhook',
  express.raw({ type: 'application/json' }), // RAW body, not express.json()
  async (req, res) => {
    const rawBody = req.body.toString('utf8');

    if (!verifyWebhookSignature(rawBody, req.get('X-GPChat-Signature'))) {
      return res.sendStatus(401);
    }

    // We acknowledge RIGHT AWAY: processing (AI call, sending the
    // answer) continues afterwards, without making GPChat wait.
    res.sendStatus(200);

    const event = JSON.parse(rawBody) as { type: string; data: Record<string, unknown> };
    void handleEvent(event).catch((err) => console.error('Processing error:', err));
  },
);

async function handleEvent(event: { type: string; data: Record<string, unknown> }) {
  if (event.type !== 'message.received') return; // groups ignored for now
  const chatId = event.data.chatId as string;
  const text = (event.data.textMsg as string) || '';
  if (!text) return;

  await sendTextMessage(chatId, `You wrote: “${text}”`);
}

app.listen(PORT, () => console.log(`Anne is listening on http://localhost:${PORT}`));

At this point, Anne already answers — as an echo. It is of little use, but it validates the whole mechanism (signature, reception, sending) before adding the complexity of AI. We will now replace the echo with a real Gemini call.

6Call Gemini

A simple REST call, no SDK: one request, one response. We keep gemini.ts completely independent from GPChat — it only knows about messages, it could serve any other project.

src/gemini.ts
const { GEMINI_API_KEY, GEMINI_MODEL = 'gemini-flash-latest' } = process.env;

if (!GEMINI_API_KEY) {
  throw new Error('Missing variable: GEMINI_API_KEY (see .env.example)');
}

export type ChatTurn = { role: 'user' | 'model'; text: string };

const SYSTEM_PROMPT =
  "You are Anne, a friendly and concise assistant on GPChat. " +
  "You answer in the user's language, in 2 to 4 sentences at most, without excessive emojis. " +
  "If you don't know, simply say so rather than making things up.";

/** Queries Gemini with the conversation history and returns the text of the answer. */
export async function askGemini(history: ChatTurn[]): Promise<string> {
  const url =
    `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent` +
    `?key=${GEMINI_API_KEY}`;

  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      systemInstruction: { parts: [{ text: SYSTEM_PROMPT }] },
      contents: history.map((turn) => ({
        role: turn.role,
        parts: [{ text: turn.text }],
      })),
      generationConfig: { maxOutputTokens: 300, temperature: 0.7 },
    }),
  });

  if (!res.ok) {
    const body = await res.text().catch(() => '');
    throw new Error(`Gemini call failed (${res.status}): ${body}`);
  }

  const json = await res.json();
  const text = json?.candidates?.[0]?.content?.parts?.[0]?.text;
  if (!text) throw new Error('Empty or unexpected Gemini response');
  return text.trim();
}

The Gemini key, like the GPChat API key, must exist only on the server side (.env file, never in a public repository nor in code running in a browser).

7Conversation memory

Without memory, each message would be handled in isolation and Anne would “forget” everything from one answer to the next. A simple in-memory Map, limited to the latest exchanges, is plenty for a personal bot — no database needed to start.

src/memory.ts
import type { ChatTurn } from './gemini';

const MAX_TURNS_PER_USER = 10; // 5 user/bot exchanges
const conversations = new Map<string, ChatTurn[]>();

export function getHistory(userId: string): ChatTurn[] {
  return conversations.get(userId) ?? [];
}

export function pushTurn(userId: string, turn: ChatTurn): ChatTurn[] {
  const history = [...getHistory(userId), turn].slice(-MAX_TURNS_PER_USER);
  conversations.set(userId, history);
  return history;
}

export function resetHistory(userId: string): void {
  conversations.delete(userId);
}

This memory is lost every time the server restarts (deployment, crash, scheduled restart) — a deliberate choice to keep things simple. The Going further section explains how to make it persistent if you need it.

8/start and /reset commands, then Gemini for the rest

We assemble everything in index.ts: two utility commands, and Gemini for everything else. We also guard against messages that are not text (image, location…), which Anne cannot read yet.

src/index.ts (final version)
import 'dotenv/config';
import express from 'express';
import { verifyWebhookSignature, sendTextMessage } from './gpchat';
import { askGemini } from './gemini';
import { getHistory, pushTurn, resetHistory } from './memory';

const app = express();
const PORT = Number(process.env.PORT) || 3000;

// Deduplication: the same webhook delivery can be replayed by
// GPChat (see docs.html#webhook-events) — we ignore msgIds already seen.
const seenMessageIds = new Set<string>();
function alreadyProcessed(msgId: string): boolean {
  if (seenMessageIds.has(msgId)) return true;
  seenMessageIds.add(msgId);
  if (seenMessageIds.size > 500) {
    seenMessageIds.delete(seenMessageIds.values().next().value!);
  }
  return false;
}

app.get('/', (_req, res) => res.send('Anne is online 👋'));

app.post(
  '/webhook',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const rawBody = req.body.toString('utf8');

    if (!verifyWebhookSignature(rawBody, req.get('X-GPChat-Signature'))) {
      return res.sendStatus(401);
    }
    res.sendStatus(200);

    const event = JSON.parse(rawBody) as { type: string; data: Record<string, unknown> };
    void handleEvent(event).catch((err) => console.error('Processing error:', err));
  },
);

async function handleEvent(event: { type: string; data: Record<string, unknown> }) {
  if (event.type === 'ping') return; // "Send a ping" from the console
  if (event.type !== 'message.received') return; // groups: see "Going further"

  const { msgId, chatId, type, textMsg } = event.data as {
    msgId: string; chatId: string; type: string; textMsg?: string;
  };
  if (alreadyProcessed(msgId)) return;

  if (type !== 'text') {
    await sendTextMessage(chatId, "I can only read text for now 🙂");
    return;
  }

  const text = (textMsg || '').trim();

  if (text === '/start') {
    await sendTextMessage(chatId, "Hello, I'm Anne 👋 Ask me a question, I remember our conversation. Type /reset to start over.");
    return;
  }
  if (text === '/reset') {
    resetHistory(chatId);
    await sendTextMessage(chatId, 'Memory cleared ✅ Starting from scratch.');
    return;
  }
  if (!text) return;

  try {
    const history = pushTurn(chatId, { role: 'user', text });
    const reply = await askGemini(history);
    pushTurn(chatId, { role: 'model', text: reply });
    await sendTextMessage(chatId, reply);
  } catch (err) {
    console.error('AI error:', err);
    await sendTextMessage(chatId, "Sorry, I had trouble answering. Please try again in a moment 🙏");
  }
}

app.listen(PORT, () => console.log(`Anne is listening on http://localhost:${PORT}`));

That's it. Under 130 lines across four files, and Anne already knows how to: receive messages securely (verified signature), hold a conversation with memory, handle two commands, and never fail silently on an AI error.

9Run locally with an HTTPS tunnel

GPChat must be able to reach your webhook from the Internet, over HTTPS. During development, a tunnel saves you from deploying for every test. (Prefer no tunnel at all? Switch the app to polling mode with /setmode polling and fetch events with GET /v1/updates — no public server needed.)

npm run dev
# → Anne is listening on http://localhost:3000

In a second terminal, with ngrok (or Cloudflare Tunnel, equivalent):

ngrok http 3000
# → https://abcd-1-2-3-4.ngrok-free.app  (copy this HTTPS URL)

In the console, in your application's Webhooks tab, paste https://abcd-1-2-3-4.ngrok-free.app/webhook then click Send a ping. Your terminal should show the received request and answer 200 immediately.

A free ngrok URL changes every time the tunnel restarts: update it in the console if you relaunch ngrok.

10First tests

Two ways to test, to do in this order:

A. The console simulator (without writing a real message)

Webhooks tab → Simulate an event: choose message.received, a text like What is the capital of Cameroon?, and send. The console shows the exact payload sent, the computed signature, and your server's response — handy for debugging without depending on the mobile app.

B. A real message, from your own GPChat account

No special account or environment needed: open the GPChat app you use every day (the store version), with your usual account.

  1. Search for your bot by its username (annebot, step 1) and send /start.
  2. Ask a real question. The answer should arrive in 2 to 5 seconds.
  3. Follow up with a question that depends on the previous one (“and why?”) to check that memory works.
  4. Type /reset, then ask the same follow-up question again: Anne should no longer have the context.

If all of this works, your bot is functionally complete — and already in production. The next steps do not change its behavior: they make it robust, put it on a real server, then prepare it to receive users other than yourself.

11Robustness and edge cases

The code from the previous steps already covers the most important cases. Here is what it handles and why, as a checklist:

CaseHandled by
Request that does not come from GPChatverifyWebhookSignature → 401, nothing is processed.
Same message delivered twice (webhook replayed)alreadyProcessed(msgId).
Gemini unavailable or slowtry/catch around askGemini, a friendly error message sent to the user instead of silence.
Non-text message (image, location…)Explicit answer rather than a crash on an empty textMsg.
Gemini answer too longTruncation to 4000 characters in sendTextMessage (GPChat limit: 4096).
User who has never written to the botNot applicable here: we only answer messages already received, never starting a conversation (see anti-spam rules).

Two points worth knowing that this tutorial does not code, to stay simple:

12Deploy the server

Anne must run somewhere permanently, reachable over HTTPS. The simplest way without managing a server yourself:

  1. Push your project to a Git repository (GitHub, GitLab…) — check that .env is indeed ignored (.gitignore, step 3).
  2. Create an account on a simple hosting platform (Render, Railway or Fly.io all work — the example below uses Render, whose free tier is enough to start).
  3. Create a “Web Service” pointing to your repository, with:
    • Build command: npm install && npm run build
    • Start command: npm start
  4. Set the environment variables from your .env in the platform's interface (never in the code pushed to Git).
  5. Deploy: you get a stable HTTPS URL, for example https://anne-bot.onrender.com.

Whatever platform you choose, the only requirements are: HTTPS, a stable public address, and the ability to set environment variables outside the code. A VPS with a reverse proxy (Caddy or nginx + Let's Encrypt) works just as well if you prefer to control everything — see the Docker Compose deployment guide of the bot library.

13Prepare for a real launch

Your bot has been running in production since step 1 — so there is no key to change, no URL to switch. You only have one thing left to update (the webhook URL, which pointed to your local tunnel) and to check that you are ready before publishing.

  1. Enter the final webhook URL (that of your step 12 deployment, for example https://anne-bot.onrender.com/webhook) in the console, in place of the ngrok URL. Click Send a ping to confirm.
  2. Retest one last time with your own account (/start, a question, /reset) to validate that the new server answers properly.
  3. Check the quota: 60 requests/minute by default (see Limits and quotas) — plenty to start, to watch if the bot becomes popular.
  4. Set an alert contact (e-mail or Slack/Discord webhook) in the console's Settings tab, to be warned if your server goes down (see Retries and monitoring).
  5. Add a photo and a description in the Bot tab (or /setphoto and /setdescription with @gpchat_forge): a bot with a face and a clear description earns trust.

Your bot is ready to welcome real users. Two options:

Once published, share its username or list it in the Bot store (reminder: a user must always write to your bot first — see anti-spam rules).

Complete code

The four files in src/, as they should look at the end of the tutorial:

import crypto from 'node:crypto';

const { GPCHAT_API_KEY, GPCHAT_WEBHOOK_SECRET, GPCHAT_SEND_URL } = process.env;

if (!GPCHAT_API_KEY || !GPCHAT_WEBHOOK_SECRET || !GPCHAT_SEND_URL) {
  throw new Error(
    'Missing variables: GPCHAT_API_KEY, GPCHAT_WEBHOOK_SECRET, GPCHAT_SEND_URL (see .env.example)',
  );
}

export function verifyWebhookSignature(
  rawBody: string,
  signatureHeader: string | undefined,
  toleranceSeconds = 300,
): boolean {
  // Several "v1=" possible during a secret rotation (see the docs, "Secret rotation")
  const match = /^t=(\d+)((?:,v1=[0-9a-f]{64})+)$/.exec(signatureHeader || '');
  if (!match) return false;

  const [, timestamp, signatures] = match;
  const ageSeconds = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (ageSeconds > toleranceSeconds) return false;

  const expected = crypto
    .createHmac('sha256', GPCHAT_WEBHOOK_SECRET!)
    .update(`${timestamp}.${rawBody}`)
    .digest();

  return signatures.split(',').filter(Boolean).some((part) => {
    const provided = Buffer.from(part.slice(3), 'hex');
    return provided.length === expected.length && crypto.timingSafeEqual(expected, provided);
  });
}

export async function sendTextMessage(to: string, content: string): Promise<void> {
  const truncated = content.length > 4000 ? content.slice(0, 3997) + '…' : content;

  const res = await fetch(GPCHAT_SEND_URL!, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${GPCHAT_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ to, type: 'text', content: truncated }),
  });

  if (!res.ok) {
    const body = await res.text().catch(() => '');
    throw new Error(`GPChat send failed (${res.status}): ${body}`);
  }
}
const { GEMINI_API_KEY, GEMINI_MODEL = 'gemini-flash-latest' } = process.env;

if (!GEMINI_API_KEY) {
  throw new Error('Missing variable: GEMINI_API_KEY (see .env.example)');
}

export type ChatTurn = { role: 'user' | 'model'; text: string };

const SYSTEM_PROMPT =
  "You are Anne, a friendly and concise assistant on GPChat. " +
  "You answer in the user's language, in 2 to 4 sentences at most, without excessive emojis. " +
  "If you don't know, simply say so rather than making things up.";

export async function askGemini(history: ChatTurn[]): Promise<string> {
  const url =
    `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent` +
    `?key=${GEMINI_API_KEY}`;

  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      systemInstruction: { parts: [{ text: SYSTEM_PROMPT }] },
      contents: history.map((turn) => ({
        role: turn.role,
        parts: [{ text: turn.text }],
      })),
      generationConfig: { maxOutputTokens: 300, temperature: 0.7 },
    }),
  });

  if (!res.ok) {
    const body = await res.text().catch(() => '');
    throw new Error(`Gemini call failed (${res.status}): ${body}`);
  }

  const json = await res.json();
  const text = json?.candidates?.[0]?.content?.parts?.[0]?.text;
  if (!text) throw new Error('Empty or unexpected Gemini response');
  return text.trim();
}
import type { ChatTurn } from './gemini';

const MAX_TURNS_PER_USER = 10;
const conversations = new Map<string, ChatTurn[]>();

export function getHistory(userId: string): ChatTurn[] {
  return conversations.get(userId) ?? [];
}

export function pushTurn(userId: string, turn: ChatTurn): ChatTurn[] {
  const history = [...getHistory(userId), turn].slice(-MAX_TURNS_PER_USER);
  conversations.set(userId, history);
  return history;
}

export function resetHistory(userId: string): void {
  conversations.delete(userId);
}
import 'dotenv/config';
import express from 'express';
import { verifyWebhookSignature, sendTextMessage } from './gpchat';
import { askGemini } from './gemini';
import { getHistory, pushTurn, resetHistory } from './memory';

const app = express();
const PORT = Number(process.env.PORT) || 3000;

const seenMessageIds = new Set<string>();
function alreadyProcessed(msgId: string): boolean {
  if (seenMessageIds.has(msgId)) return true;
  seenMessageIds.add(msgId);
  if (seenMessageIds.size > 500) {
    seenMessageIds.delete(seenMessageIds.values().next().value!);
  }
  return false;
}

app.get('/', (_req, res) => res.send('Anne is online 👋'));

app.post(
  '/webhook',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const rawBody = req.body.toString('utf8');

    if (!verifyWebhookSignature(rawBody, req.get('X-GPChat-Signature'))) {
      return res.sendStatus(401);
    }
    res.sendStatus(200);

    const event = JSON.parse(rawBody) as { type: string; data: Record<string, unknown> };
    void handleEvent(event).catch((err) => console.error('Processing error:', err));
  },
);

async function handleEvent(event: { type: string; data: Record<string, unknown> }) {
  if (event.type === 'ping') return;
  if (event.type !== 'message.received') return;

  const { msgId, chatId, type, textMsg } = event.data as {
    msgId: string; chatId: string; type: string; textMsg?: string;
  };
  if (alreadyProcessed(msgId)) return;

  if (type !== 'text') {
    await sendTextMessage(chatId, "I can only read text for now 🙂");
    return;
  }

  const text = (textMsg || '').trim();

  if (text === '/start') {
    await sendTextMessage(chatId, "Hello, I'm Anne 👋 Ask me a question, I remember our conversation. Type /reset to start over.");
    return;
  }
  if (text === '/reset') {
    resetHistory(chatId);
    await sendTextMessage(chatId, 'Memory cleared ✅ Starting from scratch.');
    return;
  }
  if (!text) return;

  try {
    const history = pushTurn(chatId, { role: 'user', text });
    const reply = await askGemini(history);
    pushTurn(chatId, { role: 'model', text: reply });
    await sendTextMessage(chatId, reply);
  } catch (err) {
    console.error('AI error:', err);
    await sendTextMessage(chatId, "Sorry, I had trouble answering. Please try again in a moment 🙏");
  }
}

app.listen(PORT, () => console.log(`Anne is listening on http://localhost:${PORT}`));

Going further

Want to…Lead
Answer in groups tooHandle the group_message.received event (see Events and payload); only answer when isMentioned is true, or you will spam the group.
Keep memory after a restartReplace the Map in memory.ts with a table in Redis, SQLite or Postgres — the interface (getHistory/pushTurn/resetHistory) stays identical, only the file changes.
Add commands visible in the / menuConsole → Bot tab → Commands (or /setcommands with @gpchat_forge).
Answer with images, location, etc.All message types — same endpoint, just other fields.
Be alerted if the webhook goes downSet an e-mail or alert webhook in the console's Settings tab (see Retries and monitoring).
Start from a production-grade skeletonThe official bot template and the bot library (polling and webhook, tests, Docker, CI).
Let users sign in with their GPChat accountThat is a different need (acting on behalf of a user, not sending messages): see Login with GPChat (OAuth2).

Final checklist

Well done — you have a complete AI bot, tested, and in production. What comes next is a matter of taste: extra commands, persistent memory, group support. Everything you need is in the full documentation.