true_zefy

I want a discord bot that will stay in a vc and wont leave a type of music one but its cant leave i also want to be able to send messages through it so like i can tell it to say something in a chat with out it being complicated i want it to also have the abilty to reply to people when they say trigger words

Kodari AI
KodariAug 26 at 8:58 pm 1
VCPersistentBot
A Discord bot that permanently stays in a voice channel without leaving, providing continuous presence. It supports simple text messaging where users can command the bot to say phrases in chat. The bot also includes a trigger-word reply system, automatically responding to specific keywords mentioned by users. Built with JavaScript, it uses Discord.js for seamless integration, offering an uncomplicated setup for voice persistence, chat messaging, and automated replies.

I’ll build a Discord.js bot with:

  1. Persistent voice connection with automatic reconnects and no leave command.

  2. Simple /say command for sending messages to text channels.

  3. Configurable trigger-word replies with cooldown protection.

  4. Environment-based setup with no hardcoded bot token.

Kodari can make mistakes. Review important code before using.
Files
config.json
index.js
package.json
README.md
Code
4 559
index.js
require('dotenv').config();

const {
  ChannelType,
  Client,
  GatewayIntentBits,
  PermissionFlagsBits,
  REST,
  Routes,
  SlashCommandBuilder
} = require('discord.js');

const {
  VoiceConnectionStatus,
  entersState,
  getVoiceConnection,
  joinVoiceChannel
} = require('@discordjs/voice');

const config = require('./config.json');

const requiredEnvironmentVariables = [
  'DISCORD_TOKEN',
  'CLIENT_ID'
];

for (const variable of requiredEnvironmentVariables) {
  if (!process.env[variable]) {
    throw new Error(`Missing required environment variable: ${variable}`);
  }
}

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

const reconnectTimers = new Map();
const voiceTargets = new Map();
const triggerCooldowns = new Map();
const reconnectDelay = Number(process.env.VOICE_RECONNECT_DELAY_MS) || 5000;

let shuttingDown = false;

const commands = [
  new SlashCommandBuilder()
    .setName('join')
    .setDescription('Join your current voice channel or a selected voice channel.')
    .addChannelOption(option =>
      option
        .setName('channel')
        .setDescription('The voice channel to join.')
        .addChannelTypes(ChannelType.GuildVoice, ChannelType.GuildStageVoice)
        .setRequired(false)
    ),

  new SlashCommandBuilder()
    .setName('say')
    .setDescription('Send a message through the bot.')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages.toString())
    .addChannelOption(option =>
      option
        .setName('channel')
        .setDescription('The text channel where the message should be sent.')
        .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)
        .setRequired(true)
    )
    .addStringOption(option =>
      option
        .setName('message')
        .setDescription('The message the bot should send.')
        .setMaxLength(2000)
        .setRequired(true)
    )
];

async function registerCommands() {
  const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
  const route = process.env.GUILD_ID
    ? Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID)
    : Routes.applicationCommands(process.env.CLIENT_ID);

  await rest.put(route, {
    body: commands.map(command => command.toJSON())
  });

  console.log(
    process.env.GUILD_ID
      ? `Registered commands in guild ${process.env.GUILD_ID}.`
      : 'Registered global commands.'
  );
}

function clearReconnectTimer(guildId) {
  const timer = reconnectTimers.get(guildId);

  if (timer) {
    clearTimeout(timer);
    reconnectTimers.delete(guildId);
  }
}

function scheduleReconnect(guildId, channelId) {
  if (
    shuttingDown ||
    voiceTargets.get(guildId) !== channelId ||
    reconnectTimers.has(guildId)
  ) {
    return;
  }

  const timer = setTimeout(async () => {
    reconnectTimers.delete(guildId);

    try {
      const channel = await client.channels.fetch(channelId);

      if (!channel || !channel.isVoiceBased()) {
        throw new Error('The configured voice channel no longer exists.');
      }

      await connectToVoiceChannel(channel);
    } catch (error) {
      console.error(
        `Voice reconnect failed for guild ${guildId}:`,
        error.message
      );

      scheduleReconnect(guildId, channelId);
    }
  }, reconnectDelay);

  reconnectTimers.set(guildId, timer);
}

async function connectToVoiceChannel(channel) {
  if (!channel || !channel.isVoiceBased() || !channel.guild) {
    throw new Error('A valid guild voice channel is required.');
  }

  const guildId = channel.guild.id;
  const channelId = channel.id;

  voiceTargets.set(guildId, channelId);
  clearReconnectTimer(guildId);

  const existingConnection = getVoiceConnection(guildId);

  if (
    existingConnection &&
    existingConnection.joinConfig.channelId === channelId &&
    existingConnection.state.status !== VoiceConnectionStatus.Destroyed
  ) {
    return existingConnection;
  }

  if (existingConnection) {
    existingConnection.destroy();
  }

  const connection = joinVoiceChannel({
    channelId,
    guildId,
    adapterCreator: channel.guild.voiceAdapterCreator,
    selfDeaf: false,
    selfMute: false
  });

  connection.on(VoiceConnectionStatus.Disconnected, async () => {
    try {
      await entersState(
        connection,
        VoiceConnectionStatus.Signalling,
        5000
      );
    } catch {
      if (connection.state.status !== VoiceConnectionStatus.Destroyed) {
        connection.destroy();
      }

      scheduleReconnect(guildId, channelId);
    }
  });

  connection.on(VoiceConnectionStatus.Destroyed, () => {
    scheduleReconnect(guildId, channelId);
  });

  try {
    await entersState(connection, VoiceConnectionStatus.Ready, 20000);
    console.log(`Connected to ${channel.name} in ${channel.guild.name}.`);
    return connection;
  } catch (error) {
    if (connection.state.status !== VoiceConnectionStatus.Destroyed) {
      connection.destroy();
    }