Want a code that detects custom status and gives the person a role on discord - 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.

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 make Discord Bot Automatically Role Someone when they have certain word in status

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.

ServerInfo DiscordJS Issue

My issue here is when I execute the command the owner is only undefined instead of the actual owner of the server. How can I fix this issue?
module.exports.run = async (client, message, args) => {
const { MessageEmbed } = require('discord.js');
message.delete();
const guild = message.guild;
const Emojis = guild.emojis.cache.size || "No Emoji!";
const Roles = guild.roles.cache.size || "No Roles!";
const Members = guild.memberCount;
const Humans = guild.members.cache.filter(member => !member.user.bot).size;
const Bots = guild.members.cache.filter(member => member.user.bot).size;
const owner = guild.owner.user.tag
const embed = new MessageEmbed()
.setTitle(guild.name + " Information!")
.setColor("2F3136")
.setThumbnail(guild.iconURL())
.addField(`Name`, `${guild.name}`, true)
.addField(`Owner`, `${owner}`, true)
.addField(`ID`, `${guild.id}`, true)
.addField(`Roles Count`, `${Roles}`, true)
.addField(`Emojis Count`, `${Emojis}`, true)
.addField(`Members Count`, `${Members}`, true)
.addField(`Humans Count`, `${Humans}`, true)
.addField(`Bots Count`, `${Bots}`, true)
.addField(`Server Created At`, guild.createdAt.toDateString())
.setFooter(`Requested by ${message.author.username}`)
.setTimestamp();
message.channel.send({ embeds: [embed] });
}
module.exports.config = {
name: "serverinfo",
aliases: [""]
}
I'm pretty sure that there isn't an owner property in a Guild. To get the owner you have two methods:
Method 1 is using the .fetchOwner() method of a Guild
const owner = await message.guild.fetchOwner().user.tag
Method 2 is getting the owner id and then fetching the user from guild.members:
const owner = message.guild.members.cache.get(message.guild.ownerId)
You can choose which method is better for you

A code to add a role to all members of the server

const { MessageEmbed } = require('discord.js')
module.exports = {
name: "addrole",
aliases: ["role", "P!role"],
category: "moderation",
description: "Add role to any user",
run: async (client, message, args) => {
if (!message.member.hasPermission("MANAGE_ROLES")) {
return message.channel.send("sorry you need permission to mute someone");
}
if (!message.guild.me.hasPermission("MANAGE_ROLES")) {
return message.channel.send("I do not have the permissions");
}
const targets = message.mentions.members;
if(!targets.first()) return message.reply(`<:no:677902165859237894>please mention user!`)
let arole = message.mentions.roles.first();
if(!arole) return message.reply(`<:no:677902165859237894>please mention role for add!`)
const embed = new MessageEmbed()
.setColor("RANDOM")
.setDescription(`<a:ok_:731369076315652167>role added ${arole}`)
await message.channel.send(embed)
targets.forEach(target => target.roles.add(arole));
}
}
This adds role to the mentioned users.
Instead is there a way to alter
const targets = message.mentions.members
Such that the targets are all server members? And then by foreach, I can give the role to all the targets.
You could access all guild members from message.guild.members.cache and use .forEach().

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