Build your room
Discord integration
Webhook notices, two-way chat with a bot, and security best practices.
Connecting your room to your community's Discord brings people back: match notices, results, the room link and even talking to whoever is playing. The discord.ts file in the example project shows both ways.
| Way | Does | Needs |
|---|---|---|
| Webhook | Only sends messages (results, "room is live") | A webhook URL |
| Bot | Sends and receives: room ↔ channel chat, commands | A bot in the Discord Developer Portal |
Way 1: webhook (5 minutes)
- In Discord: Channel settings → Integrations → Webhooks → New webhook.
- Copy the URL and put it in
.env:DISCORD_WEBHOOK=https://discord.com/api/webhooks/... - Done. The example room announces the result of each match.
ts
export async function avisarWebhook(url: string, texto: string): Promise<void> {
await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ content: texto.slice(0, 2000), allowed_mentions: { parse: [] } }),
});
}Way 2: bot with two-way chat
Creating the bot
- Go to discord.com/developers/applications → New Application.
- Bot tab → Reset Token and copy the token to
DISCORD_TOKENin.env. - Still on the Bot tab, enable Message Content Intent (without it the bot can't read message text).
- OAuth2 → URL Generator tab: check
botand the View Channels, Send Messages and Read Message History permissions. Open the generated URL and add the bot to your server. - In Discord, enable Developer Mode (Settings → Advanced), right-click the channel → Copy ID and put it in
DISCORD_CANAL.
What the example does
- Every message in the room chat goes to the channel:
**Ana**: gg - Every message in the channel goes to the room:
[discord] Bruno: good game - Each match result and the room link (when it starts) go to the channel.
The piece that connects both ends, in sala.ts:
ts
this.discord = await PonteDiscord.conectar(token, canal);
this.discord.aoReceber = (autor, texto) => falar(this.room, `[discord] ${autor}: ${texto}`);
this.discord.enviar(`sala no ar: ${this.room.shareLink}`);(PonteDiscord = Discord bridge, aoReceber = on receive, enviar = send.)
The full code
ts
// discord.ts
import { Client, Events, GatewayIntentBits, type SendableChannels } from 'discord.js';
/** Simplest way: just POST notices to Discord (no bot). Create the webhook in Channel > Edit > Integrations. */
export async function avisarWebhook(url: string, texto: string): Promise<void> {
await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
// empty allowed_mentions: nobody can ping @everyone by typing it as their in-game name
body: JSON.stringify({ content: texto.slice(0, 2000), allowed_mentions: { parse: [] } }),
}).catch((err) => console.error('[discord] webhook falhou', err));
}
/** A real bot: two-way chat (room <-> channel) and commands. */
export class PonteDiscord {
private canal: SendableChannels | null = null;
/** Messages arriving from the Discord channel (the bot ignores its own and other bots'). */
aoReceber: (autor: string, texto: string) => void = () => {};
private constructor(private readonly client: Client) {}
static async conectar(token: string, canalId: string): Promise<PonteDiscord> {
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent],
});
const ponte = new PonteDiscord(client);
client.on(Events.MessageCreate, (msg) => {
if (msg.channelId !== canalId || msg.author.bot || !msg.content) return;
ponte.aoReceber(msg.member?.displayName ?? msg.author.username, msg.content);
});
await client.login(token);
const canal = await client.channels.fetch(canalId);
if (!canal?.isSendable()) throw new Error('canal do Discord não encontrado ou sem permissão de enviar');
ponte.canal = canal;
return ponte;
}
enviar(texto: string): void {
this.canal?.send({ content: texto.slice(0, 2000), allowedMentions: { parse: [] } }).catch((err) => console.error('[discord]', err));
}
destroy(): void {
void this.client.destroy();
}
}
/** Strips Discord formatting from game text (a "**admin**" name doesn't turn bold, `@` doesn't become a mention). */
export const limpar = (t: string) => t.replace(/[\*_~`|>@#]/g, (c) => `\${c}`);Security and common sense
- Escape what comes from the game. Player names and messages can contain
**,`,@... Thelimpar()("clean") function puts a\before those characters so nothing turns into formatting or a mention. - Ignore bots in the channel (including yours), or messages echo forever.
- Limit the size. Discord accepts up to 2000 characters per message; bonk chat, around 95 per line.
- One-way bridge for moderation. If the channel is public, consider sending only room → Discord and leaving the Discord → room direction to a staff role.
Going further
| Idea | How |
|---|---|
/sala command that replies with the link and who is playing | discord.js slash commands (SlashCommandBuilder) reading room.state.players |
| Role for people who play a lot | Link the bonk account to Discord with a 6-digit code the bot sends privately and the player types in the room (!vincular 123456) |
| Replays on Discord | Send the .bkrp as an attachment (files: [{ attachment: path }]) at the end of each match |
| Several processes (room and bot separate) | The room opens a small local HTTP API (only 127.0.0.1, with a token) with /status and an event stream; the Discord bot consumes it. That is how the BonkTools rooms worked: one bot for several rooms |