Discord.js Bot crashing while used command - javascript

my problem is when i write command! Tempmute (user) (time) and in field (time) i'll write for example 10 s / m / h / d it works great but when i wrote other letter in this field bot just crash.
Can any one tell me how to fix it? Thanks in advance!
Code:
if (command === `${prefix}tempmute`) {
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!tomute) return message.reply("Nie moge znaleźć określonego użytkownika");
if(tomute.hasPermission("ADMINISTRATOR")) return message.reply("Ta osoba ma zbyt wysoką rangę lub nie masz permisji!");
let muterole = message.guild.roles.find(r => r.name === "muted");
if(!muterole){
try {
muterole = message.guild.createRole({
name: "muted",
color: "#0000000",
permissions: []
})
message.guild.channels.forEach(async (channel, id) => {
channel.overwritePermissions(muterole,{
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
} catch(e) {
console.log(e.stack);
}
}
let mutetime = args[1];
if(!mutetime) return message.reply("Wprowadź czas na jaki ma byc zmutowana osoba")
tomute.addRole(muterole.id);
message.reply(`<#${tomute.id}> został zmutowany na ${ms(ms(mutetime))}`);
setTimeout(function(){
tomute.id.removeRole(muterole.id);
message.channel.send(`<#${tomute.id}> został odmutowany!`);
}, ms(mutetime));
}
}
);
Error in console:
C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\ms\index.js:34
throw new Error(
^
Error: val is not a non-empty string or a valid number. val=undefined
at module.exports (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\ms\index.js:34:9)
at Client.<anonymous> (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\bot.js:241:58)
at Client.emit (events.js:210:5)
at MessageCreateHandler.handle (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
at WebSocketConnection.onPacket (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:210:5)
at Receiver.receiverOnMessage (C:\Users\pr0mo\OneDrive\Pulpit\Discord Rust Bot\node_modules\ws\lib\websocket.js:789:20)

Add your code to the try catch statement it won't crash anymore, but if you want to check if the argument corresponds to what you want, you can make an regexp
try catch:
try
{
}catch(error)
{
console.log(error)
}
Regex:
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
mutetime);
if(!match)return;

Related

Discord.js can't register context menu

I've been messing around with discord.js and wanted to add a context menu to my bot, for some reason whenever I start the bot I get this really weird error, I can't seem to solve it or find a solution online, here's the code:
const { ContextMenuCommandBuilder } = require(`#discordjs/builders`);
module.exports = {
data: new ContextMenuCommandBuilder()
.setName(`test`)
.setType(`MESSAGE`),
async execute(interaction) {
interaction.reply({
content: `Successful.`,
ephemeral: true
});
}
}
And here's the error:
C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:1470
return Result.err(new CombinedError(errors));
^
CombinedError: Received one or more errors
at UnionValidator.handle (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:1470:23)
at UnionValidator.parse (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:113:88)
at validateType (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#discordjs\builders\dist\index.js:1462:17)
at ContextMenuCommandBuilder.setType (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#discordjs\builders\dist\index.js:1484:5)
at Client.<anonymous> (C:\Users\willi\OneDrive\Desktop\NovaBotAI\NovaBot.js:65:14)
at Object.onceWrapper (node:events:642:26)
at Client.emit (node:events:527:28)
at WebSocketManager.triggerClientReady (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:17)
at WebSocketManager.checkShardsReady (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\discord.js\src\client\websocket\WebSocketManager.js:367:10)
at WebSocketShard.<anonymous> (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\discord.js\src\client\websocket\WebSocketManager.js:189:14) {
errors: [
ExpectedValidationError: Expected values to be equals
at LiteralValidator.handle (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:674:76)
at LiteralValidator.run (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:102:23)
at UnionValidator.handle (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:1465:32)
at UnionValidator.parse (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:113:88)
at validateType (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#discordjs\builders\dist\index.js:1462:17)
at ContextMenuCommandBuilder.setType (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#discordjs\builders\dist\index.js:1484:5)
at Client.<anonymous> (C:\Users\willi\OneDrive\Desktop\NovaBotAI\NovaBot.js:65:14)
at Object.onceWrapper (node:events:642:26)
at Client.emit (node:events:527:28)
at WebSocketManager.triggerClientReady (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:17) {
validator: 's.literal(V)',
given: 'MESSAGE',
expected: 2
},
ExpectedValidationError: Expected values to be equals
at LiteralValidator.handle (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:674:76)
at LiteralValidator.run (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:102:23)
at UnionValidator.handle (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:1465:32)
at UnionValidator.parse (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#sapphire\shapeshift\dist\index.js:113:88)
at validateType (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#discordjs\builders\dist\index.js:1462:17)
at ContextMenuCommandBuilder.setType (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\#discordjs\builders\dist\index.js:1484:5)
at Client.<anonymous> (C:\Users\willi\OneDrive\Desktop\NovaBotAI\NovaBot.js:65:14)
at Object.onceWrapper (node:events:642:26)
at Client.emit (node:events:527:28)
at WebSocketManager.triggerClientReady (C:\Users\willi\OneDrive\Desktop\NovaBotAI\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:17) {
validator: 's.literal(V)',
given: 'MESSAGE',
expected: 3
}
]
}
I'm at a loss, nothing I do seems to fix it, I tried changing the setType() value to a number and that got the code to start, but then it didn't register and I couldn't use it at all, but other than that I've got nothing.
You probably have fixed that already, but I have experienced the same issue today and solved it. I'm gonna post the solution, in case someone else needs it..
const { ContextMenuCommandBuilder } = require(`#discordjs/builders`);
const { ApplicationCommandType } = require('discord-api-types/v9');
module.exports = {
data: new ContextMenuCommandBuilder()
.setName(`test`)
.setType(ApplicationCommandType.Message),
async execute(interaction) {
interaction.reply({
content: `Successful.`,
ephemeral: true
});
}
}
If you are using module.exports why don't you use the command directly like:
const { client, ContextMenuInteraction } = require('discord.js');
module.exports = {
name: "...",
type: 'USER',

I get this error: TypeError: Cannot read properties of undefined (reading 'members') whenever I execute command

const levels = require('discord-xp')
const { MessageEmbed } = require('discord.js')
const client = require('../../index')
module.exports = {
name: "edit",
description: "Edits a users level or xp",
usage: ".edit <user> [xp / level] [add / set / remove] <number>",
developersOnly: true,
run: async (message, args, client) => {
const usage = ".edit <user> [xp / level] [add / set / remove] <number>"
if (!args[0]) return message.channel.send(`> You need to state more arguments \`${usage}\``)
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
const mentionedMember = message.mentions.members.first()
if (!['xp', 'level'].includes(args[1])) return message.channel.send(`> You did not specify if you are changing level or xp: \`${usage}\``)
if (args[1] === "xp") {
if (!['add', 'set', 'remove'].includes(args[2])) return message.channel.send(`You did not state if you're adding, setting, or removing`)
const value = Number(args[3]);
let levelUser = await Levels.fetch(mentionedMember.user.id, message.guild.id)
if (!levelUser) return message.channel.send('> That person isnt in the database yet.')
if (args[2] === 'add') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.appendXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Added \`${value}\` xp to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'remove') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.subtractXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Removed \`${value}\` xp to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'set') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.setXp(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Set ${mentionedMember}'s xp to \`${value}\``)
} catch (err) {
console.log(err)
}
}
} else if (args[1] === 'level') {
if (!['add', 'set', 'remove'].includes(args[2])) return message.channel.send(`You did not state if you're adding, setting, or removing`)
const value = Number(args[3]);
let levelUser = await Levels.fetch(mentionedMember.user.id, message.guild.id)
if (!levelUser) return message.channel.send('> That person isnt in the database yet.')
if (args[2] === 'add') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.appendLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Added \`${value}\` level(s) to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'remove') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.subtractLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Removed \`${value}\` level(s) to ${mentionedMember}`)
} catch (err) {
console.log(err)
}
} else if (args[2] === 'set') {
if (!value) return message.channel.send('> That is not a valid number')
try {
await Levels.setLevel(mentionedMember.user.id, message.guild.id, value)
message.channel.send(`> Set ${mentionedMember}'s level to \`${value}\``)
} catch (err) {
console.log(err)
}
}
}
}
}
This is supposed to be a level and xp edit command for my bots leveling system
i tested it on my self first but it didnt seem to work and i dont think theres any errors in my code. It send this super long error:
TypeError: Cannot read properties of undefined (reading 'members')
at Object.run (/home/runner/sung-jin-woo/commands/leveling/edit.js:13:46)
at Client.<anonymous> (/home/runner/sung-jin-woo/events/guild/messageCreate.js:124:18)
at Client.emit (node:events:402:35)
at MessageCreateAction.handle (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/actions/MessageCreate.js:25:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
at WebSocketShard.onPacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
at WebSocketShard.onMessage (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
at WebSocket.onMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
at Receiver.receiverOnMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/websocket.js:1022:20)
at Receiver.emit (node:events:390:28)
at Receiver.dataMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:522:14)
at Receiver.getData (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:440:17)
at Receiver.startLoop (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:148:22)
at Receiver._write (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:83:10) Promise {
<rejected> TypeError: Cannot read properties of undefined (reading 'members')
at Object.run (/home/runner/sung-jin-woo/commands/leveling/edit.js:13:46)
at Client.<anonymous> (/home/runner/sung-jin-woo/events/guild/messageCreate.js:124:18)
at Client.emit (node:events:402:35)
at MessageCreateAction.handle (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/actions/MessageCreate.js:25:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
at WebSocketShard.onPacket (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
at WebSocketShard.onMessage (/home/runner/sung-jin-woo/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)
at WebSocket.onMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
at Receiver.receiverOnMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/websocket.js:1022:20)
at Receiver.emit (node:events:390:28)
at Receiver.dataMessage (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:522:14)
at Receiver.getData (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:440:17)
at Receiver.startLoop (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:148:22)
at Receiver._write (/home/runner/sung-jin-woo/node_modules/ws/lib/receiver.js:83:10)
}
so like can someone help me?
(if you need any more info about code say it in comment ill reply with the info there)
Whenever you see this error, check the line 'reading members'(in your case). That simply means you are doing a key access where keyname is 'members' and object inside which this key 'members' is present is undefined. For example X.members where X is undefined.So check in your code why this 'X'(imaginary name given for the sake of answer could be any name that you only know) is undefined or what could make that 'X' undefined. And after finding that you should put a check before doing the access i.e something like below to avoid these run time errors:
if(X) then X.members
OR
X?.members
Looking at your code the error is coming from here :
const mentionedMember = message.mentions.members.first()
Keep this line in correct place i.e all your access to mentionedMember should occur after this line and then change above line to :
const mentionedMember = message.mentions?.members.first() provided members has first() method. If you are not sure then you can do like this also const mentionedMember = message.?mentions?.members?.first()
There is one more way which is not cleaner but it's fine:
let mentionedMember;
if(message && message.mentions && message.mentions.members) {
mentionedMember = message.mentions.members.first()
}
In this line code:
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
const mentionedMember = message.mentions.members.first()
Try to arrange this like:
const mentionedMember = message.mentions.members.first()
if (!mentionedMember) return message.channel.send(`> Mention a valid user / member.`);
if (!args[1]) return message.message.channel.send(`> You must state if you are editing the member's level or xp: \`${usage}\``)
In line:
if (!mentionedMember) return message.channel.send('> Mention a valid user / member.'); you already calling the mentionedMember which is its not readable.
Let me know if the error still there after you rearrange your code

Discord.js ReferenceError: channel is not defined

I'm using the discordjs bot guide and copied their help command from the GitHub. However the code gives an error. I've tried almost every solution I could find for the ReferenceError I'm getting. What am I doing wrong?
My code:
const { prefix } = require('../../config.json');
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands'],
usage: '[command name]',
cooldown: 5,
execute(message, args) {
const data = [];
const { commands } = message.client;
if (!args.length) {
data.push('Here\'s a list of all my commands:');
data.push(commands.map(command => command.name).join(', '));
data.push(`\nYou can send \`${prefix}help [command name]\` to get info on a specific command!`);
return message.author.send(data, { split: true })
.then(() => {
if (message.channel.type === 'dm') return;
message.reply('I\'ve sent you a DM with all my commands!');
})
.catch(error => {
console.error(`Could not send help DM to ${message.author.tag}.\n`, error);
message.reply('it seems like I can\'t DM you!');
});
}
const name = args[0].toLowerCase();
const command = commands.get(name) || commands.find(c => c.aliases && c.aliases.includes(name));
if (!command) {
return message.reply('that\'s not a valid command!');
}
data.push(`**Name:** ${command.name}`);
if (command.aliases) data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.description) data.push(`**Description:** ${command.description}`);
if (command.usage) data.push(`**Usage:** ${prefix}${command.name} ${command.usage}`);
data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);
message.channel.send(data, { split: true });
},
};
The error:
ReferenceError: channel is not defined
at Object.execute (C:\Users\user\JS Bot\commands\utility\help.js:64:5)
at Client.<anonymous> (C:\Users\user\JS Bot\index.js:78:11)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\user\JS Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\user\JS Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\user\JS Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\user\JS Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\user\JS Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\user\JS Bot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)

How to fix RichEmbed Discord.js

I know the question exists but even though I looked into the other question and i used 'sendEmbed' instead of 'send' but nothing seems to work, if anyone can help with this error I'll be grateful :)
this is my code:
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = "Removed For Security";
const PREFIX = "!";
bot.on('ready', () => {
console.log("Bot is online");
})
bot.on('message', (msg) => {
let args = msg.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'ping':
msg.channel.send("pong!")
break;
case 'clear':
if (!args[1])
return msg.reply('Error please define second argument');
msg.channel.bulkDelete(args[1]);
break;
case 'embed': {
const embed = new Discord.RichEmbed()
.addField('Player Name', msg.author.username)
msg.channel.send(embed)
break;
}
}
})
bot.login(token);
and this is the error:
C:\Users\isam\Desktop\discord bot\index.js:24
const embed = new Discord.RichEmbed()
^
TypeError: Discord.RichEmbed is not a constructor
at Client.bot.on (C:\Users\isam\Desktop\discord bot\index.js:24:27)
at Client.emit (events.js:193:13)
at MessageCreateAction.handle (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\Users\isam\Desktop\discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\isam\Desktop\discord bot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:193:13)
at Receiver.receiverOnMessage (C:\Users\isam\Desktop\discord bot\node_modules\ws\lib\websocket.js:800:20)
As you can see the error is in RichEmbed constructor, also my Discord.js version is '12.2.0', Any ideas?
Discord.RichEmbed got removed in v12.
just use Discord.MessageEmbed instead.
it's essentially the same. just a new name.
new docs: https://discord.js.org/#/docs/main/v12/class/MessageEmbed
Discord.RichEmbed got removed in V12
try this :
const embed = new Discord.MessageEmbed()
//l'embed
msg.channel.send(embed)

TypeError: value.split is not a function

I'm creating a discord.js bot v12 and I get this error on line 2 when I use the purge command in discord and I'm assuming value.split is not a function and wondering if I should be doing something else since I'm using v12 of discord.js:
Uncaught Promise Error:
TypeError: args.split is not a function or its return value is not iterable
at Object.module.exports.run (c:\Users\Kazzu\Desktop\src\commands\prune.js:2:34)
at module.exports (c:\Users\Kazzu\Desktop\src\events\message.js:33:9)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (c:\Users\Kazzu\Desktop\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:311:20)
This is my code:
module.exports.run = async (client, message, args) => {
let [ userId, limit ] = args.split(/\s+/);
if(!userId && !limit) {
let deletedMessages = await message.channel.bulkDelete();
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
if(!userId || !limit) return message.channel.send('Please provide the correct arguments.');
let r = new RegExp(/^\d+$/);
if(!r.test(userId)) return message.channel.send('Please provide a valid user id.');
if(isNaN(limit)) return message.channel.send('Please provide a numeric value for limit');
if(limit > 100) return message.channel.send('Limit must be less than or equal to 100.');
try {
let fetchedMessages = await message.channel.messages.fetch({ limit });
let filteredMessages = fetchedMessages.filter(message => message.author.id === userId);
let deletedMessages = await message.channel.bulkDelete(filteredMessages);
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
catch(err) {
console.log(err);
}
}
module.exports.help = {
name: "purge",
description: "Deletes a number of messages from a user in a channel."
}
module.exports.requirements = {
userPerms: [],
clientPerms: [],
ownerOnly: false
}
It seems that args is not type of string. When you call .split() for something other than a string, JavaScript runtime cannot find the .split() method for that type. So, make sure you are passing a string to your function or try something like that:
if (typeof string === args) {
var str = args.toString();
}
Turns out I needed to replace value.split to value.slice

Categories

Resources