Send a message to a text channel when a person joins a specific voice channel
I'm trying to make my bot that notifies my server staff in a specific text channel when someone enters the voice support waiting room.
Unfortunately, I only found some examples for Discord version 12, and it's not working for me in version 13. I don't know what to change in that code.
There is no error message or anything, it just doesn't send a message when someone is joining the voice channel.
client.on('voiceStateUpdate', (oldState, newState) => {
const newUserChannel = newState.channelID;
const textChannel = client.channels.cache.get('931223643362703521');
if (newUserChannel === '931156705303317013') {
textChannel.send('Somebody joined');
}
console.error();
});
Solution 1:
First, make sure you add the GUILD_VOICE_STATES
intents.
It's probably better to fetch
the channel, instead of relying on the cache. If the channel is already cached, fetch
will use that and won't make a request to the discord API, but if it's not cached, channels.cache.get
won't find it.
I've made a couple of changes and added some comments in the code below:
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_VOICE_STATES,
],
});
client.on('voiceStateUpdate', async (oldState, newState) => {
const VOICE_SUPPORT_ID = '931156705303317013';
const LOG_CHANNEL_ID = '931223643362703521';
// if there is no newState channel, the user has just left a channel
const USER_LEFT = !newState.channel;
// if there is no oldState channel, the user has just joined a channel
const USER_JOINED = !oldState.channel;
// if there are oldState and newState channels, but the IDs are different,
// user has just switched voice channels
const USER_SWITCHED = newState.channel?.id !== oldState.channel?.id;
// if a user has just left a channel, stop executing the code
if (USER_LEFT)
return;
if (
// if a user has just joined or switched to a voice channel
(USER_JOINED || USER_SWITCHED) &&
// and the new voice channel is the same as the support channel
newState.channel.id === VOICE_SUPPORT_ID
) {
try {
let logChannel = await client.channels.fetch(LOG_CHANNEL_ID);
logChannel.send(
`${newState.member.displayName} joined the support channel`,
);
} catch (err) {
console.error('❌ Error finding the log channel, check the error below');
console.error(err);
return;
}
}
});