Files
data
.gitignore
bot.js
package.json
README.md
Code
5 307
bot.js
'use strict';
require('dotenv').config();
const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const path = require('node:path');
const express = require('express');
const {
ChannelType,
Client,
EmbedBuilder,
GatewayIntentBits,
PermissionFlagsBits,
SlashCommandBuilder
} = require('discord.js');
const DISCORD_TOKEN = process.env.DISCORD_TOKEN;
const INTEGRATION_SECRET = process.env.INTEGRATION_SECRET;
const CHANNEL_CONFIG_PATH = path.join(__dirname, 'data', 'channel.json');
const PURPLE = 0x8B5CF6;
if (!DISCORD_TOKEN || !INTEGRATION_SECRET) {
console.error('Set DISCORD_TOKEN and INTEGRATION_SECRET in your .env file.');
process.exit(1);
}
let configuredChannelId = null;
const client = new Client({
intents: [GatewayIntentBits.Guilds]
});
const commands = [
new SlashCommandBuilder()
.setName('setchannel')
.setDescription('Choose where duel result notifications are posted.')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
.addChannelOption(option => option
.setName('channel')
.setDescription('Text channel for duel notifications')
.addChannelTypes(ChannelType.GuildText)
.setRequired(true)),
new SlashCommandBuilder()
.setName('testwin')
.setDescription('Post a clearly labeled test winner embed.')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
].map(command => command.toJSON());
async function loadChannelConfig() {
await fs.mkdir(path.dirname(CHANNEL_CONFIG_PATH), { recursive: true });
try {
const saved = JSON.parse(await fs.readFile(CHANNEL_CONFIG_PATH, 'utf8'));
configuredChannelId = typeof saved.channelId === 'string' ? saved.channelId : null;
} catch (error) {
if (error.code !== 'ENOENT') throw error;
await saveChannelConfig(null);
}
}
async function saveChannelConfig(channelId) {
configuredChannelId = channelId;
await fs.writeFile(CHANNEL_CONFIG_PATH, `${JSON.stringify({ channelId }, null, 2)}\n`);
}
function createResultEmbed({ winnerUsername, brainrotName, brainrotValue, timestamp }, testMode = false) {
const date = new Date(timestamp);
const embed = new EmbedBuilder()
.setColor(PURPLE)
.setTitle('🏆 Duel Victory')
.addFields(
{ name: 'Winner', value: winnerUsername, inline: true },
{ name: 'Brainrot', value: brainrotName, inline: true },
{ name: 'Brainrot Value', value: String(brainrotValue), inline: true },
{ name: 'Timestamp', value: `<t:${Math.floor(date.getTime() / 1000)}:F> · <t:${Math.floor(date.getTime() / 1000)}:R>` }
)
.setTimestamp(date);
if (testMode) {
embed.setDescription('🧪 **TEST MODE** — preview only; this is not a real duel result.');
}
return embed;
}
async function getNotificationChannel() {
if (!configuredChannelId) return null;
const channel = await client.channels.fetch(configuredChannelId);
if (!channel || !channel.isTextBased() || typeof channel.send !== 'function') return null;
return channel;
}
function isAuthorizedRequest(request) {
const authorization = request.get('authorization') || '';
const match = /^Bearer (.+)$/.exec(authorization);
if (!match) return false;
const supplied = Buffer.from(match[1]);
const expected = Buffer.from(INTEGRATION_SECRET);
return supplied.length === expected.length && crypto.timingSafeEqual(supplied, expected);
}
function validateResult(body) {
if (!body || typeof body !== 'object' || Array.isArray(body)) return false;
const { winnerUsername, brainrotName, brainrotValue, timestamp } = body;
const validValue = (typeof brainrotValue === 'string' && brainrotValue.trim().length > 0)
|| (typeof brainrotValue === 'number' && Number.isFinite(brainrotValue));
return typeof winnerUsername === 'string' && winnerUsername.trim().length > 0 && winnerUsername.length <= 256
&& typeof brainrotName === 'string' && brainrotName.trim().length > 0 && brainrotName.length <= 256
&& validValue && String(brainrotValue).length <= 128
&& typeof timestamp === 'string' && Number.isFinite(Date.parse(timestamp));
}
client.once('clientReady', async () => {
try {
await client.application.commands.set(commands);
console.log('Slash commands registered.');
} catch (error) {
console.error('Failed to register slash commands:', error);
}
console.log(`Bot is ready! Logged in as ${client.user.tag}`);
console.log('KODARI_READY');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
try {
if (interaction.commandName === 'setchannel') {
const channel = interaction.options.getChannel('channel', true);
await saveChannelConfig(channel.id);
await interaction.reply({
content: `Duel notifications will be posted in <#${channel.id}>.`,
ephemeral: true
});
return;
}
if (interaction.commandName === 'testwin') {
const channel = await getNotificationChannel();
if (!channel) {
await interaction.reply({
content: 'No notification channel is configured. Run `/setchannel` first.',
ephemeral: true
});
return;
}
const timestamp = new Date().toISOString();
await channel.send({
embeds: [createResultEmbed({
winnerUsername: 'Example Winner',
brainrotName: 'Example Brainrot',
brainrotValue: 'Example value (test only)',
timestamp
}, true)],
allowedMentions: { parse: [] }
});
await interaction.reply({ content: `Test embed sent to <#${channel.id}>.`, ephemeral: true });
}
} catch (error) {
console.error('Interaction failed:', error);
const response = { content: 'The command failed. Check the bot logs for details.', ephemeral: true };
if (interaction.replied || interaction.deferred) {
await interaction.followUp(response).catch(() => {});
} else {
await interaction.reply(response).catch(() => {});
}
}
});
client.on('error', error => console.error('Discord client error:', error));
async function start() {
await loadChannelConfig();
const app = express();
app.use(express.json({ limit: '16kb' }));
app.get('/health', (request, response) => {
response.json({ online: client.isReady() });
});
app.post('/api/duel-results', async (request, response) => {
if (!isAuthorizedRequest(request)) {
response.status(401).json({ error: 'Unauthorized' });
return;
}
if (!validateResult(request.body)) {
response.status(400).json({
error: 'Expected winnerUsername, brainrotName, brainrotValue, and a valid ISO timestamp.'
});
return;
}
if (!client.isReady()) {
response.status(503).json({ error: 'Bot is not connected to Discord yet.' });
return;
}