I am trying to use the discord API to make a bot that its going to create a role and add a person to it. I'm not sure why my code isn't working.
async function role(message){
try {
let guild = client.guild.get(236824834066219009);
guild.roles.create({
data:{
name:"asd",
color:"grey",
},
reason:"asd",
})
let role = message.guild.roles.find(r => r.name === "asd");
let user = 236824834066219009;
await user.addrole(role).catch(console.error);
} catch (error) {
console.log(error);
}
}
The reason why your code is not working is because since discord.js v12 there have been a lot of changes.
You can't use .find() on roles anymore you have to access their cache first so you need to replace let role = message.guild.roles.find(r => r.name === "asd"); with let role = message.guild.roles.cache.find(r => r.name === "asd");
You also can't add roles using addrole(), you need to use roles.add() so you need to replace user.addrole(role) with user.roles.add(role)
You can also make your code more efficient by not having to find the role, you can just use .then() to add the role to the user, which you can also pass through as a parameter in your function along with the guild, like so:
async function role(message, user, guild){
try {
guild.roles.create({
data:{
name:"asd",
color:"grey",
},
reason:"asd",
}).then((role) => user.roles.add(role)).catch(console.error);
} catch (error) {
console.log(error);
}
}
Related
I'm creating a Christmas bot for my server. A private bot and I wonder how I can make it so that the bot checks every hour if a user has certain emojis in their guild username. If they do, they will get the Christmas role and if they don't have certain emojis, they won't get the role of course.
But it also needs to remove immediately if someone removes the emojis from their nickname. How can I do that?
This is what I have this far:
let roleKerst = fs.readFileSync('./database/role.txt').toString();
client.once('ready', () => {
const userArray = client.guilds.cache.get(guild).members.fetch()
function nieuweFunctie(){
if (roleKerst == 'aan') {
//const user2 = userArray?.nickname
// userArray.forEach(user34 => {
// const user2 = user34.nickname
// console.log('nickname', user2)
// })
Array.prototype.forEach.call(userArray, userKip => {
console.log(userKip)
});
let nicknameEmoji = userKip.nickname
//const user2 = userArray.nickname
//console.log('nickname', user2)
if (nicknameEmoji.includes('🎄') || nicknameEmoji.includes('🎅')) {
//client.members.roles.add('1042423440264663160')
console.log('They have the emoji in their name')
} else if (!nicknameEmoji.includes('🎄') || !nicknameEmoji.includes('🎅')) {
//client.members.roles.remove('1042423440264663160')
console.log('They do not have the emoji in their name')
}
//})
console.log('timer is working')
} else {
console.log('timer is off')
}
}
setInterval(nieuweFunctie, 10000)
});
setInterval is definitely not something you want to use for this.
You should use the guildMemberUpdate event for this. Don't forget that you'll need the Guilds, GuildMembers and GuildPresences intents for this to fire.
The callback function will take two parameters; the oldMember is the first one and the newMember is the second one. You can use these two objects to check what changes the member made.
For example, you can check if the oldMember's nickname included any of the emojis. If it included and newMember's nickname doesn't have any of them, you know that they removed it from their nickname.
To check if they added an emoji, you'll check if the oldMember doesn't have any and if the newMember has at least one of them. You can use the Array#some method for this.
See the example below. It does exactly what you wanted.
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildPresences,
],
});
client.on('guildMemberUpdate', async (oldMember, newMember) => {
// if member hasn't changed their nickname, just exit early
if (oldMember.nickname === newMember.nickname) return;
const christmasEmojis = ['🎄', '🎅'];
const CHRISTMAS_ROLE_ID = 'YOUR ROLE ID HERE';
const userTag = newMember.user.tag;
const hasChristmasRole = newMember.roles.cache.has(CHRISTMAS_ROLE_ID);
const isEmojiAdded =
!christmasEmojis.some((emoji) => oldMember.nickname?.includes(emoji)) &&
christmasEmojis.some((emoji) => newMember.nickname?.includes(emoji));
const isEmojiRemoved =
christmasEmojis.some((emoji) => oldMember.nickname?.includes(emoji)) &&
!christmasEmojis.some((emoji) => newMember.nickname?.includes(emoji));
console.log(`ℹ ${userTag} has changed their nickname from ${oldMember.nickname} to ${newMember.nickname}`);
if (isEmojiAdded) {
console.log(`ℹ ${userTag} has added a Christmas emoji to their nickname`);
if (hasChristmasRole)
return console.log(`ℹ ${userTag} already has the Christmas role`);
try {
await newMember.roles.add(CHRISTMAS_ROLE_ID);
return console.log(`ℹ ${userTag} now has the Christmas role`);
} catch (error) {
console.log('Error adding role to member', error);
}
}
if (isEmojiRemoved) {
console.log(`ℹ ${userTag} has removed a Christmas emoji from their nickname.`);
if (!hasChristmasRole)
return console.log(`ℹ ${userTag} doesn't have the Christmas role`);
try {
await newMember.roles.remove(CHRISTMAS_ROLE_ID);
return console.log(`ℹ ${userTag} now doesn't have the Christmas role`);
} catch (error) {
console.log('Error removing role from member', error);
}
}
});
If you want to check all this on the ready event, you'll need to fetch all members and iterate over the returned collection using Collection#each:
const members = await client.guilds.cache.get(guild)?.members.fetch();
members.each(member => {
if (christmasEmojis.some((emoji) => member.nickname?.includes(emoji)))
// check if the member has the role and/or add it
if (!christmasEmojis.some((emoji) => member.nickname?.includes(emoji)))
// check if the member has the role and/or remove it
});
So what's going on is that I'm trying to make a set role/set channel command for logs and a mute role to mute people with and I'm wondering how to do this. I have looked at the docs and other stackoverflow threads and it still doesn't work.
if(!args[1]) return message.channel.send('Please specify a arg')
let roleName = args.slice(2).join(" ");
var role = message.guild.roles.cache.find(role => role.name === roleName)
if(!role){
message.channel.send("Thats not a role!")
}
if(role){
await GuildConfigSchema.update({ Guild: message.guild.id }, { MuteRole: role })
message.channel.send(`The mute role is now ${role}`)
}
First you can use if(role){ } else { } something like that and second on comments you said when I ping it for your code ping will not work because you use role.name if you want to catch role with ping then use let role = message.mentions.roles.first();
This is the current code that I have, I would like to make it where if you have a certain role then you can bypass the cooldown, also if anyone knows how to make a command that restricts a certain command to a certain channel, instead of having this really long message.channel.id.
const Discord = require('discord.js');
const fetch = require('node-fetch');
const talkedRecently = new Set();
module.exports.run = async(client, message, args, queue, searcher, ) => {
if (talkedRecently.has(message.author.id)) {
message.channel.send("Wait 1 minute before getting typing this again. " +'<#'+ message.author.id + '>');
} else {
switch(args[0].toLowerCase()){
case 'neko':
if(message.channel.id === '739002385531404288'||
message.channel.id === '646849145289834506'||
message.channel.id === '785079847763574794'||
message.channel.id === '782891383361896469'||
message.channel.id === '784417039425994772'){
fetch('https://nekos.life/api/v2/img/lewd')
.then(res => res.json())
.then(json => {
let nekoEmbed = new Discord.MessageEmbed()
.setTitle('Lewd Nekos! (=^・ω・^=)')
.setImage(json.url)
message.channel.send(nekoEmbed)
})
}else{
return}}
talkedRecently.add(message.author.id);
setTimeout(() => {
talkedRecently.delete(message.author.id);
}, 60000);
}
}
module.exports.config = {
name: "hentai",
aliases: ['ht']
}
```
Answering Your First Question:
Simply check if the member has a certain role. If they do, construct your if statement so that it will not fire if they have that role
Make sure to use message.member when checking roles
if (talkedRecently.has(message.author.id) && !message.member.roles.cache.has('bypass role id here')) {
// Your cooldown message
}
Learn more about Roles#has
Answering your 2nd question:
You can have an array of channel id's then use includes to check if any of the id's in the array match the current channel id
const ids = ['id1', 'id2', 'id3', 'id4'] // And so on
if (ids.includes(message.channel.id)) {
// Your Code
}
Learn more about Array.prototype.includes
I have a problem adding a custom role to a user. The command should look like this: ${prefix}addrole #user <role name>. The user should receive a custom role and the bot should send a confirmation message. This is my code:
client.on('message', (message) => {
if (message.content.startsWith(`${prefix}addrole`)) {
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermissions('MANAGE_MEMBERS'))
return message.reply("You don't have acces!");
const rMember =
message.guild.member(message.mentions.user.first()) ||
message.guild.members.get(args[0]);
if (!rMember) return message.reply("I couldn't find that user!");
const role = args.join(' ').slice(22);
if (!role) return message.reply('Please type a role!');
const gRole = message.guild.roles.find(`name`, role);
if (!gRole) return message.reply("I couldn't find that role!");
if (nMember.roles.has(gRole.id));
await nMember.addRole(gRole.id);
try {
nMember.send(`You received ${gRole.name}`);
} catch (e) {
message.channel.send(
`The user <#${rMember.id}>, received the role ${gRole.name}. We tried to dm him but he disabled them.`
);
}
};
module.exports.help = {
name: 'addrole',
};
}
});
The first problem I found comes from these two lines:
if(nMember.roles.has(gRole.id));
await(nMember.addRole(gRole.id));
First of all:
await is not a function, and thus you don't need parentheses. If you do put parentheses, you will get an error. Instead, just use:
await nMember.addRole(gRole.id)
Second of all:
GuildMember.roles.has is deprecated. discord.js v12+ uses Managers, so you will have to add the cache property. Write:
if (nMember.roles.cache.has(gRole.id))
This also applies to a line further up in the code:
let gRole=message.guild.roles.find(`name`, role);
Replace that with
let gRole = message.guild.roles.cache.find(r => r.name = role)
Third of all:
This issue is also seen in the second line of code I quoted:
await nMember.addRole(gRole.id)
addRole() is also deprecated, instead use:
await nMember.roles.cache.add(gRole.id)
Fourth of all, and I barely caught this:
MANAGE_MEMBERS is no longer a permission flag. Instead, use MANAGE_ROLES.
Overall the code could be cleaned up a bit, but I think that's all the errors I found.
So I have this inside my main index.js to check for any blacklisted users to prevent them from joining if they tried to join back again.
bot.on("guildMemberAdd", member => {
if(member.user.bot)
if (!db.get("blacklist_users").find({ user_id: member.id }).value()) {
return;
} else {
member.ban();
member.send("**You are blacklisted.**")
}
})
bot.on('message', message => {
let member = message.author;
if(!db.get("blacklist_users").find({ user_id: member.id }).value()) {
return;
}else {
member.ban();
member.send("**You are blacklisted.**")
}
})
Always be sure to check the API documentation for types. In this case, message.author returns a User object, not a GuildMember object. User does not have a ban function because it isn't associated with a guild. If you need the member object you will need to retrieve it from the member property.
let member = message.member;
Just be wary that this may be undefined if the message did not originate in a guild (i.e. Direct Message) or the member has left the guild before it is executed.
So i got it solved now by moving the code to my event instead of leaving it in the main file. And of course i had to define some other stuff in order to read where the blacklisted user is.
if (!db.get("blacklist_users").find({ user_id: member.id }).value()) {
return;
} else {
member.ban()
console.log(`User "${member.user.username}" has joined tried to join "${member.guild.name} and is probably blacklisted` )
}
i hope this will help you guys