Developers
Example bot
A small JavaScript bot with no dependencies, with /ping, /dado (dice) and a webhook. Download it, fill in the token and run it.
Download the example (.zip) API reference
11 files, 11 kB, MIT license. Code comments are in Portuguese. Tested against the Zync API on every change.
What you need
- Node.js 20.6 or newer (nothing to
npm install); - a Zync server you manage;
- a public URL for the bot. Zync does not call local addresses; to test on your computer, use a tunnel, such as
cloudflared tunnel --url http://localhost:8787.
Step by step
- In Settings → Developer, use Create application and copy the token. In Show signing secret, copy the secret.
- In Add to a server, add the bot to one of your servers.
- Copy
.env.exampleto.envand fill inZYNC_BOT_TOKENandZYNC_SIGNING_SECRET. - Register the commands with
npm run registrar. - Start the bot with
npm startand set the application’s Interactions URL:https://<your-public-address>/interactions. - In the server, type
/pingor/dado 20.
Webhook
In Edit channel → Webhooks, create a webhook, put the URL in ZYNC_WEBHOOK_URL and run:
npm run webhook -- "Version 1.2 released ✅"
Adding a command
Add the command to COMMANDS in comandos.mjs, answer it in answer() ({ content } posts in the channel; with ephemeral: true, only the person who used it sees it) and run npm run registrar again.
The files
comandos.mjs: The command list and what each one replies. Start here.bot.mjs: The interactions URL server: checks the signature and replies within 3 s.registrar.mjs: Sends the command list with the bot token.webhook.mjs: Posts to the channel through the webhook URL.zync.mjs: Helpers: call the API, wait on 429 and check the signature.package.json: The npm commands: start, registrar, webhook and test..env.example: The variables the bot reads. Copy it to .env.test/bot.test.mjs: Offline tests (npm test).
comandos.mjs
// Os comandos do bot: a lista que vai para o Zync (registrar.mjs) e o que cada um responde
// (bot.mjs). Para criar um comando novo, acrescente aqui e rode `npm run registrar` de novo.
/** Lista enviada a PUT /v1/applications/:id/commands (substitui a lista inteira). */
export const COMMANDS = [
{ name: 'ping', description: 'Confere se o bot está no ar' },
{
name: 'dado',
description: 'Rola um dado',
options: [{ name: 'lados', description: 'Quantos lados (padrão 6)', required: false }],
},
];
/**
* Responde a uma interação do tipo "command". A volta é o corpo da resposta HTTP:
* { content, ephemeral } — ephemeral: true faz só quem usou ver a resposta.
*/
export function answer(interaction) {
const { name, options = {} } = interaction.command ?? {};
const who = interaction.user?.displayName ?? interaction.user?.username ?? 'você';
switch (name) {
case 'ping':
return { content: 'Pong! 🏓' };
case 'dado': {
const raw = String(options.lados ?? '6').trim();
const sides = Number(raw);
if (!Number.isInteger(sides) || sides < 2 || sides > 1000) {
return { content: `"${raw}" não serve: use um número inteiro de 2 a 1000.`, ephemeral: true };
}
const roll = 1 + Math.floor(Math.random() * sides);
return { content: `🎲 ${who} rolou um d${sides}: **${roll}**` };
}
default:
return { content: `Não conheço o comando /${name}.`, ephemeral: true };
}
}
bot.mjs
// O bot: um servidor HTTP que recebe os comandos de barra do Zync na URL de interações,
// confere a assinatura e responde em menos de 3 segundos.
//
// npm start (lê o .env; porta 8787 por padrão)
//
// A URL de interações da aplicação precisa ser pública (https, porta padrão), por exemplo
// atrás de um túnel: https://seu-tunel.example/interactions
import { createServer } from 'node:http';
import { answer } from './comandos.mjs';
import { need, verifySignature } from './zync.mjs';
const SIGNING_SECRET = need('ZYNC_SIGNING_SECRET');
const PORT = Number(process.env.PORT ?? 8787);
const MAX_BODY = 64 * 1024;
const send = (res, status, body) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
};
export const server = createServer((req, res) => {
if (req.method === 'GET' && req.url === '/health') return send(res, 200, { ok: true });
if (req.method !== 'POST' || req.url !== '/interactions') return send(res, 404, { error: 'not found' });
const chunks = [];
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > MAX_BODY) req.destroy();
else chunks.push(chunk);
});
req.on('end', () => {
// A assinatura é sobre o corpo cru: confira ANTES de fazer o JSON.parse.
const raw = Buffer.concat(chunks).toString('utf8');
if (!verifySignature(req.headers, raw, SIGNING_SECRET)) {
return send(res, 401, { error: 'assinatura inválida' });
}
let interaction;
try {
interaction = JSON.parse(raw);
} catch {
return send(res, 400, { error: 'JSON inválido' });
}
if (interaction.type !== 'command') return send(res, 400, { error: 'tipo desconhecido' });
const reply = answer(interaction);
console.log(`/${interaction.command?.name} de @${interaction.user?.username} → ${reply.content}`);
send(res, 200, reply);
});
});
server.listen(PORT, () => {
console.log(`Bot no ar em http://localhost:${PORT}/interactions`);
});
registrar.mjs
// Registra os comandos de comandos.mjs na aplicação, com o token do bot.
//
// npm run registrar
//
// Cada chamada substitui a lista inteira: comandos que saíram de comandos.mjs somem do Zync.
import { COMMANDS } from './comandos.mjs';
import { api, applicationIdFrom, need } from './zync.mjs';
const TOKEN = need('ZYNC_BOT_TOKEN');
const appId = applicationIdFrom(TOKEN);
const saved = await api(TOKEN, 'PUT', `/applications/${appId}/commands`, COMMANDS);
console.log(`Comandos registrados: ${saved.map((c) => `/${c.name}`).join(', ')}`);
webhook.mjs
// Publica uma mensagem num canal pelo webhook de entrada, sem token de bot: só a URL.
//
// npm run webhook -- "Versão 1.2 publicada ✅"
//
// A URL vem de Editar canal → Webhooks no app (aparece uma vez só) e vai em ZYNC_WEBHOOK_URL.
import { need } from './zync.mjs';
const url = need('ZYNC_WEBHOOK_URL');
const content = process.argv.slice(2).join(' ').trim() || 'Olá do webhook de exemplo! 👋';
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content }),
});
if (!res.ok) {
const error = (await res.json().catch(() => null))?.error ?? {};
console.error(`O webhook respondeu ${res.status} ${error.code ?? ''}: ${error.message ?? ''}`);
process.exit(1);
}
console.log(`Publicado: ${content}`);
zync.mjs
// Ajudantes do bot de exemplo: chamar a API do Zync com o token do bot e conferir a assinatura
// das interações. Sem dependências: só o que vem com o Node (20.6 ou mais novo).
import { createHmac, timingSafeEqual } from 'node:crypto';
/** Endereço da API. Em produção é https://usezync.com/api; para testar local, a sua API. */
export const API = (process.env.ZYNC_API ?? 'https://usezync.com/api').replace(/\/+$/, '');
/** Lê uma variável obrigatória do ambiente (ou do .env, com `node --env-file=.env`). */
export function need(name) {
const value = process.env[name]?.trim();
if (!value) {
console.error(`Falta ${name}. Copie .env.example para .env e preencha.`);
process.exit(1);
}
return value;
}
/** O ID da aplicação está dentro do token (zb.<id sem hífens>.<segredo>); volta com os hífens. */
export function applicationIdFrom(token) {
const [prefix, hex] = token.split('.');
if (prefix !== 'zb' || !/^[0-9a-f]{32}$/.test(hex ?? '')) {
throw new Error('O token não parece de bot (zb.<app-id>.<segredo>).');
}
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
/**
* Chama a API como o bot. Erros voltam como exceção com o `code` estável da API
* (ex.: RATE_LIMITED, FORBIDDEN) e, no 429, espera `retryAfterMs` e tenta mais uma vez.
*/
export async function api(token, method, path, body, retried = false) {
const res = await fetch(`${API}/v1${path}`, {
method,
headers: {
Authorization: `Bot ${token}`,
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
if (res.status === 204) return null;
const data = await res.json().catch(() => null);
if (res.ok) return data;
const error = data?.error ?? {};
if (res.status === 429 && !retried) {
await new Promise((r) => setTimeout(r, error.details?.retryAfterMs ?? 1000));
return api(token, method, path, body, true);
}
throw Object.assign(new Error(`${res.status} ${error.code ?? ''} ${error.message ?? ''}`.trim()), {
status: res.status,
code: error.code,
});
}
/**
* Confere a assinatura de uma interação: HMAC-SHA256 do segredo de assinatura sobre
* "<X-Zync-Timestamp>.<corpo cru>", e recusa timestamps com mais de 5 minutos.
*/
export function verifySignature(headers, rawBody, signingSecret, now = Date.now()) {
const ts = headers['x-zync-timestamp'];
const sig = String(headers['x-zync-signature'] ?? '');
if (!ts || !Number.isFinite(Number(ts)) || Math.abs(now - Number(ts)) > 5 * 60_000) return false;
const expected =
'sha256=' + createHmac('sha256', signingSecret).update(`${ts}.${rawBody}`).digest('hex');
return sig.length === expected.length && timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
}
package.json
{
"name": "zync-bot-exemplo",
"version": "1.0.0",
"private": true,
"description": "Bot de exemplo do Zync: comandos de barra (/ping e /dado) e webhook de entrada, sem dependências.",
"type": "module",
"license": "MIT",
"engines": {
"node": ">=20.6"
},
"scripts": {
"start": "node --env-file=.env bot.mjs",
"registrar": "node --env-file=.env registrar.mjs",
"webhook": "node --env-file=.env webhook.mjs",
"test": "node --test"
}
}
.env.example
# Copie para .env e preencha. Nunca coloque o .env no git: quem tem o token age como o bot.
# Configurações → Desenvolvedor → token da aplicação (aparece uma vez só).
ZYNC_BOT_TOKEN=zb.<app-id>.<segredo>
# Configurações → Desenvolvedor → Mostrar segredo de assinatura.
ZYNC_SIGNING_SECRET=
# Editar canal → Webhooks → URL do webhook (só para o webhook.mjs).
ZYNC_WEBHOOK_URL=
# Opcional: a porta do bot.mjs (padrão 8787) e a API (padrão https://usezync.com/api).
# PORT=8787
# ZYNC_API=https://usezync.com/api
test/bot.test.mjs
// Testes sem rede: as respostas dos comandos e a conferência da assinatura (npm test).
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { test } from 'node:test';
import { COMMANDS, answer } from '../comandos.mjs';
import { applicationIdFrom, verifySignature } from '../zync.mjs';
const cmd = (name, options = {}) => ({ type: 'command', command: { name, options }, user: { displayName: 'Rafa' } });
test('comandos: nomes válidos para o Zync e com descrição', () => {
assert.ok(COMMANDS.length <= 25);
for (const c of COMMANDS) {
assert.match(c.name, /^[a-z0-9_-]{1,32}$/);
assert.ok(c.description);
for (const o of c.options ?? []) assert.ok(o.description, `${c.name}.${o.name}`);
}
});
test('/ping e /dado', () => {
assert.deepEqual(answer(cmd('ping')), { content: 'Pong! 🏓' });
for (let i = 0; i < 50; i++) {
const n = Number(/\*\*(\d+)\*\*/.exec(answer(cmd('dado', { lados: '20' })).content)[1]);
assert.ok(n >= 1 && n <= 20);
}
assert.match(answer(cmd('dado')).content, /rolou um d6/);
assert.equal(answer(cmd('dado', { lados: 'muitos' })).ephemeral, true);
assert.equal(answer(cmd('nao-existe')).ephemeral, true);
});
test('assinatura: aceita a certa, recusa a errada e a velha', () => {
const secret = 'a'.repeat(64);
const body = '{"type":"command"}';
const now = 1_794_012_351_192;
const sign = (ts) => 'sha256=' + createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex');
const h = (ts, sig = sign(ts)) => ({ 'x-zync-timestamp': String(ts), 'x-zync-signature': sig });
assert.equal(verifySignature(h(now), body, secret, now), true);
assert.equal(verifySignature(h(now), body + ' ', secret, now), false);
assert.equal(verifySignature(h(now, 'sha256=00'), body, secret, now), false);
assert.equal(verifySignature(h(now - 6 * 60_000), body, secret, now), false);
assert.equal(verifySignature({}, body, secret, now), false);
});
test('o ID da aplicação sai do token', () => {
assert.equal(applicationIdFrom('zb.01a1b5cb87e0703a8db1803ee8d509d2.segredo'), '01a1b5cb-87e0-703a-8db1-803ee8d509d2');
assert.throws(() => applicationIdFrom('Bearer abc'));
});