Get number of users in voice channel - javascript

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

Related

Is there a way to personalise collectors to a user? Discord.js

To put it simply, my bot is reading off another bot to see if a drop has been dropped, however, there are some problems occurring.
Current Scenario:
User 1 drops
User 2 drops
The bot my bot is reading off (ID:733122859932712980, hence the filter) sends the first drop
My bot pings the role twice before the second drop has dropped.
The bot my bot is reading off sends the second drop
No ping from my bot
What I want is for the second ping to happen after the second drop happens
Current code:
const Discord = require('discord.js');
module.exports = {
name: "drop",
aliases:["d"],
async execute(client, msg, args) {
const filter = m => m.author.id === "733122859932712980";
const collector = msg.channel.createMessageCollector({
filter
});
collector.on("collect", m => {
if (m.embeds[0]){
const embed = m.embeds[0]
if(embed.author?.name.includes("K-DROP")){
for (var i=0; i<embed.fields.length ; i++){
if(embed.fields[i].name) {
if(embed.fields[i].value.includes("Winner")){
return;
}
else
{
m.channel.send("<#&980128851495641101>")
break;
}
}
}
}
collector.stop();
}
})}};

How can I link an invite code to a user? DISCORD.JS

I have an invite create command, but whenever it creates an invite it does it under the bots ID. I'm wondering if there is a way I can add the invite code to a different user ID so when they use an invites command, it will show the amount of invites that specific code has sent. Bump
module.exports = {
commands: 'invites',
requiredRoles: ['Affiliate'],
callback: (message) => {
if (message.channel.id === '824652970410770443'){
var user = message.author
message.guild.fetchInvites()
.then
(invites =>
{
const userInvites = invites.array().filter(o => o.inviter.id === user.id);
var userInviteCount = 0;
for(var i=0; i < userInvites.length; i++)
{
var invite = userInvites[i];
userInviteCount += invite['uses'];
}
const embed = new Discord.MessageEmbed()
.setColor('#1AA2ED')
.setTitle(message.author.username + "'s Invites")
.setDescription(`Invites: ${userInviteCount}`)
message.reply(embed).then((msg) => {
message.delete()
})
}
)
}
if (message.channel.id !== '824652970410770443'){
message.reply(`You can't do that here`)
}
}
}; ```
You can not change the Invite Creator that Discord knows, however you could locally store which user created which invite link.
This would however have to be done when in the command that creates an invite.
You have multiple options on how to store this data, but the simplest one would just be writing the data to an Object that associates the User ID to the Invite ID, then stringifying and saving that Object to a file whenever your bot exits and loading and parsing that file whenever your bot starts.
Then, whenever you need to know which user created an invite link, look it up in that Object.

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

Mass Role Assigner Command for a Discord.js Bot

I've been working on a discord bot in discord.js that assigns a role to the people mentioned in this framework:
${prefix}assignrole ${role} ${user1} ${user2} ${user3} ...
I have figured out a way to assign the role to one person but I can't find a way to assign it to many people. Heres my code:
if(command === "assignrole"){
if(!message.member.roles.some(r=>["Defenestration Administration", "Moderator", "Admin", "Administrator/Creator"].includes(r.name)) )
return message.reply("Sorry, you don't have permissions to use this!");
var role = message.mentions.roles.first();
var roleId = message.mentions.roles.first().id
message.mentions.members.first().addRole(roleId)
if(!role) {
return message.channel.send("Wrong Input, Must Type a Valid Role After the Command!")
}
}
Can someone help me by showing me a way to assign multiple users a role.
Any answers or help are appreciated, thanks :)
-Joshua
message.mentions.members is a collection. It contains all the members you mentioned in the message. You can loop through the aforementioned collection and add the role.
if (command === "assignrole") {
const Role = message.mentions.roles.first();
message.mentions.members.forEach(member => {
member.roles.add(Role).catch(e => console.error(e));
});
message.channel.send(`Added role ${Role.name} to ${message.mentions.members.map(member => member.user.tag).join(", ")}.`);
}
In addition to #Jakye, you can also use a for loop to avoid rate limit with an async system.
client.on("message", async message => {
let membersArray = message.mentions.members.array();
for(var guildMemberId in membersArray) {
await membersArray[guildMemberId].roles.add(message.mentions.roles.first());
}
message.channel.send("All members have received the role " + message.mentions.roles.first().name + ".");
}

Discord bot: struggling to tally emoji reacts for voting

first time poster here. Sorry if this is an obvious fix, but I'm very new to the world of nodejs and programming in general.
I'm currently trying to create a Discord bot that allows any user to initiate a "love it or hate it" vote with the !vote command. Once the vote is initiated, the bot sends out a message announcing the vote, then reacts to its own message with a heart and skull emoji to denote the love and hate options, respectively. This part is working as intended.
After a set amount of time passes (a very short period), the bot should tally the emoji reactions and figure out if there are more hearts, more skulls, or an equal number of both. Depending on the outcome, it will send another message announcing the outcome of the vote. This part is not working as intended.
As it stands, I can get the bot to respond to my !vote command by sending a new message in the chat and reacting to that message with the proper emojis. The bot will also wait for the set amount of time and announce the outcome of the vote. However, it always announces that the vote was neutral, regardless of which emoji I clicked on before the timer expired (making sure I didn't click both, of course).
My code to compare the number of votes clearly is not functioning as intended. However, after spending hours trying out different fixes, I can't figure out the solution for the life of me and it's driving me crazy. Is there a part of this that's incorrect? And if so, how do I fix it?
Many thanks to anyone who can chime in. After lurking for a while and finding countless fixes in other people's questions in the past, I thought I'd finally turn to the lovely people at Stack Overflow for help. You guys rock!
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', function(message){
if(message.content.toLowerCase().startsWith('!vote'))
{
var heartCount = 0;
var skullCount = 0;
message.channel.send(
"The vote begins! Do we love it or hate it?")
.then(async function (message){
try {
await message.react("❤️")
await message.react("💀")
}
catch (error) {
console.error('One of the emojis failed to react.');
}
})
const filter = (reaction, user) => {
return ["❤️","💀"].includes(reaction.emoji.name) && user.id === message.author.id };
message.awaitReactions(filter, {time: 10000})
.then(collected => {
for (var i = 0; i < collected.length; i++){
if (collected[i].emoji.name === "❤️")
{heartCount++;}
else if (collected[i].emoji.name === "💀")
{skullCount++;}
};
if (heartCount > skullCount){
message.channel.send("We love it!");
}
else if (heartCount < skullCount){
message.channel.send("We hate it.");
}
else {
message.channel.send("We're neutral about it.");
}
})
}
});
bot.login(process.env.BOT_TOKEN);
The fist problem its user.id === message.author.id so only message author can react. message.channel.send return a promise of new message, so you can use then => for message react. Better use action collector on collect for get count and then when collector ends send a message.
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', function(message){
var heartCount = 0;
var skullCount = 0;
if(message.content.toLowerCase().startsWith('!vote')) {
message.channel.send('The vote begins! Do we love it or hate it?').then(msg => {
msg.react(`❤️`).then(() => msg.react('💀'));
const filter = (reaction, user) => {
return [`❤️`, '💀'].includes(reaction.emoji.name);
};
const collector = msg.createReactionCollector(filter, {time: 10000});
collector.on('collect', (reaction, reactionCollector) => {
if (reaction.emoji.name === `❤️`) {
heartCount+=1
} else if (reaction.emoji.name === `💀`) {
skullCount+=1
}
});
collector.on('end', (reaction, reactionCollector) => {
if (heartCount > skullCount){
message.channel.send("We love it!");
}
else if (heartCount < skullCount){
message.channel.send("We hate it.");
}
else {
message.channel.send("We're neutral about it.");
}
});
})
}
})

Categories