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();
}