hanifa ali

Build a Discord bot named NST HUB DUELZ, inspired by gaming duel-result notification bots.

Requirements:

  • Use JavaScript and discord.js.
  • Send beautiful purple Discord embeds similar to gaming winner notifications.
  • Show the winner's username, Brainrot name, Brainrot value, and timestamp.
  • Let me configure the Discord channel where notifications are sent.
  • Include a test command /testwin to preview the embed.
  • Keep the bot token secure using environment variables.
  • Provide the complete project files and clear setup instructions.

Important: Do not invent real duel results. Create a test mode and a documented integration interface so my authorized game system can send verified duel results to the bot.

Kodari AI
KodariOct 11 at 6:15 pm 1
NstHubDuelzBot
A Discord bot that sends purple gaming-style embeds for duel results. It displays the winner's username, Brainrot name, Brainrot value, and timestamp. Configurable notification channel via environment variables. Includes a /testwin command to preview the embed and a documented HTTP webhook endpoint for authorized game systems to send verified duel results. Uses discord.js, JavaScript, and secure token handling via dotenv.

Created the NST HUB DUELZ Discord bot project with slash commands, purple result embeds, and an authenticated integration API.

  • /setchannel saves the notification channel; /testwin posts a clearly labeled preview, not a real duel result.

  • Authorized game systems can submit verified results to https://8ynls53n.kodaribots.com/api/duel-results using the shared INTEGRATION_SECRET.

  • To start: copy .env.example to .env, set DISCORD_TOKEN and a strong INTEGRATION_SECRET, then run npm install and npm start. Invite the bot with bot and applications.commands scopes, then configure the channel with /setchannel.

  • README.md documents setup and the integration payload. No privileged Discord intents are needed.

hanifa ali

<redacted>

Kodari AI
KodariOct 11 at 6:16 pm 1

That looks like your Discord bot token. It’s now exposed, so reset it immediately in the Discord Developer Portal: Your App → Bot → Reset Token. Then put the new token in your project’s .env file as DISCORD_TOKEN=...—never share it in chat or commit it to source control.

hanifa ali

my token is <redacted>

Kodari AI
KodariOct 11 at 6:17 pm 1

That token has been exposed in chat. Reset it now in the Discord Developer Portal under Your App → Bot → Reset Token; don’t use the exposed token. Put the replacement only in your local .env as DISCORD_TOKEN=..., and never share it or commit it to your project.

hanifa ali

;env

Kodari AI
KodariOct 11 at 6:17 pm 1

If you mean the .env file, put your newly reset token in the project root like this:

Env
DISCORD_TOKEN=your_new_token_here
INTEGRATION_SECRET=your_long_random_secret

Don’t put the token you shared here in the file—reset it first. Keep .env private and out of version control.

hanifa ali

DISCORD_TOKEN=<redacted> INTEGRATION_SECRET=token

Kodari AI
KodariOct 11 at 6:18 pm 1

Both values are exposed here. Reset the Discord bot token now in the Developer Portal and replace it only in your local .env. Also replace INTEGRATION_SECRET=token with a long, random secret (for example, generate one with openssl rand -hex 32).

Env
DISCORD_TOKEN=your_new_token
INTEGRATION_SECRET=your_generated_secret

Don’t send the replacement here or commit .env to your repository.

Kodari can make mistakes. Review important code before using.
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;
    }