Build on GPChat
Create bots that talk to your users, automate groups and broadcast lists, publish stories, and connect your services to your users' GPChat accounts.
Base URL
| Environment | URL | Console |
|---|---|---|
| Production | https://api.gpchat.app | console.html (French) |
There is no staging environment open to third-party developers: the GPChat mobile app distributed on the stores can only connect to production, so there is no way to exchange real messages anywhere else. To test safely, every new application starts as a draft: only you and the users or groups you authorize can use it, and it is invisible in other people's search. You therefore develop and test directly in production with no impact on other users, then publish it yourself when it is ready.
Quick start
- Sign in to the developer console by scanning the QR code with the GPChat app (Settings → GPChat for Developers → Web sign-in), or with Google.
- Create an application with "Create the bot" ticked. Copy the API key (
gpk_live_…) and the webhook secret right away: they will not be shown again.From your phone you can also message @gpchat_forge and type
/newbot. - Expose an HTTPS endpoint that receives webhooks, enter its URL in the Webhooks tab and click "Send a ping". No public server (working on localhost)? Use polling mode instead, or a tunnel such as ngrok.
- Message your bot from the GPChat app (search for its username). Your server receives a
message.receivedevent. - Reply with the API, using
data.chatIdas the recipient:
import express from 'express';
import crypto from 'node:crypto';
const app = express();
const { GPCHAT_API_KEY, GPCHAT_WEBHOOK_SECRET } = process.env;
// RAW body required to verify the signature
app.post('/gpchat/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
if (!verify(req.body, req.get('X-GPChat-Signature'), GPCHAT_WEBHOOK_SECRET)) {
return res.sendStatus(401);
}
res.sendStatus(200); // acknowledge right away (< 10 s)
const { type, data } = JSON.parse(req.body);
if (type === 'message.received' && data.textMsg === '/start') {
await fetch('https://api.gpchat.app/v1/messages', {
method: 'POST',
headers: { Authorization: `Bearer ${GPCHAT_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ to: data.chatId, type: 'text', content: 'Welcome! 👋' }),
});
}
});
function verify(rawBody, header, secret) {
// "v1=" can appear several times during a secret rotation
const m = /^t=(\d+)((?:,v1=[0-9a-f]{64})+)$/.exec(header || '');
if (!m || Math.abs(Date.now() / 1000 - Number(m[1])) > 300) return false;
const expected = crypto.createHmac('sha256', secret).update(`${m[1]}.${rawBody}`).digest();
return m[2].split(',').filter(Boolean).some((p) => {
const got = Buffer.from(p.slice(3), 'hex');
return got.length === expected.length && crypto.timingSafeEqual(expected, got);
});
}
app.listen(3000);
import hmac, hashlib, json, os, re, time
import requests
from flask import Flask, request, abort
app = Flask(__name__)
API_KEY = os.environ["GPCHAT_API_KEY"]
SECRET = os.environ["GPCHAT_WEBHOOK_SECRET"].encode()
def verify(raw: bytes, header: str) -> bool:
m = re.fullmatch(r"t=(\d+)((?:,v1=[0-9a-f]{64})+)", header or "") # several v1= possible (rotation)
if not m or abs(time.time() - int(m[1])) > 300:
return False
expected = hmac.new(SECRET, f"{m[1]}.".encode() + raw, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, p[3:]) for p in m[2].split(",") if p)
@app.post("/gpchat/webhook")
def webhook():
raw = request.get_data() # raw body
if not verify(raw, request.headers.get("X-GPChat-Signature")):
abort(401)
event = json.loads(raw)
if event["type"] == "message.received" and event["data"].get("textMsg") == "/start":
requests.post(
"https://api.gpchat.app/v1/messages",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"to": event["data"]["chatId"], "type": "text", "content": "Welcome! 👋"},
timeout=10,
)
return "", 200
curl -X POST https://api.gpchat.app/v1/messages \
-H "Authorization: Bearer $GPCHAT_API_KEY" \
-H "Content-Type: application/json" \
-d '{"to": "USER_ID", "type": "text", "content": "Welcome! 👋"}'
Bot template and open-source library
To get going fast with the structure GPChat expects (polling or signed-webhook delivery, signature verification, deduplication by msgId, buttons, Markdown, rate limiting, graceful shutdown, tests, Docker, CI), start from the official template — a real, commented project that works on the first run:
In your language — same architecture, same commands, same behaviour (ordered parallel polling, signed webhook, buttons, FR/EN, health and metrics, Docker, CI, tests):
git clone https://github.com/GPChat-Platform/bot-template my-bot
cd my-bot && npm install
GPCHAT_API_KEY=gpk_live_… npm start # polling mode: no public server needed
npm test # tests included, no network
The official Node.js SDK (@gpchat/bot, dependency-free) ships with the template; a Python SDK lives in the cloud/sdk/python repository. Your bot can run anywhere: a VPS (Docker), Firebase Functions, Cloud Run, Cloudflare Workers…
Key concepts
| Concept | Description |
|---|---|
| Application | Container for your credentials: App ID (= OAuth2 client_id), client_secret, API key(s), webhook and signing secret. Maximum 20 applications per account. |
| Bot | A real GPChat account (isBot: true) attached to an application (one per application). It receives and sends messages like a user, privately or in the groups it belongs to. |
| Draft / Published | An application is created as a draft (usable by you and your testers only) then published by you (open to everyone). See Draft and publication. |
| API key | gpk_live_… — identifies the bot. Default scopes: messages:send, groups:manage. Only its SHA-256 fingerprint is stored: it is shown only once. |
| OAuth2 token | gpat_… (access, 1 h) and gprt_… (refresh, 30 days) — let you act on behalf of a user who has given consent. |
| Webhook | HTTPS URL of your server, called for every message your bot receives. Signed with HMAC-SHA256. |
| userId | Stable identifier of a GPChat user. You get it through webhooks (from, chatId) or through /oauth/userinfo (sub). |
Authentication
Every request carries a token in the Authorization header:
Authorization: Bearer gpk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
| Endpoint | API key (bot) | OAuth2 token (user) | Required scope |
|---|---|---|---|
/v1/messages, /v1/messages/group | ✅ | — | messages:send |
/v1/groups/* | ✅ | ✅ | groups:manage |
/v1/stories, /v1/stories/delete | — | ✅ | stories:write |
/v1/stories/mine | — | ✅ | stories:read |
/v1/polls/* | ✅ | ✅ | polls:write |
/oauth/userinfo | — | ✅ | profile |
Never expose an API key or a client_secret on the client side (browser, mobile app, code repository). Call the API from your server only.
Create and manage a bot
In the console, Bot tab:
- Description (512 characters) — shown on the bot's profile and when the conversation opens.
- Commands (50 max) — offered in the app's
/menu. Name: lowercase letters, digits and_(32 characters); description: 256 characters. - Display name — follows the application name (Settings tab).
- Photo — https URL of a square image (512 × 512 recommended, PNG or JPEG): console → Bot, or
/setphotoin @gpchat_forge (send the image right after the command, or/setphoto https://…;/setphoto removeremoves it). Through the API: thebotPhotoUrlfield ofupdateDeveloperApp.
With @gpchat_forge on mobile: /newbot, /mybots, /token, /setdescription, /setphoto, /setcommands, /setwebhook, /setmode, /testwebhook, /status, /addtester, /removetester, /testers, /publish, /unpublish, /cancel. The username must end with bot (5 to 32 characters, lowercase/digits/_) and cannot contain "gpchat".
/token immediately revokes the current key and issues a new one.
A freshly created bot is a draft: see Draft and publication to authorize testers, then publish it.
Draft and publication
You publish your application yourself, with no manual review: an automatic checklist, acceptance of the terms and a few caps protect users.
The two states
| 🧪 Draft (initial state) | 🌍 Published | |
|---|---|---|
| Who can use the bot | You, and the users and groups you authorize | All GPChat users |
| Search by @username | Visible only to you and your testers | Visible to everyone |
| Bot directory | Absent | Listed |
| Webhooks | Only for messages from you, your testers and your authorized groups. Messages from any other user are never forwarded to you. | All messages received by the bot |
| API (messages, groups, polls) | Only towards you, your testers and your authorized groups | Under the usual rules |
| Login with GPChat (OAuth2) | Authorization and tokens reserved for you and your testers | All users |
Applications created before drafts were introduced remain published: nothing changes for them.
Authorize testers
Console → Publication tab, or with @gpchat_forge (/addtester @username, /removetester @username, /testers).
- Users: up to 25, identified by their @username. An account that has disabled discovery by @username cannot be added this way.
- Groups: up to 10. You must be an administrator of the group: authorizing a group means accepting that its members' messages are relayed to your webhook, which is for the group's administrators to decide. A group created by your bot through the API is authorized automatically.
- You always have access to your own application. The bot must always have been added to the group by an administrator.
- For a tester to open your bot, share its link (
https://gpchat.app/bot/your_bot) or its @username; they can also find it in search, which shows them your draft bot.
Publish
Publishing requires all of the following to pass (checked automatically, Publication tab or /status):
| Item | Why |
|---|---|
| Application active (neither disabled nor suspended) and publication not blocked by GPChat | — |
| Bot created | Users write to the bot. |
| Name and @username without gpchat, forge, anne ai, official, admin, verified | Prevent impersonation of GPChat or its official bots. |
| Description of at least 20 characters | Users must know what the bot does before writing to it. |
| Webhook configured and successfully tested (2xx response from the current URL) | A bot whose server does not answer would be published but silent. Changing the URL invalidates the test. |
| Acceptance of the publication terms | See below. |
Console → Publication → Publish, or /publish then /publish confirm with @gpchat_forge. You can go back to draft at any time (/unpublish): the bot disappears from search and the directory, your testers are kept, and so are existing conversations.
Limits
| Limit | Value |
|---|---|
| Applications published at the same time per account | 5 |
| Publications / unpublications | 10 per hour |
| Tester additions / removals | 30 per minute |
Publication terms (version 2026-10)
By publishing, you acknowledge that:
- you are responsible for the bot, its replies and the processing of the messages your webhook receives; you comply with GPChat's Terms of Service and Privacy Policy as well as the applicable personal-data law;
- you do not collect, resell or share users' data with third parties without their explicit consent, and you use it only to provide the service described by your bot;
- your bot does not impersonate anyone (GPChat, another service, a person), does not distribute illegal content, harassment, scams or spam, and does not solicit users (see Rules and anti-spam);
- GPChat may, at any time and without notice in case of abuse, put your bot back to draft, block its publication or suspend the application (notably following user reports);
- the moment and the version of the terms you accept are recorded.
If GPChat blocks the publication of an application, the console shows it with the reason and publication stays impossible until GPChat lifts the block: write to infos@gpchat.app.
Draft-related errors
A draft bot that targets an unauthorized user or group receives 403 permission-denied ("This application is not published yet…"). No information about the existence or state of the targeted account is disclosed.
Secret rotation and replay
Change the signing secret without any downtime: in the console (Webhooks tab) or through the rotateWebhookSecret call, choose an overlap period from 0 to 72 h (24 h by default). During this period every event carries two signatures (t=…,v1=<new>,v1=<old>): your server accepts either one, so you can roll out the new secret at your own pace. With graceHours: 0, the old secret stops working immediately. The verification examples above already accept several v1= values.
Replay an event: in the Monitoring tab log, the Replay button puts the event back in the queue (new delivery signed with the active secret). Handy after an outage or to debug. Only your own application's events can be replayed.
Polling mode (no public server)
No reachable HTTPS server — for example you are developing on localhost? Switch the application to polling mode (console → Webhooks → Delivery mode, or /setmode polling in @gpchat_forge) and query the API:
curl "https://api.gpchat.app/v1/updates?limit=50&timeout=20" \
-H "Authorization: Bearer $GPCHAT_API_KEY"
# Response
{ "status": "success", "data": {
"updates": [ { "id": "evt_abc", "type": "message.received", "data": { "from": "…", "textMsg": "Hello" } } ],
"hasMore": false } }
# Acknowledge what you have processed (otherwise the event is sent again)
curl -X POST https://api.gpchat.app/v1/updates -H "Authorization: Bearer $GPCHAT_API_KEY" \
-H "Content-Type: application/json" -d '{"ack":["evt_abc"],"timeout":20}'
limit: 1 to 100 (default 50).timeout: 0 to 20 s of long polling — the call waits for an event before answering empty.- Events have the same format as webhooks (
type+data) but are not signed: your API key is the authentication. - An unacknowledged event is sent again; an event not collected within 24 h is dropped.
- In polling mode, the publication checklist replaces "webhook tested" with "polling tested": it is enough to have queried the API once.
- Same access rules as webhooks: in draft, you only receive your own messages and those of your testers.
Buttons and Markdown
Add buttons under a message with the buttons field (rows of buttons) and format the text with "parseMode": "markdown" (text messages only).
curl -X POST https://api.gpchat.app/v1/messages -H "Authorization: Bearer $GPCHAT_API_KEY" \
-H "Content-Type: application/json" -d '{
"to": "USER_ID", "type": "text",
"content": "**Vote**: _yes_ or _no_?",
"parseMode": "markdown",
"buttons": [
[ { "text": "Yes", "callbackData": "vote:yes" }, { "text": "No", "callbackData": "vote:no" } ],
[ { "text": "Visit the site", "url": "https://example.com" } ]
] }'
| Rule | Value |
|---|---|
| Rows / buttons per row / total | 5 / 4 / 20 |
text | 1 to 32 characters |
callbackData | 1 to 64 characters, no spaces (letters, digits and _ - : . | / = + # @) |
url | https:// only. A button carries either callbackData or url. |
Button click: when the user taps a callbackData button, you receive a callback.received event (webhook or polling):
{ "type": "callback.received",
"data": { "data": "vote:yes", "from": "USER_ID", "msgId": "ID_OF_THE_BUTTON_MESSAGE",
"chatId": "USER_ID", "text": "**Vote**: _yes_ or _no_?", "groupId": "(if group message)" } }
The server checks that the button really exists on a message from your bot in the user's conversation: a forged click is rejected. Use msgId with edit a message to update the interface after the click. The console simulator can simulate callback.received.
Supported Markdown: **bold**, _italic_, ~~strikethrough~~, \`code\`, code blocks, headings, lists, quotes and links [text](https://…). Images and HTML are not rendered; non-https links are displayed as text. The plain text stays in textMsg for clients that do not render Markdown.
Edit or delete a message and show "typing…"
Body: to (or groupId) + msgId + at least one of content, caption, buttons (null to remove the buttons). Only your own messages can be edited; the message is marked "edited".
Body: to (or groupId) + msgId. Deletes your message for everyone (again: only messages sent by the bot).
Shows "typing…" (action: "typing") or "recording a voice message…" ("recording") to the user for seconds (1 to 10, default 5). The call returns at the end of the duration: for long processing, send it in parallel. Same access rules as sending messages (the user must have written to the bot; in draft, only your testers).
Start link with a parameter
A link https://gpchat.app/bot/<username>?start=promo opens the conversation with your bot and automatically sends /start promo on first contact. You receive it as an ordinary message: textMsg = "/start promo". The parameter accepts 1 to 64 characters A-Z a-z 0-9 _ -. Ideal for tracking where a sign-up came from (campaign, QR code, referral) or for opening a specific flow directly.
Multiple API keys
Create up to 5 active keys per application, each with a label (40 characters) and its own permissions among messages:send, groups:manage, polls:write — one key per service or per environment, individually revocable without breaking anything else. Console → API keys, or the createApiKey / revokeApiKey calls. The key is shown only once, at creation.
Per-bot statistics
Console → Monitoring (or getBotStats, 1 to 30 days): messages received and sent, unique users, button clicks, webhook delivery rate, per day. Simulator test events are never counted.
Category and directory
Choose your bot's category (console → Bot, or /setcategory): assistant, productivity, games, education, entertainment, news, finance, utilities, social, other. The app's directory lists only published bots whose application is active, filterable by category and text search.
Automatic moderation and health
- Reports: when several distinct users who actually exchanged with your bot report it (3: alert to the team, 5: automatic return to draft and publication lock), you are notified in @gpchat_forge. An administrator then reviews lifting the lock.
- Webhook down: with no successful delivery for 24 h and at least 3 failures, you receive a warning; after 72 h and 5 failures, the bot is automatically put back to draft. Fix your server, retest the webhook, then publish again.
- Anti-flood: a bot sends at most 20 messages per minute to the same user, and a user cannot trigger more than 30 events per minute towards the same bot.
Send messages
Private message. to field = the recipient's userId, plus the fields of the chosen type.
Group message. groupId field instead of to. The bot must be a member (and an administrator if the group is set to "only admins can write").
Response — 201 Created
{
"status": "success",
"message": "Operation successful",
"data": { "msgId": "8f14e45f-ceea-4e7b-9a4c-1b2c3d4e5f60" },
"timestamp": 1735000000000
}
Keep msgId: it is used to quote this message later (replyToMsgId) and to find it again in webhooks.
All message types
Your bot's messages appear in the app exactly like a user's. All URLs must be https:// and publicly accessible: the app downloads them directly (host them on your CDN, S3, Cloudinary…).
| type | Required fields | Optional | Rendering in the app |
|---|---|---|---|
text | content (≤ 4,096) | — | Text bubble, clickable links |
image | fileUrl | caption (≤ 1,024) | Photo, full-screen view |
video | fileUrl, thumbnailUrl | caption | Thumbnail + video player |
audio | fileUrl | — | Audio player |
doc | fileUrl | caption | Downloadable document card |
gif | fileUrl | — | Animated GIF |
sticker | fileUrl (transparent PNG/WebP) | — | Sticker without bubble |
location | location.latitude, location.longitude | location.name, location.address (≤ 256) | Map with directions |
All types accept replyToMsgId. For a poll, use /v1/polls.
Text
{ "to": "USER_ID", "type": "text", "content": "Your parcel arrives tomorrow between 9 am and 12 pm 🚚" }
Image with caption
{ "to": "USER_ID", "type": "image", "fileUrl": "https://cdn.example.com/receipt-042.jpg", "caption": "Your receipt" }
Video
{
"to": "USER_ID",
"type": "video",
"fileUrl": "https://cdn.example.com/tutorial.mp4",
"thumbnailUrl": "https://cdn.example.com/tutorial.jpg",
"caption": "60-second tutorial"
}
Audio
{ "to": "USER_ID", "type": "audio", "fileUrl": "https://cdn.example.com/announcement.m4a" }
Document
{ "to": "USER_ID", "type": "doc", "fileUrl": "https://cdn.example.com/invoice-042.pdf", "caption": "Invoice #042" }
GIF and sticker
{ "to": "USER_ID", "type": "gif", "fileUrl": "https://media.giphy.com/media/l0MYt5jPR6QX5pnqM/giphy.gif" }
{ "to": "USER_ID", "type": "sticker", "fileUrl": "https://cdn.example.com/stickers/thanks.webp" }
Location
{
"to": "USER_ID",
"type": "location",
"location": { "latitude": 4.0511, "longitude": 9.7679, "name": "Akwa branch", "address": "Bd de la Liberté, Douala" }
}
Recommended formats: JPEG/PNG/WebP images (≤ 10 MB), MP4 H.264 videos (≤ 50 MB), M4A/MP3 audio, PDF documents. The API does not download your files: the user's app does it.
Replies and mentions
Quote a message (reply)
Add replyToMsgId: the quoted message appears above your reply. It must belong to the same conversation (otherwise 404). Use the msgId received in the webhook.
{ "to": "USER_ID", "type": "text", "content": "Noted, I'm on it!", "replyToMsgId": "RECEIVED_MSG_ID" }
Mention members (groups)
mentionedUserIds (50 max) — only in a group, and only members of the group.
{ "groupId": "GROUP_ID", "type": "text", "content": "@Alice your ticket is resolved ✅", "mentionedUserIds": ["USER_ID_ALICE"] }
Rules and anti-spam
To protect users, bots follow strict rules, checked server-side:
| Rule | Error |
|---|---|
| A bot can only write privately to a user who has already written to it at least once. A bot answers, it does not solicit. | 400 failed-precondition |
| No messages to a user who has blocked the bot. | 403 permission-denied |
| A bot cannot write to another bot (prevents loops). | 403 permission-denied |
| A bot can only add to a group (creation or adding members) users who have already written to it. | 403 permission-denied |
| One bot per application, 20 applications per account. | 409 / 429 |
| An unpublished (draft) bot can only write, add to a group or act towards you, your testers and your authorized groups. See Draft and publication. | 403 permission-denied |
To let your users start a conversation, publish your bot then share its username or list it in the Bot store. The user's first action (even /start) opens the conversation.
Webhooks
Configure the URL in the console (Webhooks tab). GPChat sends a JSON POST to it for every message your bot receives.
https://and public URL: private, local or internal addresses are refused, and redirects are not followed.- Reply with 2xx in under 10 seconds. Process the message asynchronously if needed.
- A new bot can take up to 5 minutes to receive its first webhooks.
- While the application is a draft, you only receive messages from yourself, your testers and your authorized groups.
Headers
| Header | Value |
|---|---|
Content-Type | application/json |
X-GPChat-Event | message.received, group_message.received, callback.received or ping |
X-GPChat-Signature | t=<unix_timestamp>,v1=<hmac_sha256_hex> — several v1= possible during a secret rotation |
Events and payload
The body always has the form { "type": "<event>", "data": { … } }.
message.received
{
"type": "message.received",
"data": {
"msgId": "8f14e45f-ceea-4e7b-9a4c-1b2c3d4e5f60",
"type": "text",
"textMsg": "/start",
"from": "USER_ID",
"chatId": "USER_ID",
"sentAt": 1735000000000
}
}
group_message.received
{
"type": "group_message.received",
"data": {
"msgId": "MSG_ID",
"type": "image",
"textMsg": "",
"fileUrl": "https://…/photo.jpg",
"caption": "Look at this",
"from": "USER_ID",
"groupId": "GROUP_ID",
"mentionedUserIds": ["BOT_USER_ID"],
"isMentioned": true,
"replyToMsgId": "QUOTED_MSG_ID",
"sentAt": 1735000000000
}
}
| Field | Description |
|---|---|
msgId | Unique message identifier. Use it to deduplicate: the same delivery may be replayed. |
type | text, image, video, audio, doc, gif, sticker, location, poll |
textMsg | Text in clear (decrypted by GPChat before sending). |
fileUrl, caption, gifUrl, videoThumbnail | Media, depending on the type. |
location | { latitude, longitude, name?, address? } |
poll | Poll (question, options). |
replyToMsgId | Message quoted by the user, if any. |
from | Sender's userId. |
chatId | Private messages: use as to to reply. |
groupId, mentionedUserIds, isMentioned | Group messages; isMentioned is true if your bot is mentioned. |
command | Present when the text is a command: { "name": "table", "args": "pl", "bot": "footdirect_bot" } (bot only for an addressed command /command@bot_name). See Bots in groups. |
sentAt | Send date (epoch ms). |
sandbox | true only for an event simulated from the console. |
Verify the signature
The signature is an HMAC-SHA256 of {timestamp}.{raw body}, computed with your application's webhook secret. Verify it before any processing, on the raw body (never on re-serialized JSON), in constant time, and reject a timestamp older than 5 minutes (replay protection).
import crypto from 'node:crypto';
export function verifyGpchatSignature(rawBody, header, secret, toleranceSec = 300) {
// During a secret rotation, the header carries several "v1=": t=…,v1=…,v1=…
const m = /^t=(\d+)((?:,v1=[0-9a-f]{64})+)$/.exec(header || '');
if (!m) return false;
if (Math.abs(Date.now() / 1000 - Number(m[1])) > toleranceSec) return false;
const expected = crypto.createHmac('sha256', secret).update(`${m[1]}.${rawBody}`).digest();
return m[2].split(',').filter(Boolean).some((part) => {
const provided = Buffer.from(part.slice(3), 'hex');
return provided.length === expected.length && crypto.timingSafeEqual(expected, provided);
});
}
import hashlib, hmac, re, time
def verify_gpchat_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
# During a secret rotation, the header carries several "v1=": t=…,v1=…,v1=…
m = re.fullmatch(r"t=(\d+)((?:,v1=[0-9a-f]{64})+)", header or "")
if not m or abs(time.time() - int(m[1])) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{m[1]}.".encode() + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, part[3:]) for part in m[2].split(",") if part)
<?php
function verifyGpchatSignature(string $rawBody, ?string $header, string $secret, int $tolerance = 300): bool {
// Several "v1=" possible during a secret rotation
if (!preg_match('/^t=(\d+)((?:,v1=[0-9a-f]{64})+)$/', $header ?? '', $m)) return false;
if (abs(time() - (int) $m[1]) > $tolerance) return false;
$expected = hash_hmac('sha256', $m[1] . '.' . $rawBody, $secret);
foreach (explode(',', $m[2]) as $part) {
if ($part !== '' && hash_equals($expected, substr($part, 3))) return true;
}
return false;
}
// $rawBody = file_get_contents('php://input');
// $header = $_SERVER['HTTP_X_GPCHAT_SIGNATURE'] ?? null;
func VerifyGpchatSignature(rawBody []byte, header, secret string) bool {
// Several "v1=" possible during a secret rotation
re := regexp.MustCompile(`^t=(\d+)((?:,v1=[0-9a-f]{64})+)$`)
m := re.FindStringSubmatch(header)
if m == nil {
return false
}
ts, _ := strconv.ParseInt(m[1], 10, 64)
if math.Abs(float64(time.Now().Unix()-ts)) > 300 {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(m[1] + "."))
mac.Write(rawBody)
expected := hex.EncodeToString(mac.Sum(nil))
for _, part := range strings.Split(m[2], ",") {
if len(part) > 3 && hmac.Equal([]byte(expected), []byte(part[3:])) {
return true
}
}
return false
}
Retries and monitoring
On failure (non-2xx code, timeout, network error), GPChat retries with exponential backoff: 30 s, 1 min, 2 min, 4 min… up to 1 h between attempts, for 8 attempts in total. Beyond that, the event is marked abandoned and your alert contacts (e-mail, Slack/Discord webhook) are notified.
Alerts to the bot's creator
Set an e-mail and/or an alert webhook (Slack, Discord…) in the console → Settings. GPChat warns you — through a @gpchat_forge message (with a notification), by e-mail and on the alert webhook — in these cases:
| Situation | Delay | What follows |
|---|---|---|
Polling bot stopped: messages are waiting and the bot no longer queried GET /v1/updates | 10 minutes | one alert, repeated at most every 6 h |
| Webhook down: no successful delivery | 24 h (≥ 3 failures) | without a fix within 72 h, the bot goes back to draft |
| Event abandoned after 8 attempts | immediate | one alert per event |
| User reports (3: alert, 5: automatic return to draft) | immediate | reviewed by an administrator |
To also monitor your own bot (error rate, rate limit, latency), expose JSON logs and metrics: the bot template ships /healthz, /readyz and /metrics (Prometheus) with ready-made alert rules.
The console's Monitoring tab shows the success rate, your server's average latency, hourly activity, quota consumption and a detailed log of the last 100 events (payload, your server's response, signature), exportable as JSON or CSV.
Bots in groups
A bot added to a group does not get the whole conversation to handle: it must answer only commands and messages that mention it. Delivery rules (same as Telegram):
| Message in the group | Bots that receive it | What your bot should do |
|---|---|---|
/help | Every bot in the group | Answer if it knows the command. |
/help@footdirect_bot | Only @footdirect_bot | Answer (the platform does not deliver it to other bots). |
@rappels_bot tomorrow 9am meeting | All; isMentioned: true for the mentioned bot | Handle the text only when isMentioned is true. |
| Ordinary message | All | Ignore. |
In the app, the “/” button in a group lists the commands of every bot member, grouped by bot; tapping one puts /command@bot_name in the message bar (the user adds parameters, then sends). Typing / also suggests commands as you type. So declare short, clear descriptions for your commands (console → Bot tab, or /setcommands with @gpchat_forge).
The event's command field gives you the command already parsed. The bot templates and the SDK (ignoreOtherBotsCommands) also ignore commands addressed to another bot when BOT_USERNAME is set.
Groups & broadcast
Actor: your bot (API key) or a user (OAuth2 token, groups:manage scope). While the application is a draft, a bot can only act in the groups you authorized (a group it creates itself is authorized automatically) and can only add you and your testers to them. The creator becomes the only administrator. A group with isBroadcast: true is a broadcast list, where only its creator writes.
| Method | Endpoint | Body | Rights |
|---|---|---|---|
| POST | /v1/groups | name (≤ 100), description? (≤ 500), members? (≤ 100), isBroadcast?, photoUrl? | Anyone |
| DELETE | /v1/groups/delete | groupId | Admin |
| POST | /v1/groups/members | groupId, memberIds (1 to 100) | Admin |
| POST | /v1/groups/members/remove | groupId, memberId | Admin, or yourself (leave) |
| PATCH | /v1/groups/members/role | groupId, memberId, isAdmin | Admin (not broadcast) |
| PATCH | /v1/groups/details | groupId + name, description, photoUrl, sendMessages, editInfoOnlyAdmin | Admin |
| POST | /v1/groups/broadcast | groupId + fields of a message | Member (creator for a broadcast) |
curl -X POST https://api.gpchat.app/v1/groups \
-H "Authorization: Bearer $GPCHAT_API_KEY" -H "Content-Type: application/json" \
-d '{"name": "Premium customers", "isBroadcast": true, "members": ["USER_ID_1", "USER_ID_2"]}'
Stories
OAuth2 token only: a story is always published on behalf of the user who gave consent.
| Method | Endpoint | Details | Scope |
|---|---|---|---|
| POST | /v1/stories | type = text (text ≤ 1,000), image (imageUrl) or video (videoUrl, thumbnailUrl?) | stories:write |
| GET | /v1/stories/mine | The user's stories | stories:read |
| DELETE | /v1/stories/delete | storyId (belonging to the user) | stories:write |
Polls
API key (bot) or OAuth2 token — polls:write scope in both cases. Target: groupId (the actor must be a member) or receiverId (private conversation). Only the poll's creator can close it.
| Method | Endpoint | Body |
|---|---|---|
| POST | /v1/polls | question (≤ 300), options (2 to 12, ≤ 100 each), allowMultipleAnswers?, isAnonymous? |
| POST | /v1/polls/vote | messageId, optionId — toggles the vote |
| POST | /v1/polls/close | messageId — creator only |
{
"groupId": "GROUP_ID",
"question": "Which slot for the meeting?",
"options": ["Monday 10 am", "Tuesday 2 pm", "Thursday 4 pm"],
"allowMultipleAnswers": true
}
Login with GPChat (OAuth2)
Let your users sign in to your service with their GPChat account, then act on their behalf (stories, polls, groups). Authorization Code flow (RFC 6749). While the application is a draft, only you and your testers can authorize it and obtain or refresh tokens; 403 permission-denied for everyone else.
Scopes
| Scope | Access |
|---|---|
profile | Name and profile picture (/oauth/userinfo) |
stories:read / stories:write | Read / publish and delete the user's stories |
polls:write | Create polls, vote, close |
groups:manage | Create and administer groups and broadcasts |
- Register your redirect URIs (console → Credentials). Exact match;
https://required (http://localhostaccepted in development). - Redirect the user to the consent page, with a random
statekept in the session:https://api.gpchat.app/oauth/authorize ?response_type=code &client_id=APP_ID &redirect_uri=https%3A%2F%2Fmyapp.com%2Fcallback &scope=profile%20stories%3Awrite &state=RANDOM_CSRF_TOKEN - Get the code: the user comes back to
redirect_uri?code=…&state=…(or?error=access_denied). Check thatstatematches. - Exchange the code from your server (single use, valid 5 minutes):
curl -X POST https://api.gpchat.app/oauth/token -H "Content-Type: application/json" -d '{ "grant_type": "authorization_code", "code": "CODE", "redirect_uri": "https://myapp.com/callback", "client_id": "APP_ID", "client_secret": "CLIENT_SECRET" }' # → { "access_token": "gpat_…", "refresh_token": "gprt_…", "token_type": "Bearer", "expires_in": 3600, "scope": "profile stories:write" } - Call the API with
Authorization: Bearer gpat_…, for exampleGET /oauth/userinfo→{ "sub", "name", "picture" }. - Refresh before expiry (1 h) with
grant_type=refresh_token. Every refresh revokes the old refresh token and issues a new one (rotation): always store the latest one received. - Sign out:
POST /oauth/revokewith{ token, client_id, client_secret }revokes the token and its whole family.
If an already-used refresh token is presented again, the request fails (401): this is a sign of possible theft. Ask for the user's consent again.
Versioning and deprecation
The API is versioned in the URL: the major version is part of the path (https://api.gpchat.app/v1/messages). The current version is v1; the documentation and the OpenAPI specification have their own number (v1.4) that increases with every addition.
What can change within a major version
In /v1 we only make backward-compatible changes: your integration should keep working without modification.
- new endpoints, new optional request fields;
- new fields in responses and events, new event or message types, new enum values;
- a rule relaxed (limit raised, field made optional).
On the client side: ignore fields and event types you do not know (do not fail on an unknown field) and do not rely on the order of JSON fields.
What counts as a breaking change
Removing or renaming an endpoint or a field, making an optional field required, changing the meaning of a field, tightening a rule incompatibly, changing the authentication format. A breaking change never ships in /v1: it ships in a new major version (/v2).
Support period: 12 months
- Announcement of a new major version in What's new and by e-mail to your applications' alert contacts (console → Settings).
- Overlap of at least 12 months: the old version stays available and maintained (security, bug fixes) for at least one year after the announcement; both versions run side by side so you migrate at your own pace.
- Signalling: during this period, responses from the old version carry the
DeprecationandSunsetheaders (end-of-service date) and the documentation publishes a migration guide. - End of service: not before the date announced in
Sunset.
Exception: a serious security flaw may require an immediate fix, announced right away. Features labeled "beta" or "experimental" in the documentation are not covered by this guarantee.
Limits and quotas
| Resource | Limit |
|---|---|
| API requests | 60 / minute by default, per API key and per endpoint (per application for OAuth2 tokens). Quota can be raised on request. |
| Applications | 20 per account (excluding deleted ones) |
| Bot | 1 per application |
| Text | 4,096 characters; caption 1,024 |
| URL | 2,048 characters, https:// |
| Mentions | 50 per message |
| Members added | 100 per request (maximum group size checked server-side) |
| Webhook | Reply expected in under 10 s; 8 attempts |
Beyond the quota: 429. Retry after a few seconds with exponential backoff (1 s, 2 s, 4 s…). Real-time consumption is visible in the console (Credentials → Quota consumption).
Errors
Every error returns an HTTP code and a uniform body:
{ "status": "error", "code": "invalid-argument", "message": "Field 'fileUrl': only https:// URLs are accepted" }
| HTTP | code | Common causes | What to do |
|---|---|---|---|
| 400 | invalid-argument | Missing or invalid field, non-https URL, unknown type | Fix the request (the message names the field) |
| 400 | failed-precondition | The user has never written to the bot; poll closed | Wait for the user to write to the bot |
| 401 | unauthenticated | Token missing, invalid, revoked or expired | Check the header; refresh the OAuth2 token |
| 403 | permission-denied | Missing scope; application disabled/suspended; bot blocked; not an administrator; unpublished application (unauthorized target) | Check rights and app status; authorize the target or publish |
| 404 | not-found | Recipient, group or quoted message not found | Check the identifiers |
| 409 | already-exists | The application already has a bot | Regenerate the key instead of recreating |
| 422 | failed-precondition | API key without a bot | Create the bot in the console |
| 429 | RATE_LIMIT_EXCEEDED / resource-exhausted | Quota exceeded; app or member limit | Exponential backoff |
| 500 | INTERNAL_ERROR | Unexpected error | Retry; if it persists, contact us with the time and the endpoint |
Disable or delete an application
Console → Settings tab → Danger zone.
| Disable | Delete | |
|---|---|---|
| Reversible | ✅ Yes ("Re-enable" button) | ❌ No |
| API keys | Refused (403), kept | Revoked |
| OAuth2 tokens | Refused (403), kept | Revoked |
| Webhooks | No more deliveries | URL and secret removed |
| Bot | Unchanged | Disabled: can no longer sign in, profile marked deleted |
| Messages already sent | Kept | Kept (remain visible to users) |
An application suspended by the GPChat team cannot be re-enabled from the console: contact infos@gpchat.app.
Security best practices
- Secrets on the server side only, in environment variables or a secrets manager, never in source code.
- Verify every webhook signature on the raw body, in constant time, with a 5-minute tolerance.
- Deduplicate by
msgId: a delivery can arrive twice. - Regenerate immediately an exposed key or secret (console → Credentials); if in doubt, disable the application.
- OAuth2: always use
state, store tokens encrypted, request the minimum scopes. - Do not trust the content of received messages: escape it before displaying it, validate it before acting on it.
- Host your media on a domain you control, over HTTPS.
FAQ
My bot does not receive webhooks.
Check (1) that the URL is registered and answers the ping, (2) that the application is active, (3) that you wait at most 5 minutes after creating the bot, (4) the Monitoring tab log to see your server's responses, (5) if the application is still a draft, that the sender is you or an authorized tester (or that the group is authorized): other people's messages are not forwarded.
My bot does not answer my friends / they cannot find it.
It is probably still a draft: only you and the testers you authorized can use it. Authorize them (Publication → Authorized users) or publish it.
I get failed-precondition when sending a message.
The user has never written to your bot. Ask them to send it a first message (for example /start).
Where do I find a user's userId?
In every webhook (from, chatId), or through /oauth/userinfo (sub) for a user signed in with Login with GPChat.
Can I test safely, given there is no staging?
Yes, directly in production: use the console's event simulator (no real user involved), then write to your bot from your own usual GPChat account. Your application is a draft until you publish it: only you and the testers you authorize can use it, other users do not see it in search and their messages are never forwarded to you — testing this way never affects other users. Publish it when it is ready (Draft and publication).
Does my text appear encrypted in webhooks?
No. Private messages are encrypted at rest, but GPChat always sends you textMsg in clear.
I develop on my laptop and have no public URL.
Use polling mode (/setmode polling in @gpchat_forge) — no server needed — or expose your local port with a tunnel (ngrok, Cloudflare Tunnel) and register the HTTPS URL it gives you as your webhook.
What's new
v1.4 — November 2026
- Bot photo: editable in the console (Bot tab), with
/setphotoin @gpchat_forge (send the image) or through the API (botPhotoUrl). See Create and manage a bot. - Versioning and deprecation: official policy, old version maintained for at least 12 months after a new major version is announced.
- Open-source bot template and a library of complete bots (Ciné Club, DevFest Guide, Dev Alerts) on GitHub.
- “Polling bot stopped” alert (10 minutes) in addition to webhook alerts: see Retries and monitoring.
- Documentation and API reference available in English (Français).
v1.3 — October 2026
- Buttons and Markdown under messages, with the
callback.receivedevent; edit / delete your messages and show "typing…". - Polling mode (
GET /v1/updates) for bots without a public server. - Secret rotation with overlap, event replay, statistics, multiple API keys.
- Categories and directory server-side; start link with a parameter.
- Automatic moderation after reports and return to draft if the webhook stays down.
v1.2 — October 2026
- Draft and publication: every new application starts as a draft (usable by you and your testers only) and you publish it yourself when it is ready. See Draft and publication. Existing applications remain published.
- Console: new Publication tab (checklist, authorized users and groups, publish / back to draft). @gpchat_forge:
/status,/addtester,/removetester,/testers,/testwebhook,/publish,/unpublish. - Security: only the server can now grant an account the bot or verified-bot status.
v1.1 — September 2026
- New message types for bots:
video,gif,sticker,location; quoted replies (replyToMsgId) and group mentions. - Webhooks: private message text sent in clear; new fields (
gifUrl,videoThumbnail,location,replyToMsgId,isMentioned,sentAt); real HTTP code and latency in monitoring. - Console: application disable and delete, redirect URI editing, operational alert contacts.
- Security: anti-spam rules for bots, SSRF protection for webhooks, strict input validation.
- New OpenAPI 3.1 interactive reference (openapi.json).
- New full tutorial: build an AI bot from A to Z in Node.js/TypeScript, from sandbox to production.