Auto role when someone starts streaming - javascript

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

Related

add a role to a user discord.js

I am trying to make a command that gives a role to a member after I type power. I already have a mute command, and that one works completely fine, But if I copy that code and change the name of the command and the role it has to give, it gives the error:
TypeError: Cannot read property of 'roles' of undefined
my code is:
if(message.content.startsWith("power")) {
let role = message.guild.roles.cache.find(r => === "Role_ID");
let member = message.mentions.members.first();
member.roles.add(role)
}
You can try:
if(message.content.startsWith("power")) {
let role = message.guild.roles.cache.find(r => === "Role_ID");
let member = message.mentions.members.first();
member.addRole(role)
}

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

discord.js - Bot wont add role: TypeError: Cannot read property 'add' of undefined

I am making a Discord bot to moderate my server. I wanted to add a command that gives the author any role by using the command !role [role name].
I used this:
const member = message.author
const rle = message.content.split(/ +/).slice(1).join(' ');
const role1 = message.guild.roles.cache.find(role => role.name === `${rle}`);
try {
member.roles.add(role1);
} catch (e) {
message.author.send(${e});
}
It (given I spell the role correctly) returns the following error:
"TypeError: Cannot read property 'add' of undefined"
Does anyone know how I would fix this issue?
The author property does not have a roles property. This is a common mistake. message.author returns a User class, while message.member returns a GuildMember class.
All you have to do is change message.author to message.member and it'll work!
Try this:
const member = message.author
const rle = message.content.split(/ +/).slice(1).join(' ');
const role1 = message.guild.roles.cache.find(role => role.name === `${rle}`);
try
{
message.guild.member(member).roles.add(role1);
}
catch (e)
{
message.author.send(${e});
}

discord.js client.guilds.cache.get(role).members | Create a array with all members of a guild

I want to create an array with every user with a specific role. But I get the following error:
TypeError: Cannot read property 'members' of undefined
The code that I am currently using:
var role = receivedMessage.guild.roles.cache.find(role => role.name === "arole");
const guild = client.guilds.cache.get(role);
if (guild == "") {
console.log("guild not found");
} else {
const Members = client.guilds.cache.get(role).members.cache.map(member => member.id);
}
This code gets all members with a certain role in the server the message was sent in:
const guild = receivedMessage.guild;
if (!guild) return console.log("Couldn't get the guild.");
const members = guild.members.cache.filter(member => member.roles.cache.find(role => role.name === "arole")).map(member => member.id);
If you want to get all members with a certain role in a specific server, you can specify the guild ID:
const guild = client.guilds.cache.get(/* Guild ID */);
if (!guild) return console.log("Couldn't get the guild.");
const members = guild.members.cache.filter(member => member.roles.cache.find(role => role.name === "arole")).map(member => member.id);
For more information on valid properties and methods, please read the Discord.js docs.
Seems like the guild is non-existent or your bot doesn't have acccess to it, you can simply check this by doing something like
const guild = client.guilds.cache.get("335507048017952771");
if (!guild) return console.log("guild not found :(");
//also use the built-in array() method
console.log(guild.array());

Discord JS // Trying to add role by reacting to the message

bot.on('messageReactionAdd', async (reaction, user) => {
// Define the emoji user add
let role = message.guild.roles.find(role => role.name === 'Alerts');
if (message.channel.name !== 'alerts') return message.reply(':x: You must go to the channel #alerts');
message.member.addRole(role);
});
Thats the part of my bot.js. I want the user to react in a certain channel and receive role Alerts
You haven't really stated what the problem is, what works and what doesn't work but I'll take a wild stab at some parts which catch my eye.
For starters you are calling properties on the variable message whilst in the code you supplied, you didn't create/set a variable named message. My guess is that you want the message to which a reaction has been added. To do that you have to use the MessageReaction parameter which is supplied in the messageReactionAdd event as reaction.
From there you can replace message.<something> with reaction.message.<something> everywhere in the code you supplied.
Something also to note is that you add the role Alerts to message.member. This won't work how you want it to, since it will give the Alerts role to the author of the original message.
What (I think) you want to do, is fetch the user who just reacted with the emoji and assign them the Alerts role. You'll have to find the member in the guild first and then assign them the Alerts role. To do this you'll have to use the User parameter and find the correct Member because you can't add a role to a User object but you can to a Member object. Below is some code which should hopefully put you on the right track.
// Fetch and store the guild (the server) in which the message was send.
const guild = reaction.message.guild;
const memberWhoReacted = guild.members.find(member => member.id === user.id);
memberWhoReacted.addRole(role);
You are using message.member variable despite not defining message.
Any of these methods won't really work in v12 so I updated it for someone else searching.
If you find any mistakes be sure to make me aware of it.
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] }); //partials arent really needed but I woudld reccomend using them because not every reaction is stored in the cache (it's new in v12)
const prefix = "-";
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) { //this whole section just checks if the reaction is partial
try {
await reaction.fetch(); //fetches reaction because not every reaction is stored in the cache
} catch (error) {
console.error('Fetching message failed: ', error);
return;
}
}
if (!user.bot) {
if (reaction.emoji.id == yourEmojID) { //if the user reacted with the right emoji
const role = reaction.message.guild.roles.cache.find(r => r.id === yourRoleID); //finds role you want to assign (you could also user .name instead of .id)
const { guild } = reaction.message //store the guild of the reaction in variable
const member = guild.members.cache.find(member => member.id === user.id); //find the member who reacted (because user and member are seperate things)
member.roles.add(role); //assign selected role to member
}
}
})
Here's a quick answer, though way too late. So I'll be updating the answer with Discord.js v.12.x (or the same as Discord.js Master)
bot.on('messageReactionAdd', async (reaction, user) => {
//Filter the reaction
if (reaction.id === '<The ID of the Reaction>') {
// Define the emoji user add
let role = message.guild.roles.cache.find((role) => role.name === 'Alerts');
if (message.channel.name !== 'alerts') {
message.reply(':x: You must go to the channel #alerts');
} else {
message.member.addRole(role.id);
}
}
});

Categories