Hello!
I’m making a custom command for Nightbot that, depending on the user’s query if they type 1, 2 or 3 (or any combination of the 3), the command will return one of the variables (named: one, two, three, four).
The example below seems to work fairly well when you actually type 1, 2 or 3 or any combination of those numbers, but as soon as you type a different number not in the code (say, 0 or 4), or any text for that matter, Nightbot returns the error [Error Connecting to WebEval Service]
Could someone explain what is happening please?
Thanks so much in advance!
Code:
$(eval
q="$(query)";
one=“Number 1”;
two=“Number 2”;
three=“Number 3”;
four=“Invalid Number”;
result=[];
for (const num of q.match(/[1-3]/g) || [])
switch (num) {
case “1”: result.push(one);
break; case “2”:
result.push(two);
break;
case “3”: result.push(three);
break;
default: result.push(four)
};
result.join(/)
)
Apologies in advance, I forgot how to wrap that whole thing in a code block I’ll post the code below in a single line for ease of testing:
$(eval q="$(query)"; one=“Number 1”; two=“Number 2”; three=“Number 3”; four=“Invalid Number”; result=[]; for (const num of q.match(/[1-3]/g) || []) switch (num) { case “1”: result.push(one); break; case “2”: result.push(two); break; case “3”: result.push(three); break; default: result.push(four)}; result.join(/))
NOTE: That “default” case in the switch for instance, I figured it would trigger whenever there isn’t a match. Instead that case is never triggered/reached.
The for loop block is only executed when there is a match (“1”, “2”, or “3”). So when there are no matches, the for loop block is never executed, and result is never changed from [], so result.join("/") will be ""
This can be fixed by changing result.join("/") to result.join("/") || four
You can also remove the default case since it will never be reached.
I also recommend changing "$(query)" to decodeURIComponent("$(querystring)") so your command doesn’t break when someone types a " when calling the command.
$(eval q=decodeURIComponent("$(querystring)"); one="Number 1"; two="Number 2"; three="Number 3"; four="Invalid Number"; result=[]; for (const num of q.match(/[1-3]/g) || []) switch (num) { case "1": result.push(one); break; case "2": result.push(two); break; case "3": result.push(three); break; } result.join("/") || four)
You can wrap code in code blocks by surrounding it with ```
Oh,… sorry for the double post but I must have missed the part you spoke about querystring… Does that trick get around the whole having to use backticks instead of quotation marks and what not?