"checkwarns" command giving me this error - discord.js

Whenever I use my checkwarns command to check the number of warns a user has it gives me this error:
2019-03-20T23:55:35.590941+00:00 app[worker.1]: (node:4)
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'warns' of
undefined
2019-03-20T23:55:35.590958+00:00 app[worker.1]: at
Object.module.exports.run (/app/commands/checkwarns.js:10:35)
I don't know how to fix this I can't find any problems with my code.
const Discord = require("discord.js");
const fs = require("fs");
const ms = require("ms");
let warns = JSON.parse(fs.readFileSync("./warnings.json", "utf8"));
module.exports.run = async(bot, message, args) => {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return
message.reply("You don't have permssion to use this command");
let wUser = message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0])
if (!wUser) return message.reply("Couldn't find that user");
let warnlevel = warns[wUser.id].warns;
if (!warns[wUser.id]) warns[wUser.id] = {
warns: 0
};
message.delete().catch();
let warnembed = new Discord.RichEmbed()
.setTitle("**warns**")
.setColor("#0xff80ff")
.addField("User Warns", warnlevel, true);
message.channel.send(warnembed);
}
module.exports.help = {
name: "checkwarns"
}
I'm using Heroku to host the bot.

Your issue might be occuring here:
let warnlevel = warns[wUser.id].warns;
If the key wUser.id doesn't exist, the value of warns[wUser.id] would be undefined, which doesn't contain any user-defined properties. Hence, you get an error trying to read the value of warns (a user-defined property) in undefined.
To get around this, you want to check whether an object at warns[wUser.id] actually exists first. An easy way to do this is by doing the following:
var warnLevel;
if (warns[wUser.id] != undefined) {
warnLevel = warns[wUser.id].warns
}
else {
// Do something else to initialize either warnLevel or warns[wUser.id] here
}

Related

Same value in replit database

i am having a problem that whenever i type the +warn <#user> then everything goes well , lets take an example that i want to warn any user so i'll type +warn <#user> and then it will show a embed by saying that your are banned by this this and you are banned from this this and also shows that how many warns the user now have and lets also take that he have 1 warn till now, and now warn another user by typing +warn <#user> and then it will show the thing blah blah blah but.. when the bot shows that how many warns the second user have then it will show the same value of warn as the first user like this warns(of the first user): 1 but when with the second user it shows warns(of the second user): 2 and even the second user have 0 warns but it will show 2 and when you retry to warn the first user it will show 3 warns idk why
code:-
const config = require("../config.json");
const Database = require("#replit/database")
const db = new Database()
const { MessageEmbed, username } = require('discord.js')
exports.run = async (client, message, args, Discord) => {
let reason = args.slice(1).join(" ")
if (!reason) reason = "No reason provided"
const user = message.author.id
let warns = await db.get(`warns_${message.author.id}`)
let member = message.mentions.members.first()
if (!member) return message.reply("Please mention a user to warn")
const wembed = new MessageEmbed()
.setTitle(`You have been warned`)
.setDescription(`You have been warned by ${message.author.username}\nFrom the server of: ${message.guild.name}\nWith the reason: ${reason}\nNow you have ${warns} warns`)
if (!member === member.user.bot) {
member.send({embeds: [wembed]})
} else {
message.channel.send(`unable to send dm to ${member}`)
}
const embed = new MessageEmbed()
.setTitle(`Warn to ${member}`)
.setDescription(`${member} has been warned successfully warned\n\n${member} have now ${warns}\nReason: ${reason}`)
message.channel.send({embeds: [embed]})
await db.set(`warns_${message.author.id}`, warns + 1)
member.send({embeds: [wembed]})
}
exports.conf = {
aliases: ['warning']
};
exports.help = {
name: "warn"
};```

TypeError: Cannot read property 'send' of undefined discord.js v12

i have this reaction role system everything works up to the last part where the coulour slection happens
async run(message, client, con) {
await message.channel.send("Give the color for the embed.")
answer = await message.channel.awaitMessages(answer => answer.author.id === message.author.id,{max: 1});
var color = (answer.map(answers => answers.content).join()).toUpperCase()
if(color.toUpperCase()==='CANCEL') return (message.channel.send("The Process Has Been Cancelled!"))
function embstr(){
var finalString = '';
for(var i =0;i<n;i++){
finalString += b[i]+ ' - '+a[i] +'\n';
}
return finalString;
}
const botmsg = message.client.channels.cache.get(channel => channel.id === reactChannel)
const embed = new MessageEmbed()
.setTitle(embtitle)
.setColor(color)
.setDescription(embstr());
botmsg.send(embed);
message.channel.send("Reaction Role has been created successfully")
here is the error message
{
"stack": "TypeError: Cannot read property 'send' of undefined
at SlowmodeCommand.run (B:\\stuff\\Downloads\\Admeeeeeen bot\\src\\commands\\reactionroles\\createreactionrole.js:100:22)
at processTicksAndRejections (node:internal/process/task_queues:93:5)"
}
The .get() method takes in a snowflake as its parameter. AKA an ID of a certain object. It is not an iterator, meaning that what you're currently attempting to do is not right JavaScript wise.
Instead of passing in a parameter to represent a channel object, we'll just want to pass in the ID of the channel that we'd like to get. Alternatively, you could replace .get() with .find() there, which is in fact an iterator that uses this form of a callback, although it's insufficient in our case considering we can just use .get() which is more accurate when it comes to IDs.
/**
* Insufficient code:
* const botmsg = message.client.channels.cache.find(channel => channel.id === reactChannel)
*/
const botmsg = message.client.channels.cache.get(reactChannel /* assuming that reactChannel represents a channel ID */)

How to know if a user already has a role in an addrole command

I want to send an error message saying that the user already has the role if they do in an addrole command.My current command is:
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "addrole",
description: "adds a role to a member",
execute: async (message , args) => {
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send("Invalid Permissions")
let member = message.mentions.members.first();
let role = message.mentions.roles.first();
if (!member)
return message.reply("Please mention a valid member of this server");
if (!role) return message.reply("please mention a valid role of this server");
const highest = message.member.roles.highest;
if(highest.comparePositionTo(role) <= 0)
return message.channel.send(`You cannot add roles equal/higher to that member's highest role`)
let addroleembed = new MessageEmbed()
.setTitle(`:white_check_mark: ${role.name} has been added to ${member.user.tag}`)
.setFooter(`Action performed by ${message.author.tag}`)
.setColor('77B255')
addroleembed.setTimestamp();
member.roles.add(role);
message.channel.send(addroleembed)
}}
I have tried using
if(!message.member.roles.cache.some(r=>[`${role.name}`].includes(r.name)))
and
if (member.roles.has(role.id) {
But neither of these seem to work, Anyone know the reason behind this? If I can't use either of these methods, Can you suggest me a solution?
You are so close!
All you need is cache when using has()
member.roles.cache.has(<RoleID>);
Learn More Here
You need to combine your two tries.
if(message.member.roles.cache.has("role ID") {
//rest of your code
}

How to make a counter of people who have been invited to the server?

Its my code
var args = message.content.slice(prefix.length).trim().split(/ +/g);
var command = args.shift().toLowerCase()
if(command == "myinv"){
var invs = (await message.member.guild.fetchInvites().then(invites => invites.findAll("memberCount"))).values()
return message.channel.send(elo)
}
When i use command i got error like this:
(node:22680) DeprecationWarning: Collection#findAll: use Collection#filter instead
(node:22680) UnhandledPromiseRejectionWarning: Error: Value must be specified.
Can anyone help me?
Discord collection has no method .findAll, the one way to get count of invites uses, its
get serverinvites, then filter this collection, because discord not guaranteed property of invite.uses, then you can reduce it for get a summ.
var args = message.content.slice(prefix.length).trim().split(/ +/g);
var command = args.shift().toLowerCase()
if(command == "myinv"){
let invites = message.member.guild.fetchInvites().then(invites => {
let countInvites = invites.filter(invite => (invite.hasOwnProperty('uses'))).reduce((a, b) => {
a.uses + b.uses
}, 0)
message.channel.send(`Total server invite uses: **${countInvites}**`)
})
}

discord.js member.roles.has(Group) - undefined

I want to give GroupID1 to user, who write commnad, but he can not be in GroupID2. When I write command, i got TypeError: Cannot read propety 'has' of undefined.
Code:
//GetRole.js
exports.run = (client, message, args) => {
const GroupID1 = ('510537798458146826');
const GroupID2 = ('510846208911081476');
const member = message.author;
if(!member.roles.has(GroupID2)) {
message.channel.send(member);
member.addRole(GroupID1).catch(console.error);
} else {
message.channel.send('You are alredy in GroupID2');
}
}
I try everything, what i found in another forums, but nothing work for me.
That doesn't work because you're defining member as message.author, but that's a User. Try using:
const member = message.member;

Resources