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);
Related
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
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.');
}
I am making a Discord Bot that separates messages into categories. How can I change it so the message doesn't have to explicitly include !example and rather say the category if the message at least includes it?
For example
bot.on('message' , msg=>{
if(msg.content === "!part-installations"){
msg.reply("Re Category: Part Installations");
}
})
The following code only makes the bot state the category if it specifically states !part-installations with no other words. How can I modify the code so that it can still state the category if it at least has for example !part-installations?
Looks like you could use a regex, which just checks to see if msg.content contains your substring.
if (/!part-installations/gi.test(msg.content)) { }
You could also use .indexOf and if the value is > -1, the substring is in msg.content:
if (msg.content.indexOf('!part-installations') > -1) { }
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!`)
}
My code is as follows:
async run(message, args)
{
if(message.content.split(" ").length === 3 && message.content.split(" ")
[0] == '!suspend' && message.content.split(" ")[1].startsWith("<") &&
message.content.split(" ")[1].endsWith(">"))
{
var nab = message.content.split(" ")[1]; // 2nd item in array when text is split by spaces, (ex. `#user`)
var nabwoo = message.content.split(" ")[2]; //3rd item in array when the text is split by spaces, (ex. `12h`)
let role = message.guild.roles.find(r => r.name === "Suspended");
//nab is the users id
let member = message.mentions.members.first();
member.addRole(role);
message.channel.sendMessage('Done.');
}
}
My code is supposed to apply a role called 'Suspended' to someone after a message like !suspend #user blank. Everything works great, except I'm unsure how to remove a role after a certain amount of time. There is the method member.removeRole(role) but how would I do this automatically after a specified amount of time? I want there to be a 3 command input. !suspend #person timeInHours (with or without units). As I said, I want it done automatically so a user doesn't have to remove the role with a command. I also want to be able to input other commands (basically suspend other people) while the bot is counting the time until the unsuspension. How would I go about doing this? An idea I have is to perhaps check every minute if it's been > x number of minutes since the suspension.
I'm not completely sure as I'm new to this as well, BUT since you delete a message after sometime using .then(msg => {msg.delete(600)}) I would assume, you could do something similar, like replace the msg.delete(600), with a method to get rid of roles sorry if this wasn't useful I was just suggesting a way you could take this.