Shabd Tiwari

"I am setting up a beginner-level Discord server bot/integration using API connections. I need a complete, step-by-step setup guide and code/configuration structure to handle the following features automatically:

  1. API Integration:

Connect the Discord server with my system/platform via API links (e.g., Conferbot / custom AI webhook API).

Provide guidance on how to securely integrate API keys, webhooks, and endpoint URLs for sending and receiving automated messages.

  1. Automated Replies & AI Assistance:

Set up automated responses for frequently asked questions (FAQs), basic commands, and general server queries using AI routing.

  1. Server Moderation & Rules:

Configure auto-moderation tools to enforce server rules, block bad words/profanity, filter invite links, and prevent spam.

Automatically assign default roles to new members upon joining.

  1. Silent Voice Channel Management (Join/Leave & Low Latency):

Enable a bot function to join and leave voice channels on command or trigger.

Crucial Requirement: The bot must NOT play any sound, music, or audio output—it must remain completely silent in the voice channel.

Optimize voice connection parameters (such as region override settings, bitrate, and Krisp noise suppression) to keep latency (ping) as low and stable as possible without connection drops or audio distortion.

Please generate the exact configuration steps, API connection workflow, and recommended bot setups to achieve this efficiently." Integrate API key of gemini as [AQ.Ab8RN6LgP6Ca6N1xe1RxgZqoP3sEPkoTX9EIqTa9HlLfHzx9Ig] if applicable, and also made an personalized file for website bot-hosting.net understands it easily and also add bot token: [<redacted>] this is an important action to add bot token

Kodari AI
KodariOct 16 at 1:12 pm 1
SilentModeratorAI
SilentModeratorAI is a Discord bot built with JavaScript that integrates Gemini AI for automated FAQ responses and intelligent server queries. It features auto-moderation with profanity filters, invite link blocking, spam prevention, and automatic role assignment for new members. The bot supports silent voice channel join/leave commands with zero audio output, optimized for low latency through region override and bitrate settings. It includes secure API key management, webhook integration for external systems, and a comprehensive configuration file tailored for bot-hosting.net deployment. The bot provides complete moderation tools, AI-powered assistance, and reliable voice channel management without any sound playback.
  1. Create a secure Discord bot with FAQ/AI replies, configurable moderation, default roles, and silent voice commands.

  2. Add a protected HTTP webhook API and a hosting manifest.

  3. Document setup, permissions, API connections, and voice limitations.

Created the Discord bot project with FAQ and Gemini /ask commands, invite/profanity and spam filtering, default-role assignment, silent /voice join and /voice leave commands, and a Bearer-protected HTTP message webhook. Setup instructions are in README.md; bot-hosting.json provides a provider-neutral hosting manifest.

Security: I did not put either credential from your message in the project. Both were exposed in chat—revoke/reset the Discord bot token in the Developer Portal and rotate the Gemini API key before using the bot. Add only their replacements to secret environment variables.

Enable Server Members Intent and Message Content Intent in the Discord Developer Portal for role assignment and message moderation. Add the words or phrases you want filtered to config.json.

For Kodari hosting, the webhook URL is https://d7a441mq.kodaribots.com/webhook/message and works while the bot is hosted and running. The bot joins voice self-muted and self-deafened and plays no audio; Discord controls voice region and bitrate, so the bot cannot guarantee low ping or prevent network drops.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot-hosting.json
bot.js
config.json
package.json
README.md
Code
6 384
bot.js
require('dotenv').config();

const crypto = require('node:crypto');
const express = require('express');
const {
  Client,
  GatewayIntentBits,
  PermissionsBitField,
  SlashCommandBuilder
} = require('discord.js');
const {
  entersState,
  getVoiceConnection,
  joinVoiceChannel,
  VoiceConnectionStatus
} = require('@discordjs/voice');
const config = require('./config.json');

if (!process.env.DISCORD_TOKEN) {
  throw new Error('DISCORD_TOKEN is required. Set it in your environment or .env file.');
}

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildVoiceStates
  ]
});

const recentMessages = new Map();
const commands = [
  new SlashCommandBuilder()
    .setName('faq')
    .setDescription('Find an answer in the configured FAQ.')
    .addStringOption(option => option
      .setName('question')
      .setDescription('What would you like to know?')
      .setRequired(true)
      .setMaxLength(150)),
  new SlashCommandBuilder()
    .setName('ask')
    .setDescription('Ask the AI assistant a server-related question.')
    .addStringOption(option => option
      .setName('question')
      .setDescription('What would you like to know?')
      .setRequired(true)
      .setMaxLength(500)),
  new SlashCommandBuilder()
    .setName('voice')
    .setDescription('Manage the bot’s silent voice connection.')
    .addSubcommand(subcommand => subcommand
      .setName('join')
      .setDescription('Join your current voice channel silently.'))
    .addSubcommand(subcommand => subcommand
      .setName('leave')
      .setDescription('Leave the voice channel.'))
].map(command => command.toJSON());

client.once('clientReady', async () => {
  try {
    await client.application.commands.set(commands);
    console.info(`Logged in as ${client.user.tag}; slash commands registered.`);
  } catch (error) {
    console.error('Could not register slash commands:', error);
  }
  console.log('KODARI_READY');
});

client.on('guildMemberAdd', async member => {
  const roleId = process.env.DEFAULT_ROLE_ID?.trim();
  if (!roleId) return;

  try {
    const role = await member.guild.roles.fetch(roleId);
    if (!role) {
      console.warn(`Configured default role ${roleId} was not found in ${member.guild.name}.`);
      return;
    }
    await member.roles.add(role, 'Default role for new members');
  } catch (error) {
    console.error(`Could not assign the default role to ${member.user.tag}:`, error);
  }
});

client.on('messageCreate', async message => {
  if (!message.guild || message.author.bot) return;

  const content = message.content.toLowerCase();
  const containsBlockedWord = (config.badWords || []).some(word => {
    const normalizedWord = String(word).trim().toLowerCase();
    return normalizedWord && content.includes(normalizedWord);
  });
  const containsInvite = /(?:https?:\/\/)?(?:www\.)?(?:discord\.gg|discord(?:app)?\.com\/invite)\/[a-z0-9-]+/i.test(message.content);

  if (containsBlockedWord || containsInvite) {
    try {
      await message.delete();
      console.info(`Removed filtered message from ${message.author.tag} in ${message.guild.name}.`);
    } catch (error) {
      console.error('Could not remove a filtered message. Check Manage Messages permission:', error);
    }
    return;
  }

  const key = `${message.guild.id}:${message.author.id}`;
  const now = Date.now();
  const recent = (recentMessages.get(key) || []).filter(entry => now - entry.time < 8000);
  recent.push({ time: now, content });
  recentMessages.set(key, recent);

  if (recent.length >= 6) {
    recentMessages.delete(key);
    try {
      await message.delete();
      if (message.member?.moderatable) {
        await message.member.timeout(10 * 60 * 1000, 'Automatic spam protection');
      }
      console.info(`Applied spam protection to ${message.author.tag} in ${message.guild.name}.`);
    } catch (error) {
      console.error('Could not apply spam protection. Check Manage Messages and Moderate Members permissions:', error);
    }
  }
});

client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;

  try {
    if (interaction.commandName === 'faq') {
      const question = interaction.options.getString('question', true).toLowerCase();
      const match = (config.faqs || []).find(faq =>
        (faq.keywords || []).some(keyword => question.includes(String(keyword).toLowerCase()))
      );
      await interaction.reply({
        content: match?.answer || 'I could not find a matching FAQ. Try `/ask` or contact a moderator.',
        ephemeral: true
      });
      return;
    }

    if (interaction.commandName === 'ask') {
      await interaction.deferReply();
      const answer = await askGemini(interaction.options.getString('question', true));
      await interaction.editReply(answer);
      return;
    }

    if (interaction.commandName === 'voice') {
      if (!interaction.guild) {
        await interaction.reply({ content: 'This command can only be used in a server.', ephemeral: true });
        return;
      }

      if (interaction.options.getSubcommand() === 'join') {
        const channel = interaction.member.voice?.channel;
        if (!channel) {
          await interaction.reply({ content: 'Join a voice channel first, then run `/voice join`.', ephemeral: true });
          return;
        }
        if (!channel.permissionsFor(client.user)?.has(PermissionsBitField.Flags.Connect)) {
          await interaction.reply({ content: 'I need the Connect permission for that voice channel.', ephemeral: true });
          return;
        }

        getVoiceConnection(interaction.guild.id)?.destroy();
        const connection = joinVoiceChannel({
          channelId: channel.id,
          guildId: interaction.guild.id,
          adapterCreator: interaction.guild.voiceAdapterCreator,
          selfDeaf: true,
          selfMute: true
        });
        connection.on('error', error => console.error('Voice connection error:', error));
        await entersState(connection, VoiceConnectionStatus.Ready, 15_000);
        await interaction.reply({ content: 'Joined silently. No audio is played or received.', ephemeral: true });
        return;
      }

      const connection = getVoiceConnection(interaction.guild.id);
      if (!connection) {
        await interaction.reply({ content: 'I am not in a voice channel.', ephemeral: true });
        return;
      }
      connection.destroy();
      await interaction.reply({ content: 'Left the voice channel.', ephemeral: true });
    }
  } catch (error) {
    console.error(`Error handling /${interaction.commandName}:`, error);
    const response = { content: 'Something went wrong. Please try again later.', ephemeral: true };
    if (interaction.deferred || interaction.replied) {
      await interaction.followUp(response).catch(() => {});
    } else {
      await interaction.reply(response).catch(() => {});
    }
  }
});