Bot assigns user a role, even if user doesn't own role - javascript

Sorry for the confusing title, I'll clarify. I'm trying to make the bot check if a user has a certain role in their quick.db inventory, and if they do, it'll equip that role. The problem I'm having is that even with the role in the inventory, it returns the error that the role isn't owned. I have a feeling that the problem is the if (db.has(message.author.id + '.hot rod red')) line, as I'm not too sure how to format checking for a role with quick.db. Sorry for the messy code, if anyone knows how to fix this let me know, thanks!
if (db.has(message.author.id + '.hot rod red')) {
if (message.member.roles.cache.some(role => role.name === 'hot rod red')) {
let embed = new Discord.MessageEmbed().setDescription('You already have this role equipped!');
return message.channel.send(embed);
} else {
await message.guild.members.cache.get(user.id).roles.add('733373020491481219');
let embed = new Discord.MessageEmbed().setDescription(`You now have the ${message.guild.roles.cache.get('733373020491481219')} role!`);
message.channel.send(embed);
user.roles.remove(user.roles.highest);
}
} else {
let embed = new Discord.MessageEmbed().setDescription('You do not own this role!'); // ERROR HERE; GIVES ROLE EVEN WITHOUT OWNING
return message.channel.send(embed);
}

Probably try something like
let check = db.get(message.author.id+'.hot rod red')
and check if it is true/false, I'd say to use string rather then boolean as you can use if(check === 'false/true'){}. You can also do
if(!check || check === 'false'){ return
let embed = new Discord.MessageEmbed().setDescription('You do not own this role!');
return message.channel.send(embed);
}
So the final code would be:
let check = await db.get(message.author.id + '.hot rod red');
let rejectEmbed = new Discord.MessageEmbed()
.setDescription('You do not own this role!');
if(!check){
return message.channel.send(rejectEmbed)
}
if(check === 'true'){
if (message.member.roles.cache.some(role => role.name === 'hot rod red')) {
let embed = new Discord.MessageEmbed().setDescription('You already have this role!');
return message.channel.send(embed);
} else {
await message.guild.members.cache.get(user.id).roles.add('733373020491481219');
let embed = new Discord.MessageEmbed().setDescription(`You now have the ${message.guild.roles.cache.get('733373020491481219')} role!`);
message.channel.send(embed);
user.roles.remove(user.roles.highest); // I'm unsure why this is here, this could be causing a potential error
}
}
If there are any more questions, please comment!! I hope this has helped.

Related

How do I get the users activity discord.js

Problem: I have been trying to add a "Activity" field to my info command, and its not working.
Expected result: Responds with the other stuff, along with the Activity field, showing what the user is doing.
Actual response: Shows everything else correctly, except the Activity field, which says undefined/null.
Code:
if (command == "info") {
const embed = new Discord.MessageEmbed()
let member = message.mentions.members.first() || message.guild.members.cache.get(args[1]) || message.guild.member(message.author)
const Roles = new Array()
message.guild.roles.cache.forEach(role => {
if (member.roles.cache.find(r => r.id == role.id)) {
Roles.push(role)
}
})
console.log(member.presence)
embed.setAuthor(user.tag, member.user.avatarURL())
embed.setTitle(`👋 Welcome to ${user.username}'s Profile!`)
embed.addField('#️⃣ Tag:', member.user.tag)
embed.addField('📡 Joined Guild at:', member.user.joinedAt)
embed.addField('💬 Joined Discord at:', member.user.cretedAt
)
if (!member.presence.activities) {
embed.addField('⚽️ Activity:', 'Not playing anything')
} else {
embed.addField('⚽️ Activity:', `${member.presence.activities.type} ${member.presence.activities.name}\n${member.presence.activities.details}\n${member.presence.activities.state}`)
}
embed.addField('📱 Platform:', member.presence.clientStatus)
embed.addField('🤖 Bot:', user.bot)
embed.addField('📜 Roles:', Roles.join(' | '))
embed.setFooter('Bot made with discord.js')
message.channel.send(embed)
}
Presence.activities is an array of Activity.
// Add check for empty activities array
if (!member.presence.activities || member.presence.activities.length == 0) {
embed.addField('⚽️ Activity:', 'Not playing anything')
} else {
const activity = member.presence.activities[0];
embed.addField('⚽️ Activity:', `${activity.type} ${activity.name}\n${activity.details}\n${activity.state}`);
}
Most of the time you will only need the first item of the array. Because you rarely see users with multiple activities.

Discord.js bot was working, added one extra command and everything broke. Can anyone help me figure out why?

Tried to venture in to the realm of making discord bots. Followed along with a fairly simple tutorial, tweaking it along the way to fit what I was trying to make. The bot originally worked, but I went back in to add the "Mistake" command, and suddenly it's not working. I added in console.log pretty much everywhere, trying to figure out how far everything was getting.
When I start the bot, it will spit out the "Bot Online" log. When I input a command, it will spit out the "Commands" log, but it won't register the command at all. I've tried looking for any minor typos, missing brackets, etc... but I just can't seem to figure out what's gone wrong. I'm hoping that someone here can help! Thank you!
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.on('ready', () => {
console.log('Bot Online');
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'goals';").get();
if (!table['count(*)']) {
sql.prepare('CREATE TABLE goals (id TEXT PRIMARY KEY, user TEXT, guild TEXT, goals INTEGER);').run();
sql.prepare('CREATE UNIQUE INDEX idx_goals_id ON goals (id);').run();
sql.pragma('synchronous = 1');
sql.pragma('journal_mode = wal');
}
//Statements to get and set the goal data
client.getGoals = sql.prepare('SELECT * FROM goals WHERE user = ? AND guild = ?');
client.setGoals = sql.prepare('INSERT OR REPLACE INTO goals (id, user, guild, goals) VALUES (#id, #user, #guild, #goals);');
});
client.on('message', (message) => {
if (message.author.bot) return;
let goalTotal;
if (message.guild) {
goalTotal = client.getGoals.get(message.author.id, message.guild.id);
if (!goalTotal) {
goalTotal = {
id: `${message.guild.id}-${message.author.id}`,
user: message.author.id,
guild: message.guild.id,
goals: 0,
};
}
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
console.log('Commands');
if (command === 'Goals') {
console.log('Goals');
return message.reply(`You Currently Have ${goalTotal.goals} Own Goals.`);
}
if (command === 'OwnGoal') {
console.log('Own Goal');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
userscore = {
id: `${message.guild.id}-${user.id}`,
user: user.id,
guild: message.guild.id,
goals: 0,
};
}
userscore.goals++;
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} has betrayed his team and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Mistake') {
console.log('Mistake');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
return message.reply('This person has no Rocket Bot activity.');
}
if (userscore === 0) {
return message.reply('This player currently has no goals.');
}
if (userscore > 0) {
userscore.goals--;
}
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} was falsely accused and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Leaderboard') {
console.log('Leaderboard');
const leaderboard = sql.prepare('SELECT * FROM goals WHERE guild = ? ORDER BY goals DESC;').all(message.guild.id);
const embed = new Discord.MessageEmbed()
.setTitle('Rocket Bot Leaderboard')
.setAuthor(client.user.username, client.user.avatarURL())
.setDescription('Total Goals Scored Against Own Team:')
.setFooter('Rocket Bot')
.setThumbnail('https://imgur.com/a/S9HN4bT')
.setColor('0099ff');
for (const data of leaderboard) {
embed.addFields({
name: client.users.cache.get(data.user).tag,
value: `${data.goals} goals`,
inline: true,
});
}
return message.channel.send({ embed });
}
if (command === 'RocketHelp') {
console.log('Help');
return message.reply(
'Rocket Bot Commands:' +
'\n' +
'!Goals - See How Many Goals You Have Scored Against Your Own Team' +
'\n' +
'!OwnGoal - Tag Another Player With # To Add One To Their Total' +
'\n' +
'!Mistake - Tag Another Player With # To Subtract One From Their Total' +
'\n' +
'!Leaderboard - Show The Current Leaderboard'
);
}
});
client.login(config.token);
You are improperly splitting the message content. You added g to the regex by accident.
Correct line:
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
Because of improper args split, it could not find any command at all, hence no console log was invoked after Commands.

Issues with autorole using Quick.db (Discord.js)

I'm trying to make an autorole code using quick.db, but it returns the error: UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes
My "setautorole" command:
const role = message.mentions.roles.first() || message.guild.roles.cache.get(args[0])
if(!role) return message.channel.send('I couldnt find the role')
db.set(`autorole`, role)
message.channel.send('The process worked fine!')
This is on index of bot:
client.on("guildMemberAdd", (member) => {
let few = db.get(`autorole_${member.guild.id}`)
if(few === null) return;
member.roles.add(few)
})
Well, I don't know what to do to fix this error, I need a little help
It's better just to save the role ID in Database
BTW you're doing it all wrong. It should be like
setautorole.js
const role = message.mentions.roles.first() || message.guild.roles.cache.get(args[0]);
if(!role){
return( message.channel.send('I couldnt find the role') );
}
db.set(`autorole_${message.guild.id}`, role.id);
message.channel.send('The process worked fine!');
index.js
client.on("guildMemberAdd", (member) => {
let roleID = db.get(`autorole_${member.guild.id}`)
if(!roleID) return;
role = member.guild.roles.find(roleID);
if(!role){
console.log("That role dosen't exist");
return (false);
}
member.roles.add(role)
})
Thanks for the idea Akio, but, i i did something like:
client.on("guildMemberAdd", (member) => {
let roleID = db.get(`autorole_${member.guild.id}`)
if(!roleID) return;
let role = member.guild.roles.cache.find(r => r.id === roleID);
if(!role){
console.log("That role dosen't exist");
return (false);
}
member.roles.add(role)
})
and worked, thanks for help :)

How can I make the bot ignore other actions made my other bots?

I want to know how I can make the bot ignore other bots actions (role update, removed) and stop logging them. Here is my code:
let messagechannel = oldMember.guild.channels.find(r => r.name === config.logsChannel);
if (!messagechannel) return 'Canalul respectiv nu există!'
if (oldMember.roles.size < newMember.roles.size) {
const embed = new Discord.RichEmbed()
.setColor('#383b3d')
.setDescription(`${oldMember.user.tag} (${oldMember.user}) a fost actualizat.`)
.setAuthor(`${oldMember.user.tag}`, oldMember.user.avatarURL)
.addField(`ID`, oldMember.id)
.setFooter(`${bot.user.tag}`, bot.user.avatarURL)
.setTimestamp();
for (const role of newMember.roles.map(x => x.id)) {
if (!oldMember.roles.has(role)) {
embed.addField(`Schimbări`, "➕ " + `${newMember.guild.roles.get(role)}`);
}
}
messagechannel.send(embed);
}
if (oldMember.roles.size > newMember.roles.size) {
const embed = new Discord.RichEmbed()
.setColor('#383b3d')
.setDescription(`${oldMember.user.tag} (${oldMember.user}) a fost actualizat.`)
.setAuthor(`${oldMember.user.tag}`, oldMember.user.avatarURL)
.addField(`ID`, oldMember.id)
.setFooter(`${bot.user.tag}`, bot.user.avatarURL)
.setTimestamp()
for (const role of oldMember.roles.map(x => x.id)) {
if (!newMember.roles.has(role)) {
embed.addField( `Schimbări`, "❌ " + `${oldMember.guild.roles.get(role)}`);
}
}
messagechannel.send(embed);
}
if (newMember.nickname != oldMember.nickname) {
const embed = new Discord.RichEmbed()
.setColor('#383b3d')
.setDescription(`${oldMember.user.tag} (${oldMember.user}) a fost actualizat.`)
.setAuthor(`${oldMember.user.tag}`, oldMember.user.avatarURL)
.addField(`ID`, oldMember.id)
.addField(`Numele vechi`, `${oldMember.displayName}`)
.addField(`Numele nou`, `${newMember.displayName}`)
.setFooter(`${bot.user.tag}`, bot.user.avatarURL)
.setTimestamp()
messagechannel.send(embed);
}
});
Can someone help me? I dont know much about these thing so I little code might come in handy.
There is a simple way to archive this with minor changes to your existing code.
The User property of GuildMember (newMember/oldMember) has a property bot
that returns a Boolean if that user is a bot user or not.
So what you could do is at this if (oldMember.user.bot || newMember.user.bot) return
to the very top of the code you just sent.
More information about the bot property you can find here

I am trying to make a discord.js avatar command, and the mentioning portion doesn't work correctly

I have an avatar command in my discord bot. When the user uses h.avatar, it outputs their avatar, which works fine. Whenever they try to use h.avatar #user, nothing happens.
Here is my code:
} if (message.content.startsWith(config.prefix + "avatar")) {
if (!message.mentions.users.size) {
const avatarAuthor = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(message.author.username)
.setImage(message.author.avatarURL)
message.channel.send(avatarAuthor);
let mention = message.mentions.members.first();
const avatarMention = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(mention.user.username)
.setImage(mention.user.avatarURL)
message.channel.send(avatarMention);
You have a check if (!message.mentions.users.size) { which makes the command run only if you do not mention somebody. You either need to use an else { in your code or do:
if (message.content.startsWith(config.prefix + 'avatar')) {
const user = message.mentions.users.first() || message.author;
const avatarEmbed = new Discord.RichEmbed()
.setColor(0x333333)
.setAuthor(user.username)
.setImage(user.avatarURL);
message.channel.send(avatarEmbed);
}
The const user = message.mentions.users.first() || message.author; tries to get the user that was mentioned but if it does not find anyone it will use the author's used.
This can also be used like this:
if (!message.mentions.users.size) {
message.channel.send('Nobody was mentioned');
return;
}
// continue command here, after guard clause
There's nothing like avatarUrl unless you have defined it.
Use this code to get the url of a user:
message.channel.send("https://cdn.discordapp.com/avatars/"+message.author.id+"/"+message.author.avatar+".jpeg");
Just replacemessage.author with the user who is mentioned
These is the updated version of the answer that works
if (message.content.startsWith(config.prefix + 'avatar')) {
const user = msg.mentions.users.first() || msg.author;
const avatarEmbed = new MessageEmbed()
.setColor(0x333333)
.setAuthor(`${user.username}'s Avatar`)
.setImage(
`https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=256`
);
msg.lineReply(avatarEmbed);
}
This uses discord's avatar url, and msg.lineReply(avatarEmbed); is a function that sends the embed as a reply to the message
My
if (msg.content.startsWith(prefix + 'avatar')) {
const user = msg.mentions.users.first() || msg.author;
const avatarEmbed = new MessageEmbed()
.setColor('')
.setAuthor(`${user.username}'s Avatar`)
.setImage(
`https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=256`
);
msg.reply(avatarEmbed);
}
if(message.content.startsWith(prefix+'av')){
if(message.mentions.users.size){
let member=message.mentions.users.first()
if(member){
const emb=new Discord.MessageEmbed().setImage(member.displayAvatarURL()).setTitle(member.username)
message.channel.send(emb)
}
else{
message.channel.send("Sorry none found with that name")
}
}else{
const emb=new Discord.MessageEmbed().setImage(message.author.displayAvatarURL()).setTitle(message.author.username)
message.channel.send(emb)
}
}
if (message.content.startsWith(prefix + 'avatar')) {
let user = message.mentions.users.first();
if(!user) user = message.author;
let color = message.member.displayHexColor;
if (color == '#000000') color = message.member.hoistRole.hexColor;
const embed = new Discord.RichEmbed()
.setImage(user.avatarURL)
.setColor(color)
message.channel.send({embed});
}

Categories