parsing err! 'return' outside of function - javascript

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

Related

Discord.JS (14.0) Random chance to React with Emoji?

I'm very new to JS, and DiscordJS in general.
I am trying to get my bot to have a CHANCE to react to any message from a specific user, with a specific emoji ID.
The documentation I found says to use "client.emojis.find", but I get a TypeError that tells me this is not a function.
Any help is appreciated!
client.on("messageCreate", (message) => {
if (message.author.id === "217900978756780032") {
const otterEmoji = client.emojis.find(
(emoji) => emoji.id === "1028007226859855914"
);
if (Math.random() < 0.5) {
message.react("otterEmoji");
}
}
});
EDIT:
This seems to work, but if anyone has other ideas for a cleaner randomizer, let me know!
client.on("messageCreate", (message) => {
const a = Math.floor(Math.random() * 11);
if (a >= 8) {
if (message.author.id === "217900978756780032") {
message.react("🦦");
}
}
});
I think instead of client.emojis, you need to use client.emojis.cache:
const otterEmoji = client.emojis.cache.find((emoji) => emoji.id = '1028007226859855914'
(based on https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/coding-guides/using-emojis.md#how-does-discordjs-store-emojis)

Reason after blacklisting command Discord.js

I want to add a reason to my blacklists (with the command !blacklist {userid} {reason}) which are visible in the embeds below like .addField ("💬 Reason:", somecode) how can I fix this?
if (command === "blacklist") {
if(!config["allowed-users"].includes(message.member.id)) return;
const user = client.users.cache.get(args[0]);
if(!user) {
return message.channel.send("This user does not exist")
}
if(blacklist.has(user.id)) {
return message.channel.send("This user is already on the blacklist")
}
blacklist.set(user.id, 'blacklisted');
let set = db.fetch(`g_${message.guild.id}`);
var embed = new Discord.MessageEmbed()
.setTitle(":warning: Blacklisted :warning:")
.setColor('#fc5a03')
.addField("👮 Moderator:", message.author.tag)
.addField("👤 User:", user.username)
.addField("🆔 User ID:", user.id)
.addField("🕒 Blacklisted on:", message.createdAt)
.setFooter("© 2020 - 2021 GlobalChat", "https://cdn.discordapp.com/avatars/759021875962576916/cc32b2b08fdd52ae86294516d34532c5.png?size=128")
.setThumbnail(user.avatarURL({ dynamic:true }))
.addField("Unblacklist?", "Please contact <#267818548431290369> or <#331736522782932993>");
client.guilds.cache.forEach(g => {
try {
client.channels.cache.get(db.fetch(`g_${g.id}`)).send(embed);
} catch (e) {
return;
}
});
}
First you'll want to check if there is no reason, this can be simple done by checking, for both approaches, if the second argument is undefined, like so
if (args[1] === undefined) {
const reason = "No reason.";
}
This solution will work for both approaches, since if the second argument is undefined there can be no more after it
You could take reason as an argument.
Inside the command add
const reason = args[1];
OR if you wanted to have the rest of the blacklist args dedicated to the reason you could add something along the lines of
let reason = ""
for (let i = 1; i < args.length; i++) {
// It's very important that i starts as 1, so we do not take the first argument into account for the reason
reason += args[i];
}
And then you can add to the embed
.addField("💬 Reason:", reason);
If you went with the first approach, the blacklist command would work like this
!blacklist 012345678910111213 the_reason_here
// or
!blacklist 012345678910111213 reason
The limitation to this approach is that a multi word reason isn't very intuitive.
If you went with the second approach though, the blacklist command would work like this
!blacklist 012345678910111213 The reason the user was banned and it can go on and on and on as long as the writer wants
You'll want to fetch the reason in the same way that you fetched the user id, like this:
const reason = args[1];
After that, in order to make sure that the reason doesn't show as undefined, you'll want to add a check in the form of an if statement, like this:
if (!reason) {
reason = "No reason";
}
After that, add .addField("💬 Reason:", reason) in the position of fields you want it to be.
Your code should look something like this:
if (command === "blacklist") {
if (!config["allowed-users"].includes(message.member.id)) return;
const user = client.users.cache.get(args[0]);
const reason = args[1];
if (!user) {
return message.channel.send("This user does not exist")
}
if (blacklist.has(user.id)) {
return message.channel.send("This user is already on the blacklist")
}
if (!reason) {
reason = "No reason";
}
blacklist.set(user.id, 'blacklisted');
let set = db.fetch(`g_${message.guild.id}`);
var embed = new Discord.MessageEmbed()
.setTitle(":warning: Blacklisted :warning:")
.setColor('#fc5a03')
.addField("👮 Moderator:", message.author.tag)
.addField("👤 User:", user.username)
.addField("🆔 User ID:", user.id)
.addField("🕒 Blacklisted on:", message.createdAt)
.addField(("💬 Reason:", reason)
.setFooter("© 2020 - 2021 GlobalChat", "https://cdn.discordapp.com/avatars/759021875962576916/cc32b2b08fdd52ae86294516d34532c5.png?size=128")
.setThumbnail(user.avatarURL({
dynamic: true
}))
.addField("Unblacklist?", "Please contact <#267818548431290369> or <#331736522782932993>");
client.guilds.cache.forEach(g => {
try {
client.channels.cache.get(db.fetch(`g_${g.id}`)).send(embed);
} catch (e) {
return;
}
});
}

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`")
}

Error: Unexpected Identifier When using an eval command

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).

Leave Command Discord JS

Leave command not working on my Discord bot which is written in JS.
This is the snippet of code I'm using.
if(command == 'leave') {
client.leaveVoiceChannel;
However the command which should make the bot leave the voice channel does not seem to work. Here is how I'm using the code.
const Eris = require('eris');
const client = new Eris(require('./config.json').token, { maxShards: 1 });
fs = require('fs')
var stations = fs.readFileSync("./stations.txt", {"encoding": "utf-8"}).toString()
client.connect();
client.on('ready', () => {
console.log('Ready to go!')
})
client.on('messageCreate', message => {
if(message.author.bot) return;
if(message.content.startsWith('!')) {
let command = message.content.substring(1).split(" ")[0];
let args = message.content.substring(2 + command.length);
if(command == 'leave') {
client.leaveVoiceChannel;
} else if(command == 'streams') {
message.channel.createMessage(stations);
} else if(command == 'radio') {
if(args == '') return message.channel.createMessage(`:exclamation: Please specify the radio stream example: **!radio <stream> or use command **!streams** to see list.`);
if(require('./stations.json')[args]) {
if(!message.member.voiceState.channelID) return message.channel.createMessage(`:exclamation: You need to be in a voice channel to play that stream.`);
client.joinVoiceChannel(message.member.voiceState.channelID).then(vc => {
if(vc.playing) vc.stopPlaying();
message.channel.createMessage(`:radio: You are listening to Streaming station **${args}**. To change the stream use **!radio <stream>**`);
vc.play(require('./stations.json')[args]);
})
} else {
return message.channel.createMessage(`:frowning2: I cannot find a radio stream with that name. Make sure it has capitals and the correct spelling. Type **!streams** to see stream list.`);
}
}
}
})
I'm not sure where I'm going wrong here.
if(command == 'stopstream') {
client.leaveVoiceChannel(message.member.voiceState.channelID);
message.channel.createMessage(`Thanks for tuning in!`); }

Categories

Resources