For some reason my if statement triggers no matter what - javascript

bot.on('message', async msg => {
let args = msg.content.split(" ");
if(!msg.guild) return;
if(msg.author.bot) return;
if (msg.content === '<prefix>') {
const req = await GuildModel.findOne({ id: msg.guild.id });
if (!req) return msg.reply('Sorry! doc doesnt exist.');
return msg.reply(`Found a document! Prefix: ${req.prefix} Suffix: ${req.suffix}`);
}else if(msg.content.includes(`<setprefix>`)) {
const req = await GuildModel.findOne({ id: msg.guild.id });
if(!req) return msg.reply('Sorry there was an error!');
await GuildModel.findOneAndUpdate({ id: msg.guild.id }, { $set: { suffix: `${args[1]}`}}, { new: true})};
return msg.channel.send('Your new prefix is asdasd')
})
So essentially my problem is that when I test the bot any message sent in any server the bot is in is responded with Your new prefix is asdasd Ive tried to troubleshoot but Ive hit my limit and cant figure it out. Im using discord.js and have received no errors in my console! Thanks for any help!

If you indented your code more consistently you would immediately notice that your curly braces must be mismatched, because the } on the last line can not both close the elseif block and the async msg => { block.
The reason your code compiles is that the elseif block is ended by an extra } on the line await GuildModel.findOneAndUpdate(...)};, so return msg.channel.send(...) is outside the if statement, and always executed.
To avoid such errors, be mindful to always indent your code consistently (one brace per indent level). Also, try to avoid writing lines that are so long and convoluted that an extra } is not noticed.

Related

How to prematurely finish a pipeline within a JS transform

Problem: I am dealing with large files (>10GB).
Sometimes I want to process the complete files and sometimes I just want to sample a few lines.
The processing setup is a pipeline:
pipeline(
inStream,
split2(),
sc,
err => {
...
}
);
sc is a transform that essentially counts some flags in the file.
The code works fine when processing the complete file but never produces the output in ... if I want to exit from the transform before inStream has finished.
_transform(chunk,encoding,done) {
let strChunk = decoder.write(chunk);
if(strChunk === '\u0003') {
this.push('\u0003');
process.exit(0);
}
if(strChunk.startsWith("#")) {
done();
} else {
if(this.sampleMax === 0) {
this.push('\u0003');
//process.exit(0);
} else
if(this.sampleMax > 0)
this.sampleMax--;
let dta = strChunk.split("\t");
let flag = dta[1].trim();
this.flagCount[flag]++;
done();
}
if I use //process.exit(0), the code in the pipeline following sc is not reached.
if I only use this.push('\u0003'); the complete inStream is processed.
The question is how to properly terminate the transform and continue with the downstream pipeline without completely reading inStream.
One solution would be to throw an error or create an error implicitly by destroying the stream. Both options are shown in the code below.
_transform(chunk,encoding,done) {
let strChunk = decoder.write(chunk);
if(strChunk === '\u0003') {
this.push('\u0003');
process.exit(0);
}
if(strChunk.startsWith("#")) {
done();
} else {
if(this.sampleMax === 0) {
//Either of the following lines can solve the problem.
throw("PLANNED_PREMATURE_TERMINATION");
this.destroy(); //=> Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
} else
if(this.sampleMax > 0)
this.sampleMax--;
let dta = strChunk.split("\t");
let flag = dta[1].trim();
this.flagCount[flag]++;
done();
}
The next step is to react to the errors generated in the above code in the pipeline.
pipeline(
inStream,
split2(),
sc,
err => {
if(err && (err === "PLANNED_PREMATURE_TERMINATION") ||
(err === "Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close") {
//do whatever should happen in this case
} else {
//stream was completely processed
//do whatever should happen in this case
}
}
);
Since err contains the message that was thrown during premature termination, we can react to that specifically and present the partially aggregated data in sc. This solved the initial problem and seems to be the only obvious route in this situation. Therefore, I post this solution. Would be great to have other (more elegant) solutions.

Javascript error handling catches nothing

I have strange error generation function.. It is from HttpRequest like this
public async request(method, url, data, headers = {}){
let init { method: method };
if (data) {
let payload: string = JSON.stringify(data);
init.body = payload;
}
if (this.key) headers["x-auth-token"] = this.key;
headers["Content-Type"] = "application/json";
init.headers = headers;
let result = await fetch(url, init);
if (result.status == 200) return result;
throw { status: result.status, message: result.statusText };
}
Now, I am trying to catch with something like this:
try {
let img = await HttpRequest.request("GET", "/login");
let text = await img.text();
let str = "data:image/jpeg;base64, " + text;
this.setState({ avatar: str });
} catch (err) {
console.log("log here");
}
What is strange, was that nothing catched, even though I deliberately made an error, no "log here" shows anywhere in console.
But if I change it like this:
try {
let img = await HttpRequest.request("GET", "/login");
let text = await img.text();
let str = "data:image/jpeg;base64, " + text;
this.setState({ avatar: str });
} catch (err) {
console.error("log here"); // <--- console.error() instead of console.log
}
Then the console showed "log here" error. It is strange that difference between console.log and console.error inside same catch clause treated different way.
Can anyone help me here, where did I do wrong?
Thank you
EDIT: If it made difference, the code behaved correctly before, when I throw the error as throw "ERROR " + result.status + ": " + result.statusText; at my request() function. It was back to normal when I changed it back to throw string instead of object.
Well.. I am not sure if this is the answer, or proper answer, but the question turned out not programming or javascript nature.
After I tried Parth Savaliya's comment, I had some ideas, and I tried to make this very simple function
function testError() {
throw {aa: 'test', bb: 'bb'};
}
try {
console.log("nothing here");
testError();
} catch (err) {
console.log(err);
console.log('foo');
}
and every time I feed different object, any console command, including console.error() gave me different result. The previous console.error() was just luck. It was varying from unintelligible mumble jumble, various strings, to no output, and finally crashed Google Chrome. There was no pattern, and seemed random. I also tried to replace console.log() in catch clause with an XHR request to server, and it worked fine. Firefox worked fine. So I conclude that it was chrome's console that was having problem. Tried to remove all extensions, cleaned cache and everything, reinstall chrome, and it was solved.
I think you're currently viewing only error logs, like
this...!
Please click on the first item on the list, to show all types of log, like
this...!

Need help defining message argument, not sure what's wrong?

I've been working on a simple help command that's supposed to give in depth help with certain commands when the argument for the command is put in, if it's not put in it's supposed to throw out a general command list.
Function snippet:
function help(helpcomm) {
if (helpcomm == "say") {
message.channel.send("Say command makes me repeat the words you type. EG. if you type `p!say Hello World!` I'm going to delete your message and say `Hello world!`.");
} else
if (helpcomm == "ping") {
message.channel.send("Ping command checks the latency between me, the node I'm hosted on and the API latency.");
} else
if (helpcomm == "purge") {
message.channel.send("Purge command deletes a number of latest messages you choose from 2 to 99. EG. if you type `p!purge 20` I will delete the last 20 messages.");
} else
if (helpcomm == "joke") {
message.channel.send("Joke sends a random joke from my database.");
} else
if (helpcomm == "roll") {
message.channel.send("Roll makes me roll a dice from 1 to 20 sides. Basically a random number generator.");
} else
if (helpcomm == "creator") {
message.channel.send("Gives info about my creator. Currently outdated.");
} else
message.channel.send("For specific command help type: `p!help [command]` \nHere are my commands: `p!say [words], p!ping, p!purge [number], p!joke, p!roll [number], p!creator`");
}
And command that's supposed to take the argument:
if (command === "help") {
let text = args.join(' ');
await message.channel.send(help(text));
}
I can node the bot with no errors thrown, but when i actually input the prefix with the command with or without an argument it throws an error saying "Message not defined."
Help would be very much appriciated, if you can explain what I'm doing wrong and how to fix it that would be amazing, no spoon feeding.
If I need to provide any additional information I will put it into comments.
That error indicates that the message variable does not exist in the scope of the help function. If you want to be calling message.channel.send inside your help function, then you'll need to pass message into it:
function help (helpComm, message) {
if (helpcomm == "say") {
return message.channel.send("Say command makes me repeat the words you type. [etc]');
}
//...
return message.channel.send("For specific command help [etc]")
}
// called like:
client.on('message', async function(message) {
//...
if (command === "help") {
let text = args.join(' ');
await help(text, message);
}
});
That said though, It's not clear to me that that's what you intend to do, since this line is already calling message.channel.send, and is apparently expecting help to return a string:
await message.channel.send(help(text));
If you just want help to produce a string, then there's no need to pass message to it, since only the main code needs to interact with the message object:
function help (helpComm) {
if (helpcomm == "say") {
return "Say command makes me repeat the words you type. [etc]';
}
// ...
return "For specific command help [etc]";
}
// called like:
client.on('message', async function(message) {
//...
if (command === "help") {
let text = args.join(' ');
await message.channel.send(help(text));
}
});

Ban/kick command crashes on use

So, I am making a public discord bot, but I am having trouble with one part of my script. My kick/ban commands are made to be done $ban #user It has to be done in a ping. Since this is public, I really want to fix this. I don't want one person to mess up and crash it to crash it for all servers. If someone does $ban user not in a ping, it crashes the bot. Here is my code:
client.on("message", (message) => {
if (message.content.startsWith("$kick")) {
if (!message.member.roles.find("name", "MODS"))
return;
// Easy way to get member object though mentions.
var member = message.mentions.members.first();
// Kick
member.kick().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully kicked :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
I don't want my bot to keep crashing to ruin the use for others, can anyone help out?
Your code crashed when you have no mention because you did not catch this use case.
Adding a simple catch, with a return for example, should work for you :
client.on("message", (message) => {
if (message.content.startsWith("$kick")) {
if(!message.member.roles.find("name", "MODS"))
return;
// Easy way to get member object though mentions.
var member= message.mentions.members.first();
// No mentions catch
if (member === undefined) return;
// Kick
member.kick().then((member) => {
// Successmessage
message.channel.send(":wave: " + member.displayName + " has been successfully kicked :point_right: ");
}).catch(() => {
// Failmessage
message.channel.send("Access Denied");
});
}
});
I think what is happening when you type $ban user (Which isn't a mention), and later when you assign var member = message.mentions.members.first(); it gives you null (Because no one was mentioned). Try to make sure that message.mentions.members isn't empty.
Cheers :)

Issue with Error handling on Firebase remove function

The promise that is returned by userRef.remove() is not giving any error, it always goes to then block even though if I change the non existing path dbRef.child('userssafasfsadf/' + userID); like so.
function deleteButtonClicked(e) {
e.stopPropagation();
var userID = e.target.getAttribute("userid");
const userRef = dbRef.child('users/' + userID);
userRef.remove()
.then(() => {
console.log('success!, show alert now');
})
.catch(err => {
console.log('errorcode', err.code);
});
}
Any help would be appreciated. Thanks.
It sounds like you're expecting the remove() function to generate an error if there was no data at the given location. It doesn't work that way, because the remove() is not transactional. Someone else could have removed the data a split second ahead of you, and that's OK. Database operations only return errors when a security rule is violated.

Categories