Discord.js / Mute everyone - javascript

So I wrote the following code that is supposed to mute all the members in a given channel:
client.on('message', message => {
if (message.content == 'sh!') {
let channel = message.member.voice.channel
for (let member of channel.members) {
member[1].setMute(true)
}
}
})
But it does not work and I cannot find out why because I do not really know how the setMute() function works.
EDIT: I am not sure about how I can access every member and mute it

The 'setMute' function is part of the member's voice state object. You're using it directly from the GuildMember object itself. As you may already know, the voice state object is the property 'voice' of the GuildMember object. So here's the solution:
// change this
member[1].setMute(true);
// to this
member[1].voice.setMute(true);
The property Members of a VoiceChannel is a Discord Collection (which extends from Javascript Map), I would iterate using a forEach loop so I could avoid Downlevel Iteration.
This should work:
client.on('message', message => {
if (message.content == 'sh!') {
const members = message.member.voice.channel.members;
members.forEach(member => {
member.voice.setMute(true);
});
}
});
Here's some useful links:
TextChannel#members | discord.js
Collection | discord.js
Map - JavaScript | MDN

Related

discord.js v13 TypeError: Cannot read properties of undefined (reading 'presence')

I'm trying to make a joke command with my friends to ban people who are playing Roblox or if he has the Roblox game status. I've searched everything in the internet and in stack overflow if there's a solution but I can't find a single working one. Here's my code:
module.exports = async (client) => {
const guild = client.guilds.cache.get('877016354581004389');
if(guild){
setInterval(async () => {
if(!guild.me.permissions.has('ADMINISTRATOR')) return;
const channel = guild.channels.cache.get('877016354581004392');
if(!channel) return console.log('ANNOUNCEMENT CHANNEL NOT FOUND...')
let bannedAmount = 0;
await guild.members.fetch().then(members => {
members.forEach(member => {
for(const allMember of Object.keys(member)){
if(allMember.user.presence.activities){
const activity = allMember.user.presence.activities[0]
if(activity.name.toLowerCase() == "roblox"){
channel.send(`${allMember} got banned because he's playing ROBLOX!!`)
allMember.ban({ reason: `he played roblox lol`});
bannedAmount = bannedAmount + 1
break;
}
}
}
})
});
let members;
if(bannedAmount > 1) members = 'members';
let kid;
if(bannedAmount > 1) kid = 'kids';
if(bannedAmount <= 0 || null){
console.log(`No member banned for playing Roblox...`);
} else if(bannedAmount > 0) {
channel.send(`${bannedAmount} ${kid || 'kid'} got banned in this server for playing Roblox. Don't do it kids!`)
console.log(`${bannedAmount} ${members || 'member'} got banned for playing Roblox...`)
}
}, 20000);
}
}
I have no hate with the game Roblox guys just fooling around lol
PS: I have already enabled intents in both discord dev website and also in the index.js file and also had used <member>.presence.activities but it looks like only user has presence property.
Well, the problem is that GuildMember#presence returns or a Presence class OR undefined, because it's an optional property. What you do in your code is taking the presence property of a user who probably doesn't has any presence and that's why allMember.user.presence returns undefined and allMember.user.presence.activities[0] too. Also keep in mind that you take the User of a member, but presences go on GuildMembers and not on Users.
Debugging:
Just use allMember instead of allMember.user, so u take the presence of a GuildMember instead of a User, after this a Member who has a presence will return the presence data too.
Add a if statement that controls if a member has a presence or not, so you don't run in the same error again.
I don't know if you tought about this, but if a member has more than one presence and the first presence in the array isn't Roblox, but for example the second presence in the array is Roblox the member won't get banned.
I hope this helps you, if you have questions just contact me on Discord
~ Iliannnn#0001

memb.guild.roles.find is not a function

I have a code where if someone joins the bot gives a Privat message and a Role but when a user joins, the bot does not give the message and the Role.
TypeError: memb.guild.roles.find
const AUTOROLEID = "689098211536666624"
client.on('guildMemberAdd', (memb) => {
var role = memb.guild.roles.find(r => r.id == "689098211536666624")
if (role) {
memb.addRole(role).then(() => {
memb.send('', new Discord.MessageEmbed().setColor(0x18FFFF).setDescription(`Willkommen aufm Discord deine aktuelle rolle ist ${role.name}!`))
})
}
})
As Discord.js v12 docs you need to access the property cache after <GuildMember>.guild.roles which is a collection of all roles in the guild so you can try this:
var role = memb.guild.roles.cache.find(r => r.id == "689098211536666624")
From the given code, I assume you are using discord.js v11 which got deprecated. So update to v12. v12 introduced the concept of managers/cache. In v11 you were able to use collection methods like get() and find()on collection structures, but now you need to ask for cache on a manager before trying to use collection methods.
Eg:
var role = memb.guild.roles.cache.find(r => r.id == "689098211536666624") //find requires a function
var var role = memb.guild.roles.cache.get("689098211536666624"); //get requires an ID as string.
and <GuildMember>.addRole() method got deprecated. You need to pass through the managers(GuildMemberRoleManager) and then call then .add() method.
Eg:
var role = memb.guild.roles.cache.find(r => r.id == "689098211536666624")
if(role){
memb.roles.add(role).then(()=>{
//do things.
}
}

discord.js | Remove a role from a member and give said role to another member

I'm trying to remove a role from one person, and give that role to the person who initiated the command.
It works the first time, when person A does it. But when someone else tries call the command for the second time, the code doesn't find person A. Any help would be cool.
//Just some startup stuff
const { error, timeStamp } = require('console'),
client = new Discord.Client(),
client.login('How About No?')
var command, role, person
//Check if it's alive
client.once('ready', () => {
console.log(`${client.user.tag} is online`)
})
//When a message is sent
client.on('message', message => {
command = message.content.toLowerCase()
if(command === 'test' && message.guild.id === 'the server ID'){
role = message.guild.roles.cache.find(r => r.id === 'the role ID') //Find the correct role
person = role.members.first()
/* I can use ".first()" here, because there's never supposed to be more than one person with this role.
The problem is here. On the second run, it outputs "undefined" even though a person has the role. */
//If a person has the role, remove it from them.
if(typeof person !== 'undefined') person.roles.remove(role).catch(error => console.log(error))
//Give the role
person = message.member
person.roles.add(role).catch(error => console.log(error))
}
})
It can happen sometimes because the cache won't update fast enough.
What you can do is fetch the role instead with API request.
message.guild.roles.fetch('the role ID',true,true)

Doesn't create the voice channel with no error

I am trying to build a bot with the discord.js library in node.js that will create a new voice channel in a certain category when a user joins a certain channel. After the creation of the channel, I want the bot to then move the user to the new channel!
I am trying the following code:
var temporary = [];
client.on('voiceStateUpdate', async (oldMember, newMember) => {
const mainCatagory = '815281015207624704';
const mainChannel = '814938402137833484';
if (newMember.voiceChannelID == mainChannel) {
await newMember.guild
.createChannel(`📞 ┋ Support Room`, { type: 'voice', parent: mainCatagory })
.then(async (channel) => {
temporary.push({ newID: channel.id, guild: newMember.guild.id });
await newMember.setVoiceChannel(channel.id);
});
}
if (temporary.length >= 0)
for (let i = 0; i < temporary.length; i++) {
let ch = client.guilds
.find((x) => x.id === temporary[i].guild)
.channels.find((x) => x.id === temporary[i].newID);
if (ch.members.size <= 0) {
await ch.delete();
return temporary.splice(i, 1);
}
}
});
The code comes with no error but doesn't create the voice channel!
The problem is that you are using discord.js v12, but your code is made for v11.
Client#voiceStateUpdate now passes VoiceStates as parameters, not GuildMembers. You should rename newMember and oldMember to newState and oldState respectively.
GuildMember#voiceChannelID is a deprecated property, which is why you don't get any errors. Your code never actually gets past the if statement. It has turned into GuildMember#voice#channelID (newState.channelID).
Guild#createChannel is also deprecated, being replaced with Guild#channels#create. The function still looks and acts the same, so you only need to change the name (newState.guild.channels.create).
GuildMember#setVoiceChannel has turned into GuildMember#voice#setChannel (newState.setChannel)
Client#guilds#find has turned into Client#guilds#cache#find (client.guilds.cache.find)
Guild#channels#find has turned into Guild#channels#cache#find (client.cache.find(...).channels.cache.find)
(As a side note, always use Collection#get instead of Collection#find when searching by IDs. .find((value) => value.id === '...') should always be converted to simply .get('...'). This also applies to switching Collection#some with Collection#has)
Guild#members#size has turned into Guild#members#cache#size (ch.members.cache.size)
Every single one of these deprecations occurred as a result of discord.js switching to a Manager/caching system. For example, Client#guilds now returns a GuildManager instead of a collection.
More information about switching from v11 to v12 (including Managers)

Adding role to all members who has another role?

I want to run a command on my discord bot and add a secondary role to all members which have the predefined role.
Its gonna be like this. All members have the X role are gonna be assigned to the Y role.
I tried to write to code but I failed so I am writing my code as pseudo-code below any help will be great.
const userID = "1234"; //this is my userid so only I will be able to use this command
let roleID1 = "xxxx";
let roleID2 = "yyyy";
client.on("message", function (message) {
if (message.author.id === userID) {
if (message.content === "!setrole") {
// Code for taking the list of all members with role xxxx.
// Code for assigning all those people to the role yyyy.
message.channel.send("Roles assigned");
}
}
});
Try this:
// iterate a function through all members of the guild
message.guild.members.cache.forEach((member) => {
if (member.roles.cache.has(roleID1) // if member has x role
member.roles.add(roleID2); // give y role
});
You could also use Array.prototype.filter(); although there's no difference in execution, it might be faster (but I really have no idea):
message.guild.members
.filter((member) => member.roles.cache.has(roleID1))
.forEach((member) => member.roles.add(roleID2))

Categories

Resources