Discord.js check if message is a number - javascript

I have a discord bot and I'm trying to figure out a way of knowing if a message is a number. Here's the code I have:
if (message.isNumber()){
//do something
}
String.prototype.isNumber = function() {
return /^\d+$/.test(this);
};
When I test it, it does absolutely nothing. Can someone help me out?

You could simply do:
if(isNaN(message.content) return;
else {
//do something
}
If the message is not a number, it would do nothing. Otherwise it would do that what you would like it to do.

Since OP does not provide more context about what message is, I assume message already holds the value that needs to be checked. So I also have to ignore that message could be an object coming from Discord.js, and that the value OP wants to check really is located at message.content, not message. Even if I know Discord.js API, message could be something completely different here.
If the value that needs to be checked really is located at message.content and does come from Discord.js API, checkout #JannikSchmidtke answer, he might know more about the Discord.js API and the context about this question.
Case A : You want to check if the type of a variable is a number
You can use typeof to check the type of it :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
if (typeof message == 'number') { console.log('is a number'); }
if (!(typeof message == 'number')) { console.log('is a not a number'); }
Case B : You want to check a variable if it is a valid number
You could use isNaN in certain cases. Here a string could be a valid number as well:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
isNaN(123) // false, it is a number
isNaN('123') // false, it is a number
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true, it is not a number
isNaN('10px') // true, is is not a number
You will also find a very good and complete answere here : (Built-in) way in JavaScript to check if a string is a valid number

Related

How do you catch an error in this timer code for discord.js?

I'm making a discord bot in javascript, and I'm trying to make it so when someone inputs a time that isn't valid, that it tells you that you have an error, instead of crashing the bot.
I've been working on it for a while and cannot find an answer to how to stop it from crashing the bot and just replying with something like, "That is not a valid number." Could someone help me?
client.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'timer':
let time = (args[1]);
if (!time) {
return message.reply("You didnt specify a time!");
}
message.reply(`Timer started for ${ms(ms(time))}`)
setTimeout(function() {
message.reply(`your timer has stopped`)
}, ms(time));
break;
}
});
isNaN()
isNaN is a JavaScript function that returns a boolean to determine whether a given input is a number or not. It stands for is Not a Number.
A few examples:
isNaN(8); // Expected outcome 'false' since 8 is a number
isNaN('hello!'); // Expected outcome 'true' since 'hello!' is not a number.
// It also works for numbers inside of a string:
isNaN('23'); // Expected outcome 'false' since 23 is a number.
You can read more about isNaN() here
In your code
From this logic, we're able to use this for your code by checking whether or not the second argument was a number or not => in this case, the variable 'time':
if (isNaN(time)) return message.reply('Please enter a number!');
You can use
if(isNaN(time)) return message.reply("That is not a valid number.")
isNaN() returns true for "Not a Number" values, which should be exactly what you need, you can read more about it here.

Replacing certain letters in discord.js

Heyo! Tried everything but can't figure this out. I have a command where you mention an user and from that mention will bot take his ID. But the ID looks like mention (<#!id>) and I need replace that mention into ID only. Here's code.
const mentionUser = message.mentions.users.first();
if(args[0] == mentionUser) {
let object = mentionUser.id;
id = object.replace('#', '');
} else {
id = args[0];
}
console.log('ID:', id);
I can't figure out if its value, object or array? So I tried every single function to convert it into a string so I can replace certain letters. String(), stringify, regexp etc... Nothing seem to be working.
Console return:
ID: <#!191243099123482625>
Well first of all, your if condition is not even being met. You're doing if (args[0] == mentionUser) and that is never true. As you can see from your console return, args[0] looks like: <#!id>. Whereas this is what mentionUser looks like as a String: <#id>. The exclamation point in the former will make it never match up with the latter, even if they are the same mention.
The exclamation point actually indicates that this is a guild member mention (meaning the user was mentioned in a guild). So the code you have currently would be very close to working if the message were a DM message instead of a guild message.
What you need to do is you need to check if the mentionUser even exists (in the event that no user was mentioned at all), and if it does exist you simply need to do mentionUser.id to get the user's ID. Replacing is only necessary to ensure that the first arg is a mention, by removing the exclamation point from the first arg. Here's an example:
const mentionUser = message.mentions.users.first();
if(mentionUser && args[0].replace('!', '').match(mentionUser)) {
id = mentionUser.id;
} else {
//Mention was not in the first arg, treat first arg as an ID instead
id = args[0];
}
console.log('ID:', id);

Troubles with the OR logical processor when coding discord bot

This is my current code, I'm wondering whether i have to use a mess of 'else if,' or if i can keep it compact.
if (message.content.toLowerCase().includes(`word`||`word2`||`word3`||`word4`||`wd`||`wd2`||`wd3`||`wd4`)){
message.reply('don\'t swear in front of me!');
message.delete({ timeout: 100 })
}})
The issue is that only the very first string, word, is being tested for.
All the other strings give no response when i type them into discord.
You have the right idea but you're using the || operator wrong. The || operator checks whether the statement on the left is false/null/undefined and if so, checks the statement on the right. The way you've defined it ('word'||'word2'||...), the operator takes the left statement, in this case the string 'word', and checks if it's false/null/undefined which it isn't because it's a string. Therefore it never checks any other words.
How I think you meant to use it, is like the following:
if (message.content.toLowerCase().includes(`word`) ||
message.content.toLowerCase().includes(`word2`) ||
message.content.toLowerCase().includes(`word3`) ||
...etc
){
// Code here
}
In theory this would work, but as you can see yourself this is far from clean and will get big and bulky with little effort. A better approach would be with using the Array.some() function which calls a function for each item in an array and returns true when one item passes the function. Take a look at the example below:
// Define an array of all the words that need to be checked.
const arrayOfBadWords = ['word', 'word2', 'word3', ...];
if (arrayOfBadWords.some(word => message.content.toLowerCase().includes(word))) {
message.reply('The message contains a blacklisted word.');
} else {
message.reply('The message looks absolutely fine.');
}

How to make a bot identify you either by ID or permission

I'm having a problem where my bot only identifies by permission, I even made sure that my ID was where the !message.author.id == was. I removed the ! from !message.author.id and it my bot still relies on the permission
I tried
- Removing the ! from the !message.author.id
- Adding a else after the return message
- Finding similar issues
- And searched the Discord.JS documentation.
if(!message.author.id ==`329023088517971969` || !message.member.hasPermission(['MANAGE_GUILD'])) return message.channel.send(`You don't have the permissions to do this!`)
<code here>
I expect the output to be that IF the bot finds my ID (the author) is the same as the value after, it would let me pass, OR if both statements are true it would let me pass, OR if the hasPermission was true, it would let me pass.
The actual result is that it only relies on the hasPermission and ignores the author ID.
Basically
Bot should: Either run code after the if() if the author's id is equal to the one shown in the code, or member has the following permissions
When using all negated conditions, you should use the logical AND operator (&&), not the logical OR operator (||).
if (message.author.id !== '329023088517971969' && !message.member.hasPermission('MANAGE_GUILD')) {
return message.channel.send(':x: Insufficient permission.')
.catch(console.error);
}
In English, this code basically says "if this isn't the author's ID and they don't have the permission flag, stop." Logically, it makes more sense than "if this isn't the author's ID or they don't have the permission flag" because if one is true and the other is false, it would stop you.
Consider this example:
const str = 'abcd';
const arr = ['foo'];
if (str !== 'abcd' || !arr.includes('bar')) console.log('This is WRONG.');
// false OR true OUTPUTS true
if (str !== 'abcd' && !arr.includes('bar')) console.log('This is correct (you won\'t see this).');
// false AND true OUTPUTS false
try put the conditions in separate function return true/false and check what its output will be. it could be easier to check which part of condition is not working as it should.
you have to change your condition to this
if(message.author.id !='329023088517971969' || !message.member.hasPermission(['MANAGE_GUILD'])) return message.channel.send(`You don't have the permissions to do this!`)
notice you have !message.author.id =='329023088517971969' which is not correct so you need to change that with message.author.id !='329023088517971969;'
I am not sure I understood the question, but sounds like the following pice of code is enough. I suggest avoiding the usage of negating conditions because is hard to read.
boolean authorHasNotPermission = message.author.id !== '329023088517971969';
boolean memberHasNotPermission = !message.member.hasPermission(['MANAGE_GUILD']);
if (authorHasNotPermission || memberHasNotPermission) {
return message.channel.send(`You don't have the permissions to do this!`)
}

JavaScript - What is a boolean for and how/where can I use it?

I know i can say that something is true or false but what can I do with it after i did that? There has to be more.
Would be great if someone has got an example.
Code is basically just making decisions about data, and acting on those decisions. That's a gross oversimplification, but it's generally true.
Booleans (and things that can "act" as Booleans) are important because they're what if statements and other conditionals use to decide what to do.
As a very simplified, kind-of real world example, imagine:
var correctPassword = "myPassword";
var enteredPassword = (get the entered password);
if (correctPassword == enteredPassword) {
logUserIn();
} else {
showBadPasswordError();
}
== compares two things (strings in this case), and returns a boolean value indicating whether or not the two strings are the same. In this case, if it returns true, that means the user's password was correct, so it uses that information to decide whether or not to log the user in.
Boolean,
in other words:
Yes/No 0/1 True/False
I am not good with coding since I am also in the beginner zone. But what I understood from most people is that the boolean is defining the current state of something/code.
is the light on? Yes..then in the code it will be "true"
No?...then "false"
You can use this in If statements...like
if (lightOn == true) {
//then do this
}
else if (lightOff == false) {
//then do this
}
Somehow in that matter.

Categories