Sensever bots: your first bot in 15 minutes
In this guide, you create a bot that replies to messages and shows buttons and a command menu, and then you switch it from polling to a webhook. Examples are in curl, JavaScript (Node.js 18 or later, no third-party packages) and Python 3 (only the requests package is needed).
You need a Sensever account with a verified email or phone. You don't need a public server for the first steps: the bot fetches updates itself.
Step 1. Create a bot
In Sensever, open Chats, click "Create" and choose "Bot".
Enter a name, for example "Shop Assistant", and the base of the username, for example
shop. The_botending is added automatically, givingshop_bot. You can see right below the field whether the address is available.Leave the "Webhook URL" field empty.
Click "Create bot" and save the token (
b1.…) and the Webhook secret. They are shown only once.
The token gives full access to the bot. Keep it on the server, in an environment variable or a secrets manager, and never put it in page or app code. If the token leaks, issue a new one: the "Actions" → "New token" menu; the old one stops working immediately.
In the examples below, the token is read from an environment variable:
export SENSEVER_BOT_TOKEN='b1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'Step 2. Check the token
curl -s https://api.sensever.com/v1/chat/bot/me \
-H "Authorization: Bearer $SENSEVER_BOT_TOKEN"{"id":"812","username":"shop_bot","name":"Shop Assistant","delivery":"polling"}id is the bot's numeric identifier, passed as a string. delivery: "polling" means no webhook is set and the bot fetches updates itself.
Step 3. Message the bot
Find @shop_bot in Sensever search or open https://sensever.com/@shop_bot and click "Open". An empty chat has a "Start" button: it sends the bot the /start command. Also send a regular message, for example "Hello".
Step 4. Get updates
curl -s "https://api.sensever.com/v1/chat/bot/updates?timeout=25" \
-H "Authorization: Bearer $SENSEVER_BOT_TOKEN"The response is a list of updates in ascending update_id order:
{
"updates": [
{
"version": 2,
"update_id": "1",
"type": "message",
"occurred_at": "2026-09-24T18:00:00+00:00",
"bot_id": "812",
"tenant_id": null,
"thread_id": "901",
"seq": "1",
"message": {
"thread_id": "901",
"seq": "1",
"kind": "text",
"text": "/start",
"sender": {"kind": "user", "ref": "p.1104", "display_name": "Anna", "avatar_url": null},
"payload": {},
"reply_to_seq": null,
"created_at": "2026-09-24T18:00:00.000000Z"
}
}
]
}Only the main fields are shown; the full message object is described in "Bot API: messages and files". A conversation is identified by the thread_id field, and a message within it by the seq field.
To acknowledge updates, pass offset in the next request — the number of the last update plus one. Updates with lower numbers are never returned again:
curl -s "https://api.sensever.com/v1/chat/bot/updates?timeout=25&offset=2" \
-H "Authorization: Bearer $SENSEVER_BOT_TOKEN"If the bot crashes before acknowledging an update, the update arrives again. Unread updates are kept for 24 hours.
Step 5. Reply
curl -s https://api.sensever.com/v1/chat/threads/901/messages \
-H "Authorization: Bearer $SENSEVER_BOT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"client_message_id":"6f1c2a52-8a7e-4f7e-9d5e-2b1f0c3d4e5f","kind":"text","text":"Hi! I am an **echo bot**.","payload":{},"send_as":"self"}'client_message_idis a UUID you create for each new message. Repeating the request with the same UUID won't create a second message: the API returns the already sent one with"replayed": true. So after a network error, retry the request with the same UUID.kind: "text", text with formatting:**bold**,*italic*,`code`,[link](https://…)and more.payloadis required; for plain text it is an empty object.send_as: "self"— the bot writes on its own behalf; other values are forbidden for bots.
The response is 201 Created with the sent message in the data field.
Step 6. The complete echo bot
The program below fetches updates, replies to /start with a greeting and buttons, repeats any other text and answers button taps. The reply identifier is derived from update_id: if an update arrives again, repeating the reply doesn't create a duplicate.
Python
import hashlib
import os
import time
import uuid
import requests
API = os.environ.get("SENSEVER_API", "https://api.sensever.com/v1/chat")
http = requests.Session()
http.headers["Authorization"] = "Bearer " + os.environ["SENSEVER_BOT_TOKEN"]
def call(method, path, body=None, tenant_id=None):
headers = {"X-Tenant-ID": tenant_id} if tenant_id else {}
r = http.request(method, API + path, json=body, headers=headers, timeout=35)
busy = r.status_code == 409 and r.json()["error"]["code"] == "polling_conflict"
if r.status_code in (429, 503) or busy:
time.sleep(int(r.headers.get("Retry-After", "5")))
return call(method, path, body, tenant_id)
r.raise_for_status()
return r.json() if r.content else None
def reply(update, text, payload=None):
# The same reply to the same update: a retry won't create a duplicate.
key = hashlib.sha256(("reply:" + update["update_id"]).encode()).hexdigest()
return call("POST", "/threads/%s/messages" % update["thread_id"], {
"client_message_id": str(uuid.UUID(key[:32])),
"kind": "text", "text": text, "payload": payload or {},
"reply_to_seq": update["seq"], "send_as": "self",
}, update.get("tenant_id"))
BUTTONS = {"buttons": [[{"text": "Yes", "callback_data": "yes"},
{"text": "No", "callback_data": "no"}],
[{"text": "Website", "url": "https://sensever.com"}]]}
def handle(update):
if update["type"] == "message" and update["message"]["kind"] == "text":
text = update["message"]["text"]
if text.startswith("/start"):
reply(update, "Hi! I am an **echo bot**. Do you like it?", BUTTONS)
else:
reply(update, text)
elif update["type"] == "callback_query":
query = update["callback_query"]
call("POST", "/bot/callbacks/%s/answer" % query["id"],
{"text": "Thank you!" if query["data"] == "yes" else "Too bad"})
offset = None
while True:
params = "?timeout=25" + ("&offset=" + offset if offset else "")
for update in call("GET", "/bot/updates" + params)["updates"]:
handle(update)
offset = str(int(update["update_id"]) + 1)JavaScript
import { createHash } from "node:crypto";
const API = process.env.SENSEVER_API ?? "https://api.sensever.com/v1/chat";
const TOKEN = process.env.SENSEVER_BOT_TOKEN;
async function call(method, path, body, tenantId) {
const headers = { Authorization: `Bearer ${TOKEN}` };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (tenantId) headers["X-Tenant-ID"] = tenantId;
const res = await fetch(API + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
const text = await res.text();
const busy = res.status === 409 && text.includes('"polling_conflict"');
if (res.status === 429 || res.status === 503 || busy) {
await new Promise((r) => setTimeout(r, 1000 * Number(res.headers.get("Retry-After") ?? 5)));
return call(method, path, body, tenantId);
}
if (!res.ok) throw new Error(`${res.status} ${text}`);
return text ? JSON.parse(text) : null;
}
// The same reply to the same update: a retry won't create a duplicate.
function uuidFrom(text) {
const h = createHash("sha256").update(text).digest("hex");
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
}
function reply(update, text, payload = {}) {
return call("POST", `/threads/${update.thread_id}/messages`, {
client_message_id: uuidFrom(`reply:${update.update_id}`),
kind: "text", text, payload, reply_to_seq: update.seq, send_as: "self",
}, update.tenant_id);
}
const BUTTONS = { buttons: [
[{ text: "Yes", callback_data: "yes" }, { text: "No", callback_data: "no" }],
[{ text: "Website", url: "https://sensever.com" }],
] };
async function handle(update) {
if (update.type === "message" && update.message.kind === "text") {
const text = update.message.text;
if (text.startsWith("/start")) await reply(update, "Hi! I am an **echo bot**. Do you like it?", BUTTONS);
else await reply(update, text);
} else if (update.type === "callback_query") {
const query = update.callback_query;
await call("POST", `/bot/callbacks/${query.id}/answer`, { text: query.data === "yes" ? "Thank you!" : "Too bad" });
}
}
let offset = null;
for (;;) {
const { updates } = await call("GET", `/bot/updates?timeout=25${offset ? `&offset=${offset}` : ""}`);
for (const update of updates) {
await handle(update);
offset = (BigInt(update.update_id) + 1n).toString();
}
}Save the code as bot.mjs and run node bot.mjs (or python3 bot.py). Message the bot: it repeats your text, and on "Start" it replies with a message with buttons. Tap "Yes" — a short "Thank you!" notification appears.
The call function retries the request after 429 and 503, and also after 409 polling_conflict: getUpdates returns this while a request from a previous copy of the bot is still running, for example right after a restart. Run only one copy of the bot per token.
Numeric identifiers (update_id, thread_id, seq) arrive as strings: they can exceed the precision of JavaScript numbers. Do arithmetic on them with BigInt or store them as strings.
Step 7. Add a command menu
A person sees the commands when they type "/" in the input field. You set them once, not on every start:
curl -s -X PUT https://api.sensever.com/v1/chat/bot/commands \
-H "Authorization: Bearer $SENSEVER_BOT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"commands":[{"command":"start","description":"Start over"},{"command":"help","description":"What I can do"}]}'The response is 204 No Content. Commands in the bot's message text (/help) become buttons that send the command.
While you're at it, set a description: it is shown in an empty chat above the "Start" button.
curl -s -X PUT https://api.sensever.com/v1/chat/bot/profile \
-H "Authorization: Bearer $SENSEVER_BOT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"description":"I repeat your messages and show buttons.","short_description":"Sample echo bot"}'Step 8. Switch the bot to a webhook
With a webhook, Sensever sends each update to your address itself, so you don't need to keep polling. URL requirements: https://, a domain name (not an IP), port 443, a valid certificate, no redirects. Typically the bot server listens on a local port behind nginx or another TLS proxy.
Set the URL:
curl -s -X PUT https://api.sensever.com/v1/chat/bot/webhook \
-H "Authorization: Bearer $SENSEVER_BOT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"url":"https://bot.example.com/sensever"}'The response is the webhook state. While a URL is set, getUpdates returns 409 webhook_active. To go back to polling, call DELETE /v1/chat/bot/webhook.
Every Sensever request is signed with the webhook secret. Verify the signature over the raw body bytes, before parsing JSON, and respond with 200 right away: the next update waits until you respond, and you have 5 seconds to do so. Do long-running work after responding.
Python
import hashlib
import hmac
import json
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["SENSEVER_WEBHOOK_SECRET"].encode()
seen = set() # In production, a table with a unique key (bot_id, update_id).
def valid(raw, timestamp, update_id, signature):
expected = "v1=" + hmac.new(SECRET, ("%s.%s." % (timestamp, update_id)).encode() + raw,
hashlib.sha256).hexdigest()
fresh = timestamp.isdigit() and abs(time.time() - int(timestamp)) < 300
return fresh and hmac.compare_digest(expected, signature)
class Webhook(BaseHTTPRequestHandler):
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length", "0")))
update_id = self.headers.get("X-Sensever-Event-Id", "")
if not valid(raw, self.headers.get("X-Sensever-Timestamp", ""), update_id,
self.headers.get("X-Sensever-Signature", "")):
self.send_response(401)
self.end_headers()
return
update = json.loads(raw)
self.send_response(200)
self.end_headers()
if update["update_id"] == update_id and update_id not in seen:
seen.add(update_id)
threading.Thread(target=handle, args=(update,)).start()
def handle(update):
print(update["type"], update.get("message", {}).get("text")) # Put handle() from step 6 here.
HTTPServer(("127.0.0.1", 8080), Webhook).serve_forever()JavaScript
import { createServer } from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";
const SECRET = process.env.SENSEVER_WEBHOOK_SECRET;
const seen = new Set(); // In production, a table with a unique key (bot_id, update_id).
function valid(raw, timestamp, updateId, signature) {
const expected = Buffer.from("v1=" + createHmac("sha256", SECRET)
.update(`${timestamp}.${updateId}.`).update(raw).digest("hex"));
const given = Buffer.from(String(signature ?? ""));
const fresh = /^\d+$/.test(timestamp ?? "") && Math.abs(Date.now() / 1000 - Number(timestamp)) < 300;
return fresh && given.length === expected.length && timingSafeEqual(given, expected);
}
async function handle(update) {
console.log(update.type, update.message?.text); // Put handle() from step 6 here.
}
createServer((req, res) => {
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
const raw = Buffer.concat(chunks);
const updateId = req.headers["x-sensever-event-id"];
if (!valid(raw, req.headers["x-sensever-timestamp"], updateId, req.headers["x-sensever-signature"])) {
res.writeHead(401).end();
return;
}
const update = JSON.parse(raw);
res.writeHead(200).end();
if (update.update_id === updateId && !seen.has(updateId)) {
seen.add(updateId);
handle(update).catch(console.error);
}
});
}).listen(8080, "127.0.0.1");Check delivery: the "Actions" → "Test delivery" menu queues an update with type: "test". The result appears in the "Delivery log" and in GET /v1/chat/bot/webhook (last_success_date, last_error_message). Opening the webhook URL in a browser is pointless: the browser sends GET, while Sensever sends a signed POST.
Step 9. Invite people to the bot
The link https://sensever.com/@shop_bot opens the bot's page. The start parameter passes a tag to the bot, for example the traffic source:
https://sensever.com/@shop_bot?start=promo_42The "Open" button on the page leads to the chat, where "Start" sends /start promo_42. The parameter is up to 64 characters of Latin letters, digits, _ and -.
What's next
"Bot API: receiving updates" — all update types, webhooks and delivery retries.
"Bot API: buttons, keyboards and commands" — the keyboard under the input field, phone number requests, menus per language.
"Bot API: groups, channels and project requests" — how a bot works with several people and answers website visitors.
Komentar