For some reason when i try to use my command it keep giveing me this error. the error and the code is listed below. i tried fixing it nothing seems to fix it
const Discord = require("discord.js");
module.exports = {
name: 'clear',
aliases: ['purge'],
discription: "clears messages",
async execute(message, args, client) {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return message.reply('You do not have permissions to use this command')
if (!args[0]) return message.reply(`Please specify a amount of messages to delete (1-99)`)
if (isNaN(args[0])) return message.reply(`Please enter a number`)
if (parseInt(args[0]) > 99) return message.reply(` The max amount of messages you may delete is 99`)
await message.channel.bulkDelete(parseInt(args[0]) + 1)
.catch(err => console.log(err))
message.channel.send(`deleted ${args[0]} messages`).then(m => m.delete({ timeout: 5000 }))
}
}
PS C:\Users\lolzy\OneDrive\Desktop\discordbot> node .
Cbs slave is online!
(node:10108) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of undefined
try this:
const Discord = require("discord.js");
module.exports = {
name: 'clear',
aliases: ['purge'],
discription: "clears messages",
async execute(client, message, args) {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel,send('You do not have permissions to use this command')
if (!args[0]) return message.reply(`Please specify a amount of messages to delete (1-99)`)
if (isNaN(args[0])) return message.reply(`Please enter a number`)
if (parseInt(args[0]) > 99) return message.reply(` The max amount of messages you may delete is 99`)
await message.channel.bulkDelete(parseInt(args[0]) + 1)
.catch(err => console.log(err))
message.channel.send(`deleted ${args[0]} messages`).then(m => m.delete({ timeout: 5000 }))
}
}
Related
So i've been trying to count the reactions statistic after it was accepted or rejected, i'd try to find a solution but i can't here's my code
module.exports = {
name: 'accept-suggestion',
cooldown: 3,
description: 'Accept a sugegstion',
permissions: 'MANAGE_ROLES',
usage: '[suggestion id] [reason]',
async run(client, message, args, cmd, Discord){
message.delete()
const messageID = args[0];
const acceptMsg = args.slice(1).join(" ");
if(!messageID) return message.reply('Please specify a suggestion Id!').then(msg => {
msg.delete({ timeout: 3000 })
})
if(!acceptMsg) return message.reply('Please specify a reason!').then(msg => {
msg.delete({ timeout: 3000})
})
try {
const suggestionChannel = message.guild.channels.cache.get(
'SuggestionChannel_ID'
);
const moderator = message.author.tag
const suggestedEmbed = await suggestionChannel.messages.fetch(messageID);
console.log(suggestedEmbed)
const data = suggestedEmbed.embeds[0];
const dataStats = suggestedEmbed[0];
let upVote = dataStats.reactions.cache.get('✅').count;
let downVote = dataStats.reactions.cache.get('❌').count;
const acceptEmbed = new Discord.MessageEmbed()
.setTitle("Suggestion (Accepted)")
.setColor('#1dc44a')
.setAuthor(data.author.name, data.author.iconURL)
.setDescription(data.description)
.addFields(
{name: `Accepted by ${moderator}`, value: ` > ${acceptMsg}`},
{name: 'Statistic', value: `${upVote}\n${downVote}`}
)
.setFooter(`${data.author.name}'s suggestion`, data.author.iconURL)
suggestedEmbed.edit(acceptEmbed).then(msg => msg.reactions.removeAll())
const user = await client.users.cache.find(
(u) => u.tag === data.author.name
);
user.send("Your suggestion has been accepted!")
} catch(err) {
console.log(err)
}
}
}
you maybe wondering why i put .reactions after dataStats, i put it because i thought it would work by seeing the output off the suggestedEmbed(the output: https://pastebin.com/yEhDecur) i hope someone could fix this :)
Running the fetch() method with a id parameter only returns a single Message so accessing it like a array/collection won't work
const dataStats = suggestedEmbed[0];
this needs to change to
const dataStats = suggestedEmbed;
https://discord.js.org/#/docs/discord.js/stable/class/MessageManager?scrollTo=fetch
I'm made a purge command which targets a particular member and deletes the given amount. The problem is it deletes the messages correctly while on completion it throws a unknown error. Help me fix it! Here's the code and its error
const Discord = require('discord.js');
const { Permissions } = require('discord.js');
const { MessageEmbed } = require("discord.js")
module.exports = {
description: 'purge command',
run: async (client, message, args) => {
setTimeout(() => message.delete(), 3500);
if (message.member.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) {
let purgeMember = message.mentions.users.first()
let amount = args[1]
if (!purgeMember) return message.channel.send("Please Mention a Member to purge").then(msg => { setTimeout(() => msg.delete(), 4000) })
if (!amount) return message.channel.send("Please provide a valid number to purge").then(msg => { setTimeout(() => msg.delete(), 4000) })
if (isNaN(amount)) return message.channel.send("Please provide a valid number to purge").then(msg => { setTimeout(() => msg.delete(), 4000) })
if (amount > 99) return message.channel.send("I can delete upto 100 messages only").then(msg => { setTimeout(() => msg.delete(), 4000) })
let AllMessages = await message.channel.messages.fetch()
let FilteredMessages = await AllMessages.filter(x => x.author.id === purgeMember.id)
let deletedMessages = 0
FilteredMessages.forEach(msg => {
if (deletedMessages >= amount) return
msg.delete()
deletedMessages++
})
} else {
message.channel.send('🛡️ | You DONT have permission to use this command!').then(msg => { setTimeout(() => msg.delete(), 5000) })
}
},
}
Error
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Unknown Message
at RequestHandler.execute (D:\STUFF\BOT\Passion-Bot-V13\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
V13\node_modules\discord.js\src\structures\Message.js:709:5) {
method: 'delete',
path: '/channels/886173223144792074/messages/886174452994437170',
code: 10008,
httpStatus: 404,
requestData: { json: undefined, files: [] }
}
This error is thrown for a cached message which bot is unable to delete appearently ( maybe pinned?, maybe cached but non existant?) You could just supress this error via try/catch
try {
msg.delete()
} catch(e) {}
Furthermore at the topmost part of your code there's a
setTimeout( () => message.delete(), 3500); ( waiting 3.5 seconds before deleting the first message) , when you loop through your messages it's highly likely that the particular message with the command is in the cache existing too, so either one of those would delete it.
My suggestion:
Either use try/catch in your msg.delete() within the loop
OR
Remove the timeout on the initial message.delete()
So the problem you are encountering right now is when a message doesn't exist as every DiscordAPIError: Unknown Message just means that a message is likely to be deleted.
The code:
setTimeout(() => message.delete(), 3500);
Is the error to the problem:
FilteredMessages.forEach(msg => {
if (deletedMessages >= amount) return
msg.delete()
deletedMessages++
})
If you see the msg.delete() in the middle of the forEach function, the message has already been deleted, therefore the setTimeout is rather obvious to cause a problem.
By removing setTimeout(() => message.delete(), 3500);, it'll most likely fix the problem.
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.');
});
})
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);
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);
});
}
}