I want to make a switch for discord.js, where a mentioned role gets removed when the user already has it, and if he doesn´t have it, it gets attached. So the code here is
let tempRole = message.guild.roles.find("name", args);
if(message.member.roles.has(tempRole)) {
console.log(`User has the role`);
}
args is the array for the command params, like "!role [role name with spaces]"
So if I have the role "Test", and I type "!role Test" it outputs "User has the role"
so how is the code for the opposite, if the user doesn´t have the role?
Because
else if(message.member.roles.has(!tempRole)) {
console.log(`User has not the role`);
}
isn´t really working, but the '!' is the only thing i know to negate the result
The ! operator negates whatever is found on the right side, in your case you are only negating the tempRole, however what you really want is to negate the result of the has call, like this:
!message.member.roles.has(tempRole)
Nonetheless since there is already an if statement verifying if the user has the role you could just use else
let tempRole = message.guild.roles.find("name", args);
if(message.member.roles.has(tempRole)) {
console.log(`User has the role`);
} else {
console.log(`User has not the role`);
}
Or even shorter with the ternary operator
message.member.roler.has(tempRole)
? console.log('User has the role')
: console.log(`User has not the role`);
Related
I'm new at JS and I'm trying to make my bot give a specific role to a specific member.
If you can help me, please, do this.
The code:
bot.on("message", (msg) => {
if ((msg.content === "!give", role, member))
var role = msg.guild.roles.cache.find((r) => {
return r.name === "convidado astolfofo";
});
var member = msg.mentions.members.first();
member.roles.add(role);
console.log(member);
console.log(role);
});
The errors I encountered:
(node:2364) UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
TypeError: Cannot read property 'add' of undefined discord.js
There are a couple of errors with your code. I'm not sure what you tried to do with if ((msg.content === "!give", role, member)) -- probably checking if the message starts with !give and if there is a role and a member -- but it won't work like that in JavaScript. You need to check them separately and once these variables are defined.
If you check if msg.content === "!give" but you also want the member to mention a member, it will never be true. If the whole message is just !give, there is no mentioned user. If there is a mentioned user, msg.content will be more than !give. Try to check if the message.content starts with "!give".
Next, if you don't use curly braces following your if statement, only the next line is inside that statement. So you try to check if the command is !give, and if it is, you search for a role, but the following lines where you check where you add the role are outside of this statement. It means, it runs on every incoming message. Try to use curly braces.
It's also a good idea to check permissions and send replies to let the user know if there are any missing ones.
Check the working example below, I've added comments to make it easier to understand:
bot.on('message', async (msg) => {
if (msg.content.startsWith('!give')) {
// check if the message author has the permission to add a role
if (!msg.member.hasPermission('MANAGE_ROLES')) {
return msg.reply('You need `MANAGE_ROLES` permission to add a role');
}
// check if the bot has the permission to add a role
if (!msg.guild.me.hasPermission('MANAGE_ROLES')) {
return msg.reply('I do not have `MANAGE_ROLES` permission to add a role');
}
// check if there is a member mentioned
const member = msg.mentions.members.first();
// if there is none, send a reply
if (!member) {
return msg.reply("Don't forget to mention someone!");
}
// search for the role
// don't forget that it's case-sensitive
const role = msg.guild.roles.cache.find((r) => r.name === 'convidado astolfofo');
// check if the role exists
if (!role) {
return msg.reply("Oh-oh, I can't find the role `convidado astolfofo`");
}
// try to add a role
try {
await member.roles.add(role);
msg.reply(`Role added to ${member}`);
} catch (error) {
console.log(error);
msg.reply('Oops, role not added, there was an error');
}
}
});
You seem to be using return incorrectly. Try this:
bot.on("message", (msg) => {
if ((msg.content === "!give", role, member))
var role = msg.guild.roles.cache.find(r => r.id === "<role id goes here>");
var member = msg.mentions.members.first();
member.roles.add(role);
console.log(member.username);
console.log(role.name);
});
I also changed your console.log statements since your console would get spammed with objects
I am returning a number from a php call. The console is printing the number correctly when I return the value in a subscribe function. When I try to run an if statement to act on the return I am receiving an error in my code that I don't know how to fix. I looked around, but couldn't find any answers to this problem.
This is all happening inside of a subscribe function. I can't refer to the variable accountStatus outside of the subscribe.
this.apiService.checkAccountStatus().subscribe((accountStatus)=>{
console.log("user account", accountStatus);
if(accountStatus = 0)
{
//account doesn't exist
console.log("user doesn't exits.", accountStatus);
}
if(accountStatus = 1)
{
//account does exist
console.log("user does exist.", accountStatus);
}
})
Debugging Errors I am receiving:
Type 'number' is not assignable to type 'Account_Info'.ts(2322)
Account_Info is the name of the ts file I am using to access the database. In my apiService.checkAccountStatus() function this is what it looks like:
checkAccountStatus(){
return this.httpClient.get<Account_Info>(`${this.PHP_API_SERVER}/api/checkaccount.php`, {withCredentials: true});
}
Any advice is welcome. Thank you!
this.apiService.checkAccountStatus().subscribe((accountStatus:any)=>{
console.log("user account", accountStatus);
if(accountStatus = 0)
{
//account doesn't exist
console.log("user doesn't exits.", accountStatus);
}
if(accountStatus = 1)
{
//account does exist
console.log("user does exist.", accountStatus);
}
})
you need to define type of accountStatus like in above code i define accountStatus:any ,use this code and let me know if it work
If Account_Info is an interface, it, indeed, is not a number. You can log it to the console because you can log anything. You cannot check for a type Account_Info to be a number in TypeScript. Also in the if clause, you are assigning, not comparing the values. You have to use the following:
//...
if(+accountStatus == 0) console.log("user doesn't exist", accountStatus)
else if(+accountStatus == 1) console.log("user does exist.", accountStatus);
//...
The reason for prepending a plus before accountStatus is that the Unary operator + in JavaScript attempts to convert the value that follows it to be a number. More info: Unary Plus on MDN
N.B.: This only ever works if the value is indeed a number. Else, +accountStatus will be NaN(not a number).
First, change type of observable.
checkAccountStatus(){
return this.httpClient.get<number>(`${this.PHP_API_SERVER}/api/checkaccount.php`, {withCredentials: true});
}
Then, set the type on subscriber and also, be careful, you are assigning instead of comparing.
this.apiService.checkAccountStatus().subscribe((accountStatus:number)=>{
console.log("user account", accountStatus);
if(accountStatus === 0) // you have (accountStatus = 0)
{
//account doesn't exist
console.log("user doesn't exits.", accountStatus);
}
if(accountStatus === 1) // you have (accountStatus = 1)
{
//account does exist
console.log("user does exist.", accountStatus);
}
})
I've done tons and tons of searches but they're all super complex codes such as, when i say "!Role (role)" then it gives me the role i specified. However, what i am looking for is something much simpler like if i were to say "Hello", then the bot would give me the role that's in the code.
I also tried a lot of the complex ones but most of them used the "addRole" function but the output didn't like it
Do you think you can help me with this?
Discord JS V12:
client.on("message", (message) => {
// Checking if the message equals to "hello".
// Since we use .toLowerCase() which converts any uppercase letter to lowercase, HeLLo will result in hello.
if (message.content.toLowerCase() == "hello") {
// Trying to find the role by ID.
const Role = message.guild.roles.cache.get("RoleID");
// Checking if the role exists.
if (!Role) { // The role doesn't exist.
message.channel.send(`I'm sorry, the role doesn't exist.`);
} else { // The role exists.
// Adding the role to the user.
message.member.roles.add(Role).catch((error) => {console.error(error)});
message.channel.send(`You received the role ${Role.name}.`);
};
}
});
Discord JS V11:
client.on("message", (message) => {
if (message.content.toLowerCase() == "hello") {
const Role = message.guild.roles.get("RoleID");
if (!Role) {
message.channel.send(`I'm sorry, the role doesn't exist.`);
} else {
message.member.addRole(Role).catch((error) => {console.error(error)})
message.channel.send(`You received the role ${Role.name}.`);
};
}
});
Ok, I know that there are similar questions out there but no matter what I try I get the same result. I have been trying for 2 days now to figure out how to check if I had the "OverBot-Admin" role for a ban command. But whenever I run the command it spams the chat! Here is my code:
if (command === "ban") {
if(message.member.roles.has(role => role.name === "OverBot-Admin")) {
let reason = args.slice(1).join(" ");
if (!reason) reason = "No reason provided";
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban({ reason: "They were being bad." })
.then(() => {
message.reply(
":white_check_mark: Successfully banned " +
message.user.id +
"for " +
reason
);
const embed = new Discord.RichEmbed()
.setTitle("Ban")
.addField("Member:", message.user.id)
.addField("Reason:", reason)
.setTimestamp()
.setFooter(
"Created by OverThrow, OverBot SE",
"https://cdn.discordapp.com/avatars/649431468254429224/0b63291c1e7342c2320ca5c3cce806ca.png?size=2048"
);
})
.catch(err => {
message.reply(":x: I was unable to ban that member!");
console.error(err);
});
} else {
message.reply(":x: That user isn't a member to this guild!");
}
} else {
message.reply(":x: You didn't mention a member to ban!");
}
}
} else {
message.reply(":x: I couldn't ban this user, please make sure you have the OverBot-Admin role!")
}
message.member.roles.has() requires a role ID as an argument, whereas here, you are passing in a function. The method I think you are looking for is Collection.exists (although this method is deprecated, if anyone can figure out a different way to go about this, please let me know).
Looking at the message.reply in the then function after banning, I see a message.user.id. However, message.user does not seem to be a valid property of the message object according to the docs. I assume that you would be referring to the user who was just banned, in which case you can reuse the user or member variable you previously defined.
If you have further problems, feel free to comment back.
I made a blog in which a user can only edit it the blogs they created. But now I want to make an admin that can edit and delete any post he wants.
if(foundBlog.author.id.equals(
req.user._id ||
foundBlog.author.username === "ADMIN"
)) {
next();
} else {
res.redirect("back");
}
But my code doesn't work.
equals() is not a valid String function except you have implemented this yourself. If you haven't and want to, you could do something as simple as
String.prototype.equals = function(str){
return this.toString() === str;
}
and then
"hello".equals("hello") // gives true
"hello".equals("kitty") // gives false
However, I would advice against poisoning the prototype of a well-known/built-in object or any shared global space for that matter cause that is a recipe for disaster.
With that said, I'll just go for the strict equality comparison.
if(foundBlog.author.id === req.user._id || foundBlog.author.username === "ADMIN")
No harm no foul.