Discord.js v13. | voiceStateUpdate Event - javascript

This is a bot that plays an audio per command in vc (on Discord server 1). But on Discord server 2, the bot should always be in a vc, and not leaven when no one (except itself) is in the vc.
So the bot should always stay in the talk channel 1073655275141210122 on Discord server 1, even if it is alone in that talk. On server 2, on the other hand, the bot should always stay in the voice channel or VC when no one else is in it (except the bot itself).
My problem: The bot leavens on both channels as soon as there is no one in them.
My current code:
// Voice State Update Event
client.on('voiceStateUpdate', (oldState, newState) => {
const state = newState || oldState
if(state.channelId == '1073655275141210122') {
return;
}
if (oldState.channelID !== oldState.guild.me.voice.channelID || newState.channel){
return;
}
if(oldState.channel.members.size == 1 && oldState.channel.members.get(client.user.id)){
newState.guild.me.voice.disconnect();
}
});
I have already tried:
if(state.channelId == '1073655275141210122') return
&
if (oldState.channelID !== oldState.guild.me.voice.channelID || !newState.channel)
but it doesn't matter.

Related

Discord js / Check if user is in an specific voice Channel

I want my bot to move a user in 1 of 2 afk channels by using a "<afk [radio]" command.
But i first want to check if the user is allready in an AFK Channel. I tried:
const voiceChannel = message.member.voice.channel;
const voiceChannelID = message.member.voice.channelID;
if (!voiceChannel) {
return message.channel.send('You are not in an voice Channel so why move to AFK?');
} else if (voiceChannelID === '789186504483536937', '791444742042943548') {
return message.channel.send('You are already in an AFK channel!');
} else if (!args.length) {
return member.voice.setChannel('789186504483536937');
}
But when i try t use the "<afk" command the bot send the message:
You are already in an AFK channel!
Any ideas why it does this?
The problem is
if (voiceChannelID === '789186504483536937', '791444742042943548')
This is not how multiple conditionals work. Seperate it with the or operator.
if (voiceChannelID === '789186504483536937' || voiceChannelID === '791444742042943548')
You can think of what you were trying to do as passing in two different conditions, f(x, y). If statements in Javascript will only check for the last one (y), and "791444742042943548" is truthy since it is non-null.

discord.js voice channel member count

I have the problem that the bot the member count updates only once and does nothing else after. Does anyone know how to solve it?
Heres my current code:
bot.on("ready", () => {
const guild = bot.guilds.cache.get('779790603131158559');
setInterval(() => {
const memberCount = guild.memberCount;
const channel = guild.channels.cache.get('802083835092795442')
channel.setName(`DC︱Member: ${memberCount.toLocaleString()}`)
}, 5000);
});
If I am understanding you correctly, you want to rename a VC to the member count. The Discord API only lets you rename a channel 2 times every 10 minutes. You are trying to run that code every 5 seconds.
Try setting your timeout delay to 600000 instead of 5000.
You could try to use voiceStateUpdate, it's fired everytime a user leaves, enters, mutes mic or unmutes mic. Here's a link to it: voiceStatusUpdate
You can also use voiceChannelID if you want to get the ID of the channel. Here a link: voiceChannelID
Here's a basic idea of the code you can use:
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
if(oldUserChannel === undefined && newUserChannel !== undefined) {
// User Joins a voice channel
} else if(newUserChannel === undefined){
// User leaves a voice channel
}
})

How to detect when a member joins & leaves a voice channel

I am working on a discord bot that would need to detect when a user joins & leaves a channel. I have tried this on line 4 because if the user's connection doesn't change, it won't run.
But this does not work. Here is my entire section of code.
client.on('voiceStateUpdate', (oldState, newState) => {
// check for bot
if (oldState.member.user.bot) return;
if (oldState.member.voice === newState.member.voice) return;//<- here
client.channels.cache.get('777782275004825640').send(`${oldState.member} joined`);
});
I've also tried .connection but it doesn't work with my current setup. Any help would be great!
I found it!
After some testing, I found out that when a channel was updated one of four things would happen.
if the user joined the oldState.channelID returned null
if the user left the newState.channelID returned null
if the user muted themselves or were deafened the oldState.channelID was equal to newState.channelID
if the user moved channels oldState.channelID did not equal newState.channelID
my Discord.Client() is set as client, so if yours is different change that
client.on('voiceStateUpdate', (oldState, newState) => {
if(oldState.channelID === newState.channelID) {
console.log('a user has not moved!')
}
if(oldState.channelID != null && newState.channelID != null && newState.channelID != oldState.channelID) {
console.log('a user switched channels')
}
if(oldState.channelID === null) {
console.log('a user joined!')
}
if (newState.channelID === null) {
console.log('a user left!')
}
});
Try this snippet and please let me know how it worked for you.
let oldChannel = oldState.voiceChannel;
let newChannel = newState.voiceChannel;
if(oldChannel === undefined && newChannel !== undefined) {
// User has joined a channel
} else if(newChannel === undefined) {
// User has left a channel
}

How to detect when a user leaves a voice channel in Discord with discord.js V12

I am making a Discord.js Bot on v12 that includes a mute command, that mutes the whole voice channel you are in. The problem is when somebody leaves the channel they stay muted. I am trying to fix that with a simple event to unmute the person, but I don't understand the VoiceStateUpdate and the OldState and NewState. I've searched widely, but I can only find one for joining a vc, not leaving. Here is what I got so far:
Mute command:
else if (command === 'mute') {
message.delete()
if (!message.member.roles.cache.has('') && !message.member.roles.cache.has('')) {
message.reply('You don\'t have permission to use this commmand!')
.then(message => {
message.delete({ timeout: 5000 })
}).catch();
return;
}
if (message.member.voice.channel) {
let channel = message.guild.channels.cache.get(message.member.voice.channel.id);
for (const [memberID, member] of channel.members) {
member.voice.setMute(true);
}
} else {
message.reply('You need to join a voice channel first!')
.then(message => {
message.delete({ timeout: 5000 })
}).catch();
}
}
Unmute event:
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.member.user.bot) return;
if (oldState.member.user !== newState.member.user) member.voice.setMute(false);
});
Thanks for taking your time to help me! :)
Well, you are already on the right track. What you should do is check if someone is muted when they leave a voice channel and then remove that mute.
So lets get to that.
First we check if the person is leaving the voice channel. Thats important because the voiceStateUpdate event is triggered every time some does anything to their voice, i.e. mute or joining. We do that by checking if oldState.channelID is either null or undefined as that indicates a joining.
if (oldState.channelID === null || typeof oldState.channelID == 'undefined') return;
Next we need to check if the person leaving is muted and return if not.
if (!oldState.member.voice.mute) return;
And lastly we remove the mute.
oldState.member.voice.setMute(false);
So your entire voiceStateUpdate should look a little something like this.
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.channelID === null || typeof oldState.channelID == 'undefined') return;
if (!oldState.member.voice.mute) return;
oldState.member.voice.setMute(false);
});
You can't manipulate the voice state of a person that isn't on a voice channel, it would cause a DiscordAPIError: Target user is not connected to voice., and even if you could, you probably would still not want to, because even if you don't get another unhandled promise error of some sort, you would probably still get an infinite loop by checking if the New State's channel is null, because it would fire another event with null channel as soon as you unmute the person and so on.
So, the way I see it right now, a possible solution to your problem, is to unmute whenever the user joins a channel. It might not be necessary to be this way if someone can figure out a better way to check if it is a channel leaving that is happening other than just using newState.channel === null. Whatever, if it's okay for you to unmute on join, you could do it this way:
client.on('voiceStateUpdate', (oldState, newState) => {
if (oldState.channel === null && newState.channel !== null) {
newState.setMute(false);
}
});
Notice though that this could bug if someone joins the channel exactly after leaving, otherwise, you should have no problems.
according to this link (and I havent tested this) you need something like this:
const Discord = require("discord.js")
const bot = new Discord.Client()
bot.login('*token*')
bot.on('voiceStateUpdate', (oldState, newState) => {
let newUserChannel = newState.voiceChannel
let oldUserChannel = oldState.voiceChannel
if(oldUserChannel === undefined && newUserChannel !== undefined) {
// User Joins a voice channel
} else if(newUserChannel === undefined){
// User leaves a voice channel
}
})
client.on('voiceStateUpdate', (oldMember, newMember) => {
const oldUserChannel = oldMember.voice.channelID
const newUserChannel = newMember.voice.channelID
if (oldUserChannel === 'MUTED CHANNEL ID' && newUserChannel !== 'MUTED CHANNEL ID') {
newMember.voice.setMute(false);
}
});
You can write in a json file the id of the muted channel and take it from there, I can't think of another way, sorry :(

How to: Give permissions for text channel when user joins VC and revoke when user leaves VC

I'm attempting to make it so that when someone joins the Voice Channel, so the Bot will add the specific person to the text channel with the permission to read and send messages and remove the individual and their permissions when they leave the Voice Channel. I'm not overly familiar with discord.js so I'm not sure on how to do it.
First and foremost, welcome to Stack Overflow. I hope we can be of help to you.
Let's start by detecting when a member joins a voice channel. To do so, we can listen to your client's voiceStateUpdate event. Next, we can compare the old voice channel with the new one, and see if the member joined or left. Finally, we can change the permissions for the member in the text channel using GuildChannel.overwritePermissions().
Update: Multiple "pairs" of text channels and voice channels with similar behavior.
To do this for many different channels, you could set up a json file to store the voice channels and corresponding text channels, and then iterate over each pair, checking if the situation matches any.
channelPairs.json
[
{ "voice": "voiceChannelIDHere", "text": "textChannelIDHere" }
]
index.js
const pairs = require('./channelPairs.json'); // Keep in mind the path may vary
client.on('voiceStateUpdate', (oldMember, newMember) => {
let oldID;
let newID;
if (oldMember.voiceChannel) oldID = oldMember.voiceChannel.id;
if (newMember.voiceChannel) newID = newMember.voiceChannel.id;
for (let i = 0; i < pairs.length; i++) {
const textChannel = newMember.guild.channels.get(pairs[i].text);
if (!textChannel) {
console.log('Invalid text channel ID in json.');
continue;
}
const vcID = pairs[i].voice;
if (oldID !== vcID && newID === vcID) { // Joined the voice channel.
textChannel.overwritePermissions(newMember, {
VIEW_CHANNEL: true,
SEND_MESSAGES: true
}).catch(console.error);
} else if (oldID === vcID && newID !== vcID) { // Left the voice channel.
textChannel.overwritePermissions(newMember, {
VIEW_CHANNEL: null,
SEND_MESSAGES: null
}).catch(console.error);
}
}
});
Okay so let's take a look at the DiscordJS API:
Found here.
As we can see, there's a class called "WSEvent" (stands for WebsocketEvent). We can use this to detect when a user joins the channel...
But we can't really use that because there's no "CHANNEL_JOIN" event. So instead, we must listen for this voiceStateUpdate or VOICE_STATUS_UPDATE event.
Like so:
// voiceStateUpdate
/* Emitted whenever a user changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
PARAMETER TYPE DESCRIPTION
oldMember GuildMember The member before the voice state update
newMember GuildMember The member after the voice state update */
client.on("voiceStateUpdate", function(oldMember, newMember){
console.log(`a user changes voice state`);
// Here we can just check if newMember is in the channel that we want. Bam.
if(newMember.voiceChannel.name == 'channelname') {
// DO SOMETHING.
myVoiceChannel.overwritePermissions(newMember, {
SEND_MESSAGES: true
});
} else {
myVoiceChannel.overwritePermissions(newMember, {
SEND_MESSAGES: null
});
}
});
Let's reduce this:
newMember.voiceChannel - This means what channel their connected to.
voiceChannel.name - Get the name of the channel so we can check it.
Hope I was a help, and by the way, here's a neat little cheatsheet I like to use when developing DiscordJS bots: https://gist.github.com/koad/316b265a91d933fd1b62dddfcc3ff584

Categories