How to make Discord Bot Automatically Role Someone when they have certain word in status - discord

trying to make it so if someone for example put my discord servers invite in their status ".gg/testing" it would give them a role and if they removed it would take their role away heres the code i have got right now off a similar stack overflow post heres my code right now but it doesnt give the user there role when they have .gg/testing in their status any tips?
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const roleID = "972823139119685712";
client.on("presenceUpdate", async (_, newPresence) => {
const role = newPresence.guild.roles.cache.get(roleID);
const status = ".gg/testing";
const member = newPresence.member;
if (member.presence.activities[0].state?.includes(status)) {
return newPresence.member.roles.add(role);
} else {
if (member.roles.cache.has(role)) {
newPresence.member.roles.remove(role);
}
}
});
client.login("");

This is the code you're looking for. Credit to HellCatVN whose code I edited a tiny bit to make this work.
client.on('presenceUpdate', async (oldPresence, newPresence) => {
const role = newPresence.guild.roles.cache.get("941814488917766145");
const member = newPresence.member
const activities = member.presence.activities[0];
if (activities && (activities.state.includes( ".gg/testing" ) || activities.state.includes("discord.gg/testing" ))) {
return newPresence.member.roles.add(role)
} else {
if(member.roles.cache.get(role.id)) {
newPresence.member.roles.remove(role)
}
}
})
The role will be gone if the user turns on invisible status too.

Related

DiscordJs v14 create a message error includes

I don't understand why i have this error i want create a bot for add role if a people write link in description but the code don't want get my includes
`
const { Client, GatewayIntentBits, Collection } = require('discord.js');
const config = require('./config');
const bot = new Client({
intents: [3276799]
});
bot.commands = new Collection()
require('./src/Structure//Handler/Event')(bot);
require('./src/Structure//Handler/Command')(bot);
bot.on('presenceUpdate', async (oldPresence, newPresence) => {
const role = newPresence.guild.roles.cache.get("1048286446345261137");
const member = newPresence.member
const activities = newPresence.activities[0];
if (activities && (activities.state.includes(".gg/slayde" ) || activities.state.includes(".gg/slayde"))) {
return newPresence.member.roles.add(role)
} else {
if(member.roles.cache.get(role.id)) {
newPresence.member.roles.remove(role)
}
}
})
bot.login(config.clients.token);
`
The error
TypeError: Cannot read properties of null (reading 'includes')
I try to fix but i'm blocked
According to the docs, the state property of Activity is optional (?string), which means it doesn't always have a value. You have to make sure it exists before you call includes() on it.
if (activities && activities.state && (activities.state.includes(".gg/slayde" ) || activities.state.includes(".gg/slayde"))) {
// etc
}

How to get active member count Discord JS

I have a function which counts all active members on active server
I've tried to get into client.guilds.cache then filter users by their presence.status to check if the user is online. As far as I am aware what's happening .size should return a number of active members on the server, but instead it returns 0, no matter what I try.
Here's the code I've tried
I call function in client.on here and pass client as an argument
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers],
});
client.on("ready", () => {
activeMembersCounter(client)
});
Then in activeMembersCounter.ts
function activeMembersCounter(client: Client<boolean>): void {
const guild = client.guilds.cache.get(config.GUILD_ID);
const onlineMembers = guild.members.cache.filter((m) => m.presence?.status === "online"&& !member.user.bot).size;
console.log(onlineMembers) // logs 0
}
I've also tried async version with fetch
async function activeMembersCounter(client: Client<boolean>): Promise<void> {
const guild = client.guilds.cache.get(config.GUILD_ID);
const onlineMembers = (await guild.members.fetch()).filter((member) => member.presence?.status === "online" && !member.user.bot);
console.log(onlineMembers.size);
}
I'm not 100% sure if my approach is correct here. I would love to get some advice :)
Two things you need to change.
Use the GatewayIntentBits.GuildPresences flag, m.presence returns null if you don't use it.
member is undefined in your online members variable. Use m.user.bot instead of member.user.bot.
Working code:
const { GatewayIntentBits, Client} = require('discord.js');
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildPresences],
});
function activeMembersCounter(c) {
const guild = c.guilds.cache.get("GUILD_ID");
console.log(guild);
const onlineMembers = guild.members.cache.filter((m) => m.presence?.status == "online" && !m.user.bot).size;
console.log(onlineMembers);
}
client.once('ready', () => {
activeMembersCounter(client);
})
Edit: If you're looking for active members, this could include DND members and Idle members. You might want to consider using m.presence?.status != "offline" instead of m.presence?.status == "online" to include these other statuses in your count.

Want a code that detects custom status and gives the person a role on discord

I am trying to make a code that searches a custom status for the phrase ".gg/RoundTable" and will then give the person a certain role I have in my server.
Here is my code so far , the code runs with no errors but it will not assign the role.
const Discord = require("discord.js")
const client = new Discord.Client()
const mySecret = process.env['TOKEN']
client.login(mySecret)
const roleID = 865801753462702090
client.on('presenceUpdate', async (oldPresence, newPresence) => {
const role = newPresence.guild.roles.cache.find(role => role.name === 'Pic Perms (.gg/RoundTable)');
const status = ".gg/RoundTable"
const member = newPresence.member
console.log(member.user.presence.activities[0].state)
if(member.presence.activities[0].state.includes(status)){
return newPresence.member.roles.add(roleID)
} else {
if(member.roles.cache.has(roleID)) {
newPresence.member.roles.remove(roleID)
}
}
})
Try this:
const Discord = require("discord.js");
const client = new Discord.Client();
const roleID = "851563088314105867";
client.on("presenceUpdate", async (_, newPresence) => {
const role = newPresence.guild.roles.cache.get(roleID);
const status = ".gg/RoundTable";
const member = newPresence.member;
if (member.presence.activities[0].state?.includes(status)) {
return newPresence.member.roles.add(role);
} else {
if (member.roles.cache.has(role)) {
newPresence.member.roles.remove(role);
}
}
});
client.login("your-token");
I'd recommend finding your role in the RoleManager.cache using get() as you already have the roleID and then actually assign that role instead of the roleID. Note I added an optional chaining operator since if a user does not have a custom status .state will be null.

Discord.JS - Find if a user has a role

I'm doing the most basic mute command ever, and I need to find if the user has a role called 'Muted'
I've added the code below, but I keep getting an error.
if (command === "mute") {
const { member, mentions } = message
const mutee = message.mentions.users.first();
const muter = message.author
console.log(mutee)
if(member.hasPermission('ADMINISTRATOR')) {
let muteRole = message.guild.roles.cache.find(role => role.name === "Muted");
if (message.guild.members.get(mutee.id).roles.cache.has(muteRole.id)) {
message.channel.send(new MessageEmbed() .setTitle(`Uh Oh!`) .setDescription(`${mutee.user} already has been Muted!`))
}
else {
}
}
}
First, I recommend you to get the mentioned member directly instead of the user with const mutee = message.mentions.members.first();. (If you are using the command under a Guild Channel)
Then, you can simply check if he has the role with:
if (mutee.roles.cache.has(muteRole.id))

How can I send an announcement of a specific role change to a specific channel?

I'd like to notify our main chat channel when a role has changed for someone, a specific role though -- how can I do this?
I hope I understood your question well. You have to use the guildMemberUpdate event to check if the roles are still the same if the event gets triggered. Then, you have to run a simple for loop and check which roles have been removed or assigned from the guildMember.
Here is the code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildMemberupdate', (oldMember, newMember) => {
const messagechannel = oldMember.guild.channels.find(r => r.name === 'Name of the channel where the announcement should be sent');
if (!messagechannel) return 'Channel does not exist!';
if (oldMember.roles.size < newMember.roles.size) {
const embed = new Discord.RichEmbed()
.setColor('ORANGE')
.setTimestamp()
.setAuthor('Role assigned')
.addField(`📎 Member:`, `${oldMember.user.tag} (${oldMember.id})`);
for (const role of newMember.roles.map(x => x.id)) {
if (!oldMember.roles.has(role)) {
embed.addField(`📥 Role(s):`, `${oldMember.guild.roles.get(role).name}`);
}
}
messagechannel.send({
embed
});
}
if (oldMember.roles.size > newMember.roles.size) {
const embed = new Discord.RichEmbed()
.setColor('ORANGE')
.setTimestamp()
.setAuthor('Role removed')
.addField(`📎 Member`, `${oldMember.user.tag} (${oldMember.id})`);
for (const role of oldMember.roles.map(x => x.id)) {
if (!newMember.roles.has(role)) {
embed.addField(`📥 Role(s):`, `${oldMember.guild.roles.get(role).name}`);
}
}
messagechannel.send({
embed
});
}
});

Resources