Error: Unexpected Identifier When using an eval command - javascript

Ok, so I follow a youtube video on how to make an Eval command (source code: https://github.com/MenuDocs/Discord.JS-Tutorial/blob/Episode-21/commands/owner/eval.js )and in their video they can just do eval message.author.id and bam it works. Whereas in my bot it appears with an error in chat: Error while evaluating: Unexpected identifier ( https://imgur.com/a/1NWuWEy *note i use 2 'a's to keep it separate from my the bot online, reducing duplicate messages).
case 'evaal':
const args = message.content.substring(PREFIX.length).trim().split(" ");
const ownerID = '285198963722944514';
if(message.author.id == ownerID) {
try {
let toEval = args.join(" ")
let evaluated = inspect(eval(toEval, { depth: 0 }));
if (!toEval) {
return message.channel.send("Error while evaluating: \`cannot evaluate air\`!");
} else {
let hrStart = process.hrtime()
let hrDiff;
hrDiff = process.hrtime(hrStart);
return message.channel.send(`*Executed in ${hrDiff[0] > 0 ? `${hrDiff[0]}s ` : ''}${hrDiff[1] / 1000000}ms.*\n\`\`\`javascript\n${evaluated}\n\`\`\``, { maxLength: 1900 })
}
} catch (e) {
return message.channel.send(`Error while evaluating: \`${e.message}\``)
}
} else {
return message.reply('You are not allowed to use this command. (Owner Only)').then(m => m.delete(5000))
}
break;
As linked above in the imgur image, the bot responds but only with the error message. I expect it to tell me the author's id of the message (me).

Related

Build a re-usable error message convertor

I work on a project where we receive error messages from the backend. Sometimes the error messages are not frontend friendly. We are doing some work to tidy these up, but in the meantime I created a function that takes the error message and replaces any values.
I want to make the function re-usable for other error messages and wondered if anyone has any advice.
Here is the function with 1 error message currently.
Error message entered: 'Minimum payment_amount is $10.'
Error message being returned: 'Minimum payment amount is $10.'
const errorMessageConvertor = (errorMessage) => {
if (errorMessage !== undefined) {
const convertedErrorMessage = errorMessage.toString();
return convertedErrorMessage.replace("payment_amount", "payment amount");
}
};
Maybe something like that
const errorMessageConvertor = (errorMessage, keyToReplace, valueToReplace) => {
if (errorMessage !== undefined) {
const convertedErrorMessage = errorMessage.toString();
return convertedErrorMessage.replace(keyToReplace, valueToReplace);
}
};
// usage
errorMessageConvertor('Minimum payment_amount is $10.','payment_amount','payment amount')
If you only want to get rid of underscores then this should solve the problem, it will replace all the underscores with spaces.
const errorMessageConvertor = (errorMessage) => {
if (errorMessage !== undefined) {
const convertedErrorMessage = errorMessage.toString();
return convertedErrorMessage.replaceAll('_', ' ');
}
};

parsing err! 'return' outside of function

So, I wanted to add a unban command.
This my code so far:
if (command === ":unban") {
if (!msg.member.hasPermission("BAN_MEMBERS")) {
return msg.channel.send(`**${msg.author.username}**, You do not have perms to unban someone`);
}
if (!msg.guild.me.hasPermission("BAN_MEMBERS")) {
return msg.channel.send(`**${msg.author.username}**, I do not have perms to unban someone`);
}
let userID = args[0]
msg.guild.fetchBans().then(bans=> {
if (bans.size == 0) return
let bUser = bans.find(b => b.user.id == userID);
if (!bUser) return
msg.guild.members.unban(bUser.user);
});
}
when I run it it gives me this error:
parsing error: 'return' outside of function
can somebody help me out on this because im new to this stuff
You cant use a return function, with nothing to return to. Returning out of those if-cases is not possible. You could put that code in a separate function and call that, then returning would not bring an error. A simple rewrite of your code using a bool should fix the issue tho:
client.on("messageCreate", message => {
if(message.content === "!ping"){
message.channel.send("pong")
} else if(message.content === '!unban') {
let permissionToKick = true;
if(!message.member.hasPermission("BAN_MEMBERS")) {
permissionToKick = false
message.channel.send(`**${message.author.username}**, You do not have perms to unban someone`)
}
if(!message.guild.me.hasPermission("BAN_MEMBERS")) {
permissionToKick = false
message.channel.send(`**${message.author.username}**, I do not have perms to unban someone`)
}
if(permissionToKick) {
let userID = args[0] //args[] are not defined, and this will throw an error
message.guild.fetchBans().then(bans=> {
if(!bans.size === 0) {
let bUser = bans.find(b => b.user.id === userID)
if(bUser) {
message.guild.members.unban(bUser.user)
}
}
})
}
}
})
PS: I see you are using args[] in your code, but args are nowhere to be defined. I won't write all the code for you, since Stackoverflow is not Code-writing platform. I would advise you learn the basics of JavaScript and discord.js first.
A good source to learn JavaScript is W3Schools. If you understand the basics, I advise you to read the Documentation of Discord.js or follow the Discord.js guide

Not finding an easy solution to unban command for Discord Bot

I have been trying to get the unban command to work for the past 2 days, but I haven't found an easy solution for it, I keep getting errors like ".find()" isn't a function, or can't define "id". And I just don't get what I need to do. PS.: I am a noobie when it comes to code.
It's also worth mentioning that I have gone through many variations of this code and I have ended at this, probably previous iterations of the code were closer to the actual solution.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = "+";
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
const { content } = msg;
if (!content.startsWith(prefix)) return;
const args = content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
switch(command) {
case "ping" : {
let latency = Date.now() - msg.createdTimestamp;
let latencyOfAPI = Math.round(client.ws.ping);
msg.reply("This is the latency between the message and the response: " + latency + "." + "\nThis is the API latency: " + latencyOfAPI + ".");
break;
}
case "pong" : {
msg.reply("ping");
break
}
case "ban" : {
const user = msg.mentions.members.first();
if (user) {
msg.guild.members.ban(user);
msg.reply("The user " + user + " has been banned.")
} else {
return msg.reply("There is no one to ban.").catch(console.error);
}
break
}
case "unban" : {
const user = client.users.cache.find(user => user.username == "").id;
let banList = msg.guild.fetchBans();
if(banList = 0) {
return msg.reply("This user isn't in the community, or he is not banned.");
} else {
banList.find(user)
msg.guild.members.unban(user);
msg.reply("User " + user + " has been unbanned.")
}
break
}
}
});
client.login('.....');
Try this:
case "unban" : {
const user = client.users.fetch(args[1]).catch((err) => console.log(err));
user.then((u) => {
if (!args[1]) {
return msg.reply("Enter ID to unban")
} else {
if (u) {
msg.guild.members.unban(u).then(() => {
msg.reply("The user " + u.username + " has been unbanned.")
}).catch((err) => console.log(err))
} else {
return msg.reply("Cannot Find User")
}
}
})
break
Usage: [prefix]unban [ID] e.g [prefix]unban 3426743678738 (type in text channel)
Tip #1: Try to use .then() & .catch() on function which return a promise. You can use .then() to confirm that you've successfully unbanned a user and .catch() to see why there was a issue with unbanning a user.
Tip #2: Make an if statement which checks if the user running this command has the right permissions before trying the code i.e BAN_MEMBERS & ADMINISTRATOR
Also Note: .fetchBans() returns a collection and Promise

Issue with Java Discord.js Modmail System

I have been trying to make a discord ModMail system on my bot and there is an error that I can't understand my code is below:
client.on('message', message => {
if (message.author.bot || !message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/+ /)
if (!message.channel.name.includes('modmail')) {
return;
} else {
if (isNaN(args[0])) {
return message.channel.send('Sorry but that is not a valid user')
}
let storage = message.guild.members.cache;
let memberId = storage.find(member => member.id.toLowerCase() === args[0]);
if (memberId) {
const msg = message.content.slice(args[0].length + prefix.length).split(" ").join(" ");
let embed = new Discord.MessageEmbed()
.setThumnail(message.author.displayAvatarURL())
.setDescription(`<#${message.author.id}>\n------------\n${msg}`)
.setColor('#599cff')
.setFooter('ModMail System')
.setTimestamp();
client.users.fetch(args[0]).then(user => user.send(embed).catch(err => console.log(err)));
message.channel.send('Your message was sent to the staff team! Please be patient for your reply.')
} else {
return message.channel.send('Could not find the user sorry.');
}
}
});
client.on('message', message => {
var msg = message.content;
var n = message.author.username;
if (message.channel.type === 'dm') {
if (message.author.bot) return;
let blacklisted = ['word1', 'word2']
let foundInText = false;
for (var i in blacklisted) {
if (message.content.toLowerCase().includes(blacklisted[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
return message.channel.send('Please do not use foul language in the message. (if you must please cover it with symbols *not letters*)');
}
message.channel.send('Your message was sent to the staff team! Please be patient for your reply.');
const mailMessage = `${message.author.id} ${msg}`
client.channels.fetch('795031406442315816').then(user => user.send(mailMessage).catch(err => console.log(err)));
}
});
The error that is shown is:
SyntaxError: Invalid regular expression: /+ /: Nothing to repeat
This has been confusing me for a while (I am new to code) please if you know how to fix this it would help a lot thank you.
I think the error is because there is a problem here:
const args = message.content.slice(prefix.length).split(/+ /)
If you change .split(/+ /) to .split(' ') or .split(/ /) it would work.

How to fix ReferenceError

After some modification, instead of message is not defined, it is receivedMessage.channel.bulkdelete(args[0].then (() => {
ReferenceError: receivedmessage is not defined. I am not really sure myself what does that mean because im new to node.js and javascript. If there is any mistakes I made please tell me!
client.on('message', (receivedMessage) => {
if (receivedMessage.author == client.user) { // Prevent bot from responding to its own messages
return
}
if (receivedMessage.content.startsWith("?")) {
processCommand(receivedMessage)
}
})
function processCommand(receivedMessage) {
let fullCommand = receivedMessage.content.substr(1) // Remove the leading exclamation mark
let splitCommand = fullCommand.split(" ") // Split the message up in to pieces for each space
let primaryCommand = splitCommand[0] // The first word directly after the exclamation is the command
let arguments = splitCommand.slice(1) // All other words are arguments/parameters/options for the command
console.log("Command received: " + primaryCommand)
console.log("Arguments: " + arguments) // There may not be any arguments
if (primaryCommand == "help") {
helpCommand(arguments, receivedMessage)
} else if (primaryCommand == "multiply") {
multiplyCommand(arguments, receivedMessage)
} else if(primaryCommand == "clear") {
clearCommand(arguments, receivedMessage)
} else {
receivedMessage.channel.send("I don't understand the command. Try `?help`, `?multiply` or '?clear'")
}
function helpCommand(arguments, receivedMessage) {
if (arguments.length > 0) {
receivedMessage.channel.send("It looks like you might need help with " + arguments + ".Try `!multiply 2 4 10` or `!multiply 5.2 7`")
} else {
receivedMessage.channel.send("I'm not sure what you need help with. Try `?help [topic]`")
}
}
function multiplyCommand(arguments, receivedMessage) {
if (arguments.length < 2) {
receivedMessage.channel.send("Not enough values to multiply. Try `!multiply 2 4 10` or `!multiply 5.2 7`")
return
}
let product = 1
arguments.forEach((value) => {
product = product * parseFloat(value)
})
receivedMessage.channel.send("The product of " + arguments + " multiplied together is: " + product.toString())
}
}
function clearCommand (arguments, receivedMessage) {
if (!recievedMessage.member.hasPermission("MANAGE_MESSAGES"))
return receivedmessage.reply("You have no permission to use this command.Sad.");
if (!args[0])
return receivedMessage.channel.send("Please specify a number.")
}
receivedmessage.channel.bulkDelete(args[0]).then(() => {
receivedMessage.channel.send(`Cleared ${args[0]} messages.`).then(msg => msg.delete(5000));
}
,)
You need to use receivedMessasge instead of message, as thats the name you choose in that function.
It kinda seems like you dont really have much experience and I would recommend you to read the offical discord.js guide: https://discordjs.guide . It will teach you how to write Discord Bots without needing to copy a lot of weired stuff into your Code!
1) You have defined receivedMessage instead of messsage
2) The code for clear command is not in any function and it executes once, before any messages.
You need to use receivedMessage instead of message and insert the code in the processCommand function
if (primaryCommand == "help") {
helpCommand(arguments, receivedMessage)
} else if (primaryCommand == "multiply") {
multiplyCommand(arguments, receivedMessage)
} else if(primaryCommand == "clear") {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.reply("You have no permission to use this command.Sad.");
if (!args[0]) return message.channel.send("Please specify a number.")
message.channel.bulkDelete(args[0]).then(() => {
message.channel.send(`Cleared ${args[0]} messages.`).then(msg => msg.delete(5000));
});
// or create a function for this command
} else {
receivedMessage.channel.send("I don't understand the command. Try `?help` or `?multiply`")
}

Categories

Resources