I'm trying to add a function to my discord bot xp-system by adding a user automatically to a role when hitting a certain level.
I have been trying all kind of solutions I can think of but none seem to work.
Have tried:
addrankup.addRole(fullmember).catch(console.error);
let addrankup.addRole(fullmember).catch(console.error);
addrankup.addRole(fullmember.id).catch(console.error);
Expected when users hit a set level to automatically get the rank:
let xpAdd = Math.floor(Math.random() * 5) + 10;
console.log(xpAdd);
if (!xp[message.author.username]) {
xp[message.author.username] = {
xp: 0,
level: 1
};
}
let curxp = xp[message.author.username].xp;
let curlvl = xp[message.author.username].level;
let nxtLvl = xp[message.author.username].level * 200;
xp[message.author.username].xp = curxp + xpAdd;
if (nxtLvl <= xp[message.author.username].xp) {
xp[message.author.username].level = curlvl + 1;
message.channel.send("Level Up!").then(msg => {
msg.delete(5000)
});
}
if (curlvl <= xp[message.author.username].level) {
xp[message.author.username].level = "2";
let addrankup = message.mentions.members.first();
let fullmember = message.guild.roles.find(`name`, "Full Member");
addrankup.addRole(fullmember.id).catch(console.error);
message.channel.send("You have received a new role!").then(msg => {
msg.delete(5000)
});
}
fs.writeFile("./xp.json", JSON.stringify(xp), (err) => {
if (err) console.log(err)
});
But instead this is what the console tells me:
(node:8460) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'addRole' of undefined
at Client.bot.on (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\index.js:125:15)
at Client.emit (events.js:187:15)
at MessageCreateHandler.handle (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:182:13)
at Receiver._receiver.onmessage (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\ws\lib\websocket.js:137:47)
at Receiver.dataMessage (E:\#DeathKillerNOR Discord Bots\DeathKillerBot\node_modules\ws\lib\receiver.js:409:14)
(node:8460) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated
either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8460) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The error tells you that addrankup is undefined which in turn means that message.mentions.members.first(); returns nothing. My guess is that instead of
let addrankup = message.mentions.members.first();
you're looking for
let addrankup = message.member;
Related
const Discord = require('discord.js');
module.exports = {
name: 'unban',
aliases: ['uban', 'unban'],
category: 'misc',
permissions: ['BAN_MEMBERS'],
description:
'Use this command to permanately or temporary ban a server member from Sekai.',
/**
* #param {Discord.Message} message
* #param {Array} args
*/
async execute(message, args) {
if (message.mentions.users.size === 0)
return message.reply('Please mention a user to unban ❌');
const targetid = message.mentions.users.first().id;
if (targetid === message.client.user.id)
return message.reply(
"Me? Really? That's not very nice, I guess you failed 🤡"
);
const targed = await message.guild.members.cache.get(targetid);
let reason = [];
if (args.length >= 2) {
args.shift();
reason = args.join(' ');
} else reason = 'No Reason provided';
try {
let extra = '';
try {
const embed = new Discord.MessageEmbed()
.setTitle('Moderation message regarding on your **BAN**')
.setAuthor("Joony's Den")
.setDescription(
`you have been banned from **${message.guild.name} ✅ **\nReason for ban: **${reason}\n${extra}**`
)
.addField('Contact','If you believe that your ban was unjustified, please feel free to contact any of these staff members. **JOONY#9513** or any of administrators online.')
.setColor('#2243e6')
.addField('Appeal Accepted?','if your appeal was accepted, please join using this link. your link will expire after 1 use. **https://discord.gg/4yuCzUC7aw**')
.addField(
'Appeal',
'Because you have been banned from the server, you will have one chance to appeal 🔨. Your appeal will be processed to the administrators or appeal managers ✅ **[CLICK HERE TO APPEAL](https://forms.gle/atc75ZftpdfJhfH56)**'
);
targed.send(embed);
} catch (error) {
extra = 'Messaging the user has failed! ❌';
}
setTimeout(() => {
targed.unban(targed, [reason])
const embed = new Discord.MessageEmbed()
.setTitle('User unbanned')
.setDescription(
`${
targed.tag || targed.user.username
} has been sucessfully unbanned from **${
message.guild.name
} ✅ **\nReason for unban: **${reason}\n${extra}**`
)
.setColor('#FA2657');
message.channel.send(embed);
}, 2000);
} catch (error) {
message.channel.send(
`I could not unban the given member, make sure that my role is above member! ❌`
);
}
},
};
Hello! how do I unban the user using this format, it has an error saying "guild.unban is undefined"
it has an error saying
targed.unban([reason])
^
TypeError: targed.unban is not a function
at Timeout._onTimeout (C:\Users\Joon\Documents\GitHub\Discord-Bot\commands\misc\unban.js:49:16)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
You cannot unban a GuildMember (a banned user is not a member of a Guild). You should call unban on GuildMemberManager. See https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=unban
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 */)
I'm having trouble making my bot filter messages and respond with a local file from my computer. Here is the code:
client.on("message", msg => {
console.log(msg.content);
let wordArray = msg.content.split(" ")
console.log(wordArray)
let filterWords = ['test']
for(var i = 0; i < filterWords.length; i++) {
if(wordArray.includes(filterWords[i])) {
msg.delete()
// Create the attachment using MessageAttachment
const attachment = new MessageAttachment('cbcfilter.png');
msg.channel.send(attachment)
}
}
});
It gives me this error message:
ReferenceError: MessageAttachment is not defined
at Client.<anonymous> (/Users/DShirriff/cbcbot/bot.js:108:26)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:435:22)
at WebSocketShard.onMessage (/Users/DShirriff/cbcbot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
at WebSocket.onMessage (/Users/DShirriff/cbcbot/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (events.js:311:20)
at Receiver.receiverOnMessage (/Users/DShirriff/cbcbot/node_modules/ws/lib/websocket.js:801:20)
Am I an idiot and missing a simple parentheses, or should I look for a different form of this line of code?
You need to import MessageAttachment.
If you're using require to import discord.js then you can do:
const Discord = require('discord.js')
const attachment = new Discord.MessageAttachment('cbcfilter.png');
If you're using import then you can do:
import { MessageAttachment } from 'discord.js'
const attachment = new MessageAttachment('cbcfilter.png');
Side note: you don't have to construct a MessageAttachment you can just do
msg.channel.send({files: ['cbcfilter.png']})
OR
msg.channel.send({
files: [{
attachment: 'entire/path/to/cbcfilter.png',
name: 'cbcfilter.png'
}]
})
This question already has an answer here:
How can I migrate my code to Discord.js v12 from v11?
(1 answer)
Closed 2 years ago.
I'm currently working on a Discord bot using discord.js for a server. While working on a command to display the server's information, I came across an error.
Here's the code:
const dateFormat = require('dateformat');
const Discord = require('discord.js');
const colors = require('../colors.json');
const date = new Date();
dateFormat(date, 'dddd, mmmm dS, yyyy, h:MM:ss TT');
exports.run = async (client, message, args, ops) => {
const millis = new Date().getTime() - message.guild.createdAt.getTime();
const days = millis / 1000 / 60 / 60 / 24;
const owner = message.guild.owner.user || {};
const verificationLevels = ['None ,(^.^),', 'Low ┬─┬ ノ( ゜-゜ノ)', 'Medium ヽ(ຈل͜ຈ)ノ︵ ┻━┻ ', 'High (╯°□°)╯︵ ┻━┻', 'Extreme ┻━┻彡 ヽ(ಠ益ಠ)ノ彡┻━┻'];
let embed = new Discord.MessageEmbed()
.setThumbnail(message.guild.iconURL)
.setFooter(`requested by ${message.author.username}#${message.author.discriminator}`, message.author.avatarURL)
.setColor(colors.cyan)
.addField('Server Name', message.guild.name, true)
.addField('Server ID', message.guild.id, true)
.addField('Owner',`${owner.username + "#" + owner.discriminator || '� Owner not found...'}`,true)
.addField('Owner ID', `${owner.id || '� Owner not found...'}`,true)
.addField('Created On',`${dateFormat(message.guild.createdAt)}`, true)
.addField('Days Since Creation', `${days.toFixed(0)}`, true)
.addField('Region',`${message.guild.region}`, true)
.addField('Verification Level',`${verificationLevels[message.guild.verificationLevel]}`,true)
.addField('Text Channels',`${message.guild.channels.filter(m => m.type === 'text').size}`,true)
.addField('Voice Channels',`${message.guild.channels.filter(m => m.type === 'voice').size}`,true)
.addField('Member Count',`${message.guild.members.filter(m => m.presence.status !== 'offline').size} / ${message.guild.memberCount}`, true)
.addField('Roles',`${message.guild.roles.size}`,true)
message.channel.send(embed);
}
And here's the error:
(node:17432) UnhandledPromiseRejectionWarning: TypeError: message.guild.channels.filter is not a function
at Object.exports.run (C:\Users\brigh\Desktop\XontavsBot\commands\serverinfo.js:29:73)
at Client.client.on (C:\Users\brigh\Desktop\XontavsBot\index.js:30:21)
at Client.emit (events.js:197:13)
at MessageCreateAction.handle (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:435:22)
at WebSocketShard.onMessage (C:\Users\brigh\Desktop\XontavsBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\brigh\Desktop\XontavsBot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:197:13)
(node:17432) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:17432) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
If anybody knows what the problem is, please let me know.
In Discord.js v12, many things like Guild#channels got turned into a manager. Guild#channels is now a ChannelManager, so to get the collection of channels use message.guild.channels.cache. For example:
message.guild.channels.cache.filter(m => m.type === 'text').size
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
}