Quick.db unwarn command unwarns all the warns in a member - discord.js

I am coding my own discord bot, and making warn system with quick.db package, and having a problem. If I warn a person 2 times, and unwarn him, It removes all the warns of the user. The code is:
//I have imported discord.js and others. This is only the part of warn and unwarn command.
if(command === "warn" ) {
const db = require('quick.db')
const Wuser = message.mentions.users.first();
const member = message.guild.member(Wuser)
if(!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("You dont have the permission to warn anyone").then(msg => {
msg.delete({ timeout: 10000 })
})
if (!Wuser) return;
if(Wuser.id === message.author.id) return message.channel.send("You cant warn yourself").then(msg => {
msg.delete({ timeout: 10000 })
})
if(Wuser.id === client.user.id) return message.channel.send("You cant warn me").then(msg => {
msg.delete({ timeout: 10000 })
})
db.add(`warn.${Wuser.id}`, 1);
const data = db.get(`warn.${Wuser.id}`);
if(data === undefined ) {
let data = 0
}
message.channel.send(`${Wuser} you are warned. Additional infractions may result in a mute. You have ${data} warns.`)
logchannel.send(`${Wuser} is warned. He have ${data} warns. He is warned by ${message.author}.`)
blogchannel.send(`${Wuser} is warned. He have ${data} warns. He is warned by ${message.author}.`)
}
if(command === "unwarn" ) {
if(!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("You dont have the permission to unwarn anyone").then(msg => {
msg.delete({ timeout: 10000 })
})
const db = require('quick.db')
let Wuser = message.mentions.users.first();
let member = message.guild.member(Wuser)
if (!Wuser) return;
if(Wuser.id === message.author.id) return message.channel.send("You cant unwarn yourself").then(msg => {
msg.delete({ timeout: 10000 })
})
if(Wuser.id === client.user.id) return message.channel.send("You cant unwarn me").then(msg => {
msg.delete({ timeout: 10000 })
})
db.delete(`warn.${Wuser.id}`)
const data = db.get(`warn.${Wuser.id}`)
message.channel.send(`${Wuser} is unwarned. 👍`)
logchannel.send(`${Wuser} is unwarned by ${message.author}.`)
blogchannel.send(`${Wuser} is unwarned by ${message.author}.`)
}
if(command === "userlog") {
if(!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("Why are you looking other's user log?").then(msg => {
msg.delete({ timeout: 10000 })
})
let Wuser = message.mentions.users.first()
let member = message.guild.member(Wuser)
if (!Wuser) return message.channel.send("User not specified").then(msg => {
msg.delete({ timeout: 10000 })
})
const db = require('quick.db')
const data = db.get(`warn.${Wuser.id}`)
let logEmbed = new MessageEmbed()
.setTitle(`Log of ${Wuser.tag}`)
.setDescription(`${Wuser} currently have ${data} warns.`)
.setThumbnail(member.user.displayAvatarURL)
message.channel.send(logEmbed)
logchannel.send(`${message.author.tag} used **.userlog** command.`)
}
What I have to edit the code? Thanks in advance.

In the unwarn command
db.delete(`warn.${Wuser.id}`)
Instead of this add to the db
db.add(`warn.${Wuser.id}`, -1);
or subtract from the value
db.subtract(`warn.${Wuser.id}`, 1);

Related

How to use collector in giveaway command

I'm making a giveaway command for my server, all from my knowledge without following a tutorial.
I'm running into an issue. I don't know how to use the collector's information to determine if there is enough reactions or not, and to get a winner.
My code:
const filter = (reaction, user) => {
return reaction.emoji.name === '🎉' && user.id === message.author.id;
};
const collector = message.createReactionCollector({ filter, time: duration });
collector.on('collect', (reaction, user) => {
console.log(`Collected ${reaction.emoji.name} from ${user.tag}`);
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} items`);
});
setTimeout(() => {
if (collector <= 1) {
message.channel.send("Not enough people reacted for me to draw a winner")
return}
let winner = (m) => m.reaction.cache.get("🎉").users.cache.filter((u) => !u.bot).random();
channel.send(`Congratulations ${winner} You just won the **${prize}**!`
);
}, duration );
Any help please? Thank you!

Cant get the reactions to recognise on a specific message now

In a pervious post I was having issues getting the bot to recognise reactions and the fix worked however and then changed it to react on a message that the bot says afterwards and now it isnt working again, I have tried changing the user condition so its the original command author but that didn't seem to work
So you run the code and it makes the embed perfectly and reacts to it however it doesnt recognise when you react and makes the timeout message
exports.run = async (client, message, args) => {
message.delete()
const MINUTES = 5;
const questions = [
{ answer: null, field: 'placeholdquestion' },
{ answer: null, field: 'placeholdquestion' },
{ answer: null, field: 'placeholdquestion' },
]; //to add more questions just add another line of the above code {answes: null, field: `Question Here`}
let current = 0;
const commanduser = message.author.id
// ...
// wait for the message to be sent and grab the returned message
// so we can add the message collector
const sent = await message.author.send(
`${questions[current].field}`,
);
const filter = (response) => response.author.id === message.author.id;
// send in the DM channel where the original question was sent
const collector = sent.channel.createMessageCollector(filter, {
max: questions.length,
time: MINUTES * 60 * 1000,
});
// fires every time a message is collected
collector.on('collect', (message) => {
//if (questions > 1 && questions < 10) {
// add the answer and increase the current index HERE
questions[current++].answer = message.content;
const hasMoreQuestions = current < questions.length; //change to be an imput of how many questions you want asked
if (hasMoreQuestions) {
message.author.send(
`${questions[current].field}`,
);
}
});
// fires when either times out or when reached the limit
collector.on('end', (collected, reason) => {
if (reason === 'time') {
return message.author.send(
`I'm not saying you're slow but you only answered ${collected.size} questions out of ${questions.length} in ${MINUTES} minutes. I gave up.`,
);
}
const embed = new MessageEmbed()
.setTitle("LOA Request")
.addFields(
{ name: 'placehold', value: questions[0].answer+'/10' },
{ name: 'placehold', value: questions[1].answer+'/10' },
{ name: 'placehold', value: questions[2].answer+'/10', inline: true },)
.setColor(`#1773BA`)
.setTimestamp()
.setThumbnail("https://media.discordapp.net/attachments/772915309714735205/795378037813805126/mvg_clean_2.png")
.setFooter("request by: " + message.author.tag);
;
message.channel.send(embed)
.then(function (message) {
message.react("👍")
message.react("👎")})
const filter = (reaction, user) => {
return ['👍', '👎'].includes(reaction.emoji.name) && user.id === commanduser; //changed to try and fix it didnt work as message.author.id or this
};
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] } )
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') {
message.channel.send('you reacted with a thumbs up.');
}
else {
message.reply('you reacted with a thumbs down.');
}
})
.catch(collected => {
console.log(`After a minute, only ${collected.size} out of 4 reacted.`);
message.reply('you didn\'t react with neither a thumbs up, nor a thumbs down.');
});
});
;
}
You have a slight logic error. You need to fit the code from your second filter to the message.awaitReactions inside of your message.channel.send(embed).then(function (message)...) method. In your code, the bot is trying to check for reactions from the original message, which you already deleted (since the awaitReactions is outside the scope of your function where you send and react to the embed).
Like this:
message.channel.send(embed)
.then(function (message) {
message.react("👍")
message.react("👎")
const filter2 = (reaction, user) => {
return ['👍', '👎'].includes(reaction.emoji.name) && user.id === commanduser;
};
message.awaitReactions(filter2, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') {
message.channel.send('you reacted with a thumbs up.');
}
else {
message.reply('you reacted with a thumbs down.');
}
})
.catch(collected => {
console.log(`After a minute, only ${collected.size} out of 4 reacted.`);
message.reply('you didn\'t react with neither a thumbs up, nor a thumbs down.');
});
})

So I am trying to ask a question to retrieve a mentioned channel but doesn't work

So I am trying to make my giveaway bot but can't make a create command so the person can add more details about the giveaway! Thus, I need questions but everytime I try it never goes well!
message.channel.send("Please mention the channel you want the giveaway to be in! **e.g #channel**");
try {
let msgs = await message.channel.awaitMessages(u2=>u2.author.id===message.author.id, { time: 15000, max: 1, errors: ["time"]});
if(parseInt(msgs.first().content)==mention.channel) {
const Channel = message.mentions.channels.first();
await Channel.send("HEY")
}
else {
message.channel.send("You did not mentioned a channel!");
}
}catch(e) {
return message.channel.send("Command Cancel!")
}
It either returns to the catch(e) line or "You did not mentioned a channel!"!
This should be what you want i think. (works with mentioning the channel, providing a channel ID or providing a channel name)
message.channel.send("Please mention the channel you want the giveaway to be in! **e.g #channel**");
let channel;
let response;
try {
response = await message.channel.awaitMessages(msg => msg.author.id === message.author.id, { max: 1, time: 1000*60*3, errors: ['time'] })
} catch {
return message.channel.send("Command Cancel!")
}
if (response.first().mentions.channels.first()) {
channel = response.first().mentions.channels.first()
} else if (!isNaN(response.first().content) && message.guild.channels.cache.get(response.first().content)) {
channel = message.guild.channels.cache.get(response.first().content)
} else if (isNaN(response.first().content) && message.guild.channels.cache.find(c => c.name.toLowerCase() === response.first().content.toLowerCase())) {
channel = message.guild.channels.cache.find(c => c.name.toLowerCase() === response.first().content.toLowerCase())
}
if (channel) {
await channel.send("HEY")
} else {
return message.channel.send("You did not mentioned a channel!");
}

Discord.js command handler problems

I've been trying to fix a command handler for 3 hours now, but anytime I try to add a custom command nothing happens. It loads the command, but when the command is run it does nothing. Here's some code:
index.js:
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
console.log(`[LOG] Loaded command ${file}`);
client.commands.set(command.name, command);
}
commands/kick.js:
const fs = require('fs');
var moment = require('moment');
var logger = fs.createWriteStream(`./logs/${moment().format('MM-DD-YYYY')}.log`, {
flags: 'a'
});
module.exports = {
name: "kick",
category: "moderation",
description: "Kicks the mentioned user.",
usage: "<imputs>",
run: (client, message, args) => {
let reason = args.slice(1).join(' ');
let user = message.mentions.users.first();
if (message.mentions.users.size < 1) return message.reply('You must mention someone to kick them.').then(msg => { msg.delete(10000) }).catch(console.error);
if (user.id === message.author.id) return message.reply("You cannot kick yourself.").then(msg => { msg.delete(10000) });
if (user.id === client.user.id) return message.reply("You cannot kick me.").then(msg => { msg.delete(10000) });
if (!message.member.hasPermission("KICK_MEMBERS")) return message.reply("You don't have the **Kick Members** permission!").then(msg => { msg.delete(10000) });
if (reason.length < 1) reason = 'No reason supplied';
if (!message.guild.member(user).kickable) return message.reply('I could not kick that member').then(msg => { msg.delete(10000) });
message.delete();
message.guild.member(user).kick();
const embed = new Discord.RichEmbed()
.setColor(0x0000FF)
.setTimestamp()
.addField('Action:', 'Kick')
.addField('User:', `${user.username}#${user.discriminator} (${user.id})`)
.addField('Moderator:', `${message.author.username}#${message.author.discriminator}`)
.addField('Reason', reason)
.setFooter(`© NetSync by Towncraft Developers`);
let logchannel = message.guild.channels.find('name', 'logs');
if (!logchannel){
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}.`).then(msg => { msg.delete(10000) });
logger.log(`[LOG] [KICK] ${user.username}#${user.discriminator} (${user.id}) was kicked by ${message.author.username}#${message.author.discriminator}.`);
}else{
message.channel.send(`Successfully kicked ${user.username}#${user.discriminator}. I\'ve also logged the kick in <#${logchannel.id}>.`).then(msg => { msg.delete(10000) });
client.channels.get(logchannel.id).send({embed});
}
if(user.bot) return;
return message.mentions.users.first().send({embed}).catch(e =>{
if(e) return
});
}
}
Like I said, been trying to do this for 3 hours now, and I'm stumped. If someone could tell me what I did wrong that'd be awesome, thanks.
You need execute command in you main.js file on bot.on('message' block.
Like this:
client.on('message', message => {
if (message.channel.type === "dm") return;
let prefix = '!'
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
if (!message.content.startsWith(prefix)) return;
let commandfile = client.commands.get(cmd.slice(prefix.length));
if (commandfile) commandfile.run(client, message, args, botconfig);
})

Discord.js | Cannot read property 'displayName' of undefined

I am making a discord bot for a friend and everything worked until i tried to make an unban command. when i tried to unban someone it did not work. then i looked at the error. it displayed:
TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Unhandled promise rejection: TypeError: Cannot read property 'displayName' of undefined
at C:\Users\user\folder_name\commands\unban.js:37:67
at processTicksAndRejections (internal/process/task_queues.js:97:5)
this is my code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
console.log(message.content);
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first();
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length >= 1) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
message.channel.send(embedMsg);
}
if (args.length < 2) {
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
newargs = "";
for (var i = 1; i < args.length; i++) {
newargs += (args[i] + " ");
}
message.guild.unban(member).then(() => {
embedMsg.setDescription(`${member.displayName} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}).catch((err) => {
embedMsg.setDescription(`Could not unban ${member.displayName}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
}
does anyone know what i am doing wrong?
It says in the discord.js's official docs that the unban method returns a member object https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=unban
The reason why it says 'undefined' is because the member object you are trying to access is not in the server/guild. So, therefore you need add a reference to the member object that the method returns:
message.guild.unban('some user ID').then((member) => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
}
Unbun method return a user promise, so user dont have property displayName, you need use .username
And you can use user.id for unban, so right way will be let member = message.mentions.members.first() || args[0]
This check doing wrong, because its not stop code execute
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
Amm and whats this part code doing? Why its duplicate?
if (args.length < 2) {
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
return;
}
The edited code
const Discord = require('discord.js');
module.exports = {
name: 'unban',
description: 'unban user',
aliases: [],
cooldown: 0,
args: true,
usage: '<mention> [reason]',
guildOnly: true,
execute(message, args, client) {
const embedMsg = new Discord.RichEmbed()
.setColor('#0000ff')
.setAuthor(message.author.username, message.author.displayAvatarURL)
.setThumbnail(message.author.displayAvatarURL)
.setTimestamp()
.setFooter('botname', client.user.displayAvatarURL);
let member = message.mentions.members.first() || args[0]
if (!message.member.hasPermission('BAN_MEMBERS')) {
embedMsg.setDescription(`You don't have permission to unban!`);
return message.channel.send(embedMsg);
}
if (!args.length < 2) {
embedMsg.setDescription('^unban takes at least one argument! the proper usage is ^unban <mention> [reason]');
return message.channel.send(embedMsg);
}
let newargs = args.splice(1,args.length).join(' ')
message.guild.unban(member)
.then(() => {
embedMsg.setDescription(`${member.username} has been succesfully unbanned for reason ${newargs}`);
return message.channel.send(embedMsg);
})
.catch((err) => {
embedMsg.setDescription(`Could not unban ${member.username}`);
console.log(err);
return message.channel.send(embedMsg);
});
}
}

Resources