discord.js voice channel member count - javascript

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

Related

How would I automatically move someone back to a channel?

So, basically I have some code setup and I don't see the issue with the code. But basically what I want it to do is if the previous voice channel of the member that switched channels was "DO NOT DISTURB" it will move them back to the "DO NOT DISTURB" voice channel. What have I done wrong? I get 0 errors in console.
client.on('voiceStateUpdate', async (oldState, newState) => {
let newUserChannel = newState.channel;
let oldUserChannel = oldState.channel;
if(oldUserChannel.id === "894024223088050176") {
var dndChannel = oldState.guild.channels.cache.find(ch => ch.type === "voice" && ch.name === "DO NOT DISTURB")
newState.member.voice.setChannel(dndChannel)
}
});
Double check if your channelid in the if condition is right and use
Guild.channels.fetch(channelId)
insted of Guild.channels.cache.find().

Logging user presence status discord.js

I am trying to log presence for my bot called Timer Bot. I want it to alert everyone when he goes online and when he goes offline. Here is the script I'm using -
client.on('presenceUpdate', (oldPresence, newPresence) => {
let member = newPresence.member;
// User id of the user you're tracking status.
if (member.id === '603517534720753686') {
if (oldPresence.status !== newPresence.status) {
// Your specific channel to send a message in.
let channel = member.guild.channels.cache.get('788547135234375712');
// You can also use member.guild.channels.resolve('<channelId>');
let text = "";
if (newPresence.status === "online") {
text = "**Hello #everyone, Timer Bot is now online! Thank you for your patience.**";
} else if (newPresence.status === "offline") {
text = "**#everyone Due to issues, Timer Bot is currently offline. We apologize for the inconvenience.**";
}
// etc...
channel.send(text);
}
}
});
For some reason, it doesn't work. Anyone know why?
Thanks,
Brian.#1111
You need to enable presence intent and then pass it in to the client when logging in.
new Discord.Client({ws:{intents: [Intents.FLAGS.GUILD_PRESENCES]}});
Source: https://discord.js.org/#/docs/main/stable/class/Intents?scrollTo=s-FLAGS
https://discord.com/developers/applications/

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 :(

Auto role when someone starts streaming

I wanted to set a role for a user if he/she starts streaming and sending a message in #streaming. But I keep getting this error that TypeError: Cannot read 'add' of undefined.
client.on('presenceUpdate', (oldMember, newMember) => {
const guild = newMember.guild;
const streamingRole = guild.roles.cache.find(role => role.id === 'streamer');
if (newMember.user.bot) return;
if (newMember.user.presence.activities.streaming) { // Started playing.
let announcement = `Ebrywan ${newMember} just started streaming`;
let channelID = client.channels.cache.find(channel => channel.name.toLowerCase() === "streaming");
if (channelID) channelID.send(announcement);
newMember.roles.add(streamingRole)
console.log(`${streamingRole.name} added to ${newMember.user.tag}`)
}
});
From what i can see from the documentation newMember is a Presence and not a user you can add a role too. Try:
newMember.member.roles.add(streamingRole)
.member will give you the member and you can get the roles of a member + adding new roles should also be possible
Presence: https://discord.js.org/#/docs/main/stable/class/Presence
Member: https://discord.js.org/#/docs/main/stable/class/GuildMember

Get number of users in voice channel

I am rewriting the music portion of my friends discord bot. I am trying to figure out how to get the number of users in the voice channel of the person who executed the command. I have looked everywhere but I can't seem to find it or its usage.
Right now I am using the following:
module.exports.run = async (client, message, args) => {
if (!message.member.roles.cache.find(role => config["dj_role"] === string.toLowerCase(role.name))) {
if (!message.member.hasPermission('MANAGE_GUILD' || 'MANAGE_ROLES' || 'ADMINISTRATOR')) {
if (!message.member.id == message.guild.ownerID) {
let count = 0;
count += voiceChannel.members.size;
if (count > 3){
return message.channel.send(client.msg["rejcted_dj"].replace("[ROLE_DJ]", config["dj_role"]));
}
}
}
}
if (!message.member.voice.channel){return message.channel.send(client.msg["music_channel_undefined"])}
//play music part
}
You're pretty close. You already got the voice channel of the command author:
if (!message.member.voice.channel){return message.channel.send(client.msg["music_channel_undefined"])}
You can use the VoiceChannel.members.size to get how many members are in the channel.
Here's an example:
const GuildMember = new Discord.GuildMember(); // This shall be the command author.
if (GuildMember.voice.channel) {
console.log(GuildMember.voice.channel.members.size);
};

Categories