Build your room
Your room, step by step
Download the example project, understand how it is organized and launch your football room in minutes.
In this track you build a complete football room, the way the BonkTools rooms worked: pick with captains, automatic scoring, commands and admins, match recording, Discord and even a "challenge the AI" mode. All built only with the bonktools library.
Each page in this tab explains one part. This one shows the skeleton and how the parts talk to each other.
1. Download the project
Download sala-exemplo.zip and unzip it. You will need Node.js 20.18 or newer (nodejs.org).
cd sala-exemplo
npm install
cp .env.example .env # on Windows: copy .env.example .env
npm run devIn a few seconds the terminal shows:
sala no ar: https://bonk.io/123456abcde("sala no ar" = "room is live".) Open the link in the browser and join. Done: you are in your room.
2. How the project is organized
sala-exemplo/
├── .env secrets and settings (keep it out of git!)
├── src/
│ ├── index.ts starts the room and recreates it if it drops
│ ├── config.ts name, password, team size, goals, admins
│ ├── sala.ts wires everything: welcome, chat, score, pick, rec, Discord
│ ├── pick.ts pick system
│ ├── comandos.ts chat commands and admins
│ ├── chat.ts splits long messages (bonk chat cuts at ~95 characters)
│ ├── rec.ts records every match to replays/*.bkrp
│ ├── discord.ts Discord webhook and bot
│ └── ia/ the AI (see the "Artificial Intelligence" tab)
└── replays/ the recorded matchesThe idea is simple: each file takes care of one thing, and sala.ts ("room") connects them all to the room's events. Want to change the pick? Touch only pick.ts. Want a new command? Only comandos.ts or sala.ts.
3. The configuration
Everything that changes from one room to another lives in config.ts, read from .env:
// config.ts
// Everything that changes from one room to another lives here (and the secrets, in .env).
export const config = {
sala: {
nome: process.env.SALA_NOME ?? 'My Room | Pick 2v2',
senha: process.env.SALA_SENHA ?? '',
maxJogadores: 8,
oculta: process.env.SALA_OCULTA === '1',
},
/** Players per team: 1 = 1v1, 2 = 2v2, 3 = 3v3. */
tamanhoTime: Number(process.env.TAMANHO_TIME ?? 2),
/** Goals to win. */
gols: Number(process.env.GOLS ?? 3),
/** bonk.io names with access to the admin commands. */
admins: (process.env.ADMINS ?? '').split(',').map((n) => n.trim().toLowerCase()).filter(Boolean),
};Variable in .env | What it changes |
|---|---|
SALA_NOME, SALA_SENHA | Room name and password |
SALA_OCULTA=1 | Hides the room from the public list (good for testing) |
TAMANHO_TIME | Team size: 1 = 1v1, 2 = 2v2, 3 = 3v3 |
GOLS | Goals to win the match |
ADMINS | Names of the accounts allowed to use !kick, !ban... |
4. Starting the room and keeping it alive: index.ts
// index.ts
import 'dotenv/config';
import { BonkSession } from 'bonktools';
import { config } from './config.js';
import { SalaIA } from './ia/sala-ia.js';
import { MinhaSala } from './sala.js';
const session = new BonkSession({
auth: process.env.BONK_USERNAME
? { type: 'registered', username: process.env.BONK_USERNAME, password: process.env.BONK_PASSWORD ?? '' }
: { type: 'guest', guestName: 'MinhaSalaBot' },
});
// BonkSession recreates the room on its own if it drops. Each new room is a new BonkRoom object:
// that's why the logic is set up on 'room-added' (and torn down when the room goes away).
const salas = new Map<string, { destroy(): void }>();
session.on('room-added', (localId) => {
const entry = session.rooms.get(localId);
if (!entry) return;
for (const [id, sala] of salas) if (!session.rooms.has(id)) { sala.destroy(); salas.delete(id); }
console.log('sala no ar:', entry.room.shareLink);
// MODO=ia: "challenge the AI" room; otherwise, the pick room
salas.set(localId, process.env.MODO === 'ia' ? new SalaIA(entry.room, process.env.IA_MODELO) : new MinhaSala(entry.room));
});
session.on('room-removed', (localId) => { salas.get(localId)?.destroy(); salas.delete(localId); });
session.on('room-dead-terminal', ({ reason }) => console.error('a sala morreu de vez:', reason));
await session.startFromConfig({
rooms: [{
id: 'minha-sala',
name: config.sala.nome,
password: config.sala.senha,
maxPlayers: config.sala.maxJogadores,
mode: 'f', // football
rounds: config.gols,
hidden: config.sala.oculta,
}],
// interval between room creations (matters with several rooms on the same account)
throttle: { maxConcurrentRooms: 1, roomCreationDelayMs: 3_000, roomCreationJitterMs: 2_000 },
});
// Ctrl+C / systemd stop: closes the room politely.
for (const sig of ['SIGINT', 'SIGTERM'] as const) process.on(sig, () => void session.destroy().then(() => process.exit(0)));Three important ideas here:
BonkSessioninstead ofcreateRoom. The session recreates the room by itself if it drops (internet, bonk server restarting). See 24/7 sessions and reconnection.- The logic is created on
room-added. When the room is recreated, it is a newBonkRoomobject. That is why we create a newMinhaSalaon everyroom-addedand destroy the old one; otherwise the old room's timers keep running forever. - Shut down politely. On
Ctrl+C(or when the server stops the process),session.destroy()closes the room properly.
5. Wiring the pieces: sala.ts
// sala.ts
import { ScoreTracker, TEAM_BLUE, TEAM_RED, type BonkRoom } from 'bonktools';
import { falar } from './chat.js';
import { Comandos, acharJogador, ehAdmin } from './comandos.js';
import { config } from './config.js';
import { PonteDiscord, avisarWebhook, limpar } from './discord.js';
import { Pick } from './pick.js';
import { Gravador } from './rec.js';
const NOME_TIME: Record<number, string> = { [TEAM_BLUE]: 'azul', [TEAM_RED]: 'vermelho' };
/** Everything the room does, built on top of a BonkRoom. A new object for every (re)created room. */
export class MinhaSala {
private readonly tracker: ScoreTracker;
private readonly pick: Pick;
private readonly gravador: Gravador;
private readonly comandos = new Comandos();
private discord: PonteDiscord | null = null;
private fimTimer: NodeJS.Timeout | null = null;
constructor(private readonly room: BonkRoom) {
// Auto-score: simulates the game physics and reports goals and the winner (football only).
this.tracker = new ScoreTracker(room, { cacheDir: '.cache/bonk-client' });
this.pick = new Pick(room, config.tamanhoTime, async (escalacao) => {
const is = await this.tracker.buildInitialState(escalacao); // the right initial state for these players
if (!is) return false;
room.startGame({ is });
return true;
});
this.gravador = new Gravador(room, this.tracker);
this.registrarComandos();
room.enableAntiAfk(); // 12 s without moving or chatting = AFK
room.on('player-join', (p) => {
falar(room, `bem-vindo, ${p.userName}! digite !ajuda para ver os comandos`);
this.pick.entrou(p.id);
});
room.on('player-leave', (p) => this.pick.saiu(p.id));
room.on('player-afk', (id) => this.pick.parado(id));
room.on('chat-message', (m) => this.chat(m.id, m.message));
this.tracker.on('score', ({ team, scores }) => falar(room, `GOL do ${NOME_TIME[team]}! azul ${scores[TEAM_BLUE]} x ${scores[TEAM_RED]} vermelho`));
this.tracker.on('match-winner', ({ team, scores }) => {
const texto = `o time ${NOME_TIME[team]} venceu! (${scores[TEAM_BLUE]} x ${scores[TEAM_RED]})`;
falar(room, texto);
this.discord?.enviar(`🏆 ${texto}`);
if (process.env.DISCORD_WEBHOOK) void avisarWebhook(process.env.DISCORD_WEBHOOK, `🏆 ${texto}`);
// waits for the game's victory screen (4 s) and rotates
this.fimTimer = setTimeout(() => this.pick.fimDePartida(team), 4_000);
});
this.tracker.on('error', (e) => console.error('[placar] desligado:', e.message));
void this.tracker.start();
if (process.env.DISCORD_TOKEN && process.env.DISCORD_CANAL) void this.ligarDiscord(process.env.DISCORD_TOKEN, process.env.DISCORD_CANAL);
}
private chat(id: number, texto: string): void {
if (id === this.room.state.myId) return;
const nome = this.room.state.players.get(id)?.userName ?? '?';
this.discord?.enviar(`**${limpar(nome)}**: ${limpar(texto)}`);
if (this.pick.mensagem(id, texto)) return; // captain picking
this.comandos.tratar(this.room, id, texto, (r) => falar(this.room, r));
}
private registrarComandos(): void {
const room = this.room;
this.comandos
.registrar('ajuda', { ajuda: 'lista os comandos', executar: (c) => c.responder(this.comandos.ajuda(ehAdmin(room, c.id))) })
.registrar('afk', { ajuda: 'entra/sai do AFK', executar: (c) => c.responder(this.pick.alternarAfk(c.id)) })
.registrar('discord', { ajuda: 'link do Discord', executar: (c) => c.responder('entre no nosso Discord: discord.gg/SEU-CONVITE') })
.registrar('kick', {
ajuda: 'expulsa: !kick nome', soAdmin: true,
executar: (c) => {
const alvo = acharJogador(room, c.args[0] ?? '');
if (alvo === null) return c.responder('jogador não encontrado');
room.kickPlayer(alvo);
},
})
.registrar('ban', {
ajuda: 'bane: !ban nome', soAdmin: true,
executar: (c) => {
const alvo = acharJogador(room, c.args[0] ?? '');
if (alvo === null) return c.responder('jogador não encontrado');
room.banPlayer(alvo);
},
});
}
private async ligarDiscord(token: string, canal: string): Promise<void> {
try {
this.discord = await PonteDiscord.conectar(token, canal);
// from Discord to the room, with the author's name
this.discord.aoReceber = (autor, texto) => falar(this.room, `[discord] ${autor}: ${texto}`);
this.discord.enviar(`sala no ar: ${this.room.shareLink}`);
} catch (err) {
console.error('[discord] não conectou:', err);
}
}
destroy(): void {
if (this.fimTimer) clearTimeout(this.fimTimer);
this.pick.destroy();
this.gravador.destroy();
this.tracker.stop(); // shuts down this room's simulation (worker)
this.discord?.destroy();
}
}Notice the pattern: sala.ts listens to the events (player-join, chat-message, score...) and hands them over to whoever is in charge of each subject. It doesn't know how the pick works; it only tells the pick that someone joined.
The flow of a match looks like this:
player joins ─► pick.entrou() ─► builds the teams ─► tracker.buildInitialState() ─► room.startGame()
│
ScoreTracker simulates the physics ─► 'score' (goal) ─► chat │
└► 'match-winner' ─► waits 4 s ─► pick.fimDePartida() ◄┘
└► rotation and next match6. Testing alone
You don't need friends to test the basics:
- Open the room in two browser tabs (a normal one and an incognito one; each joins as a player).
- Use
SALA_OCULTA=1while testing, so nobody lands in your room in the middle of a test. - The automatic score downloads the game files the first time (
.cache/folder); the first match may take a few extra seconds.
Next steps
- Pick system: how
pick.tsbuilds equal teams and lets the captain choose. - Commands, admins and moderation: create your own commands.
- Recording matches (rec): replays that open on our website.
- Discord integration and Keeping the room online 24/7.