Applying a role if users do not have other roles - javascript

Users are still getting the public role regardless of the role they have
I'm sorry if the answer here is fairly obvious but I'm learning javascript as I write this bot. I'm aiming for users to be able to do !name and gain a role called "public" as long as they don't have a role listed in the code (General, Captain, etc.).
client.on('message', async message => {
if (message.channel.id === '535226845654810624'); {
if(message.content.startsWith('!name')) {
if (message.member.roles.some(role => role.name === 'General', 'Captain', 'Lieutenant', 'Sergeant', 'Corporal', 'Recruit'));
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
}
else {(message.content.startsWith('!name'));} {
if(message.channel.id === '535226845654810624') {
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
I'm sure the code is completely ugly. I'm still learning. Right now regardless of if they have the Gen/Capt/Lieutenant/etc roles they still gain the public role.
client.on('message', async message => {
if(message.channel.id === '535226845654810624') {
if (message.content.startsWith('!name')) {
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
This is the code I had before adding in the attempt to ignore the role add if they have the other roles. I'm not sure how to change this to what I'm looking for.

Take a look at the below code, give it a try and let me know what the result is. There were several errors with your code which I'm quite surprised your editor didn't pick up (or atleast didn't error out the code), such as having a semicolon right after defining an if statement, the extra curly brackets after your else statement, etc.
Anyway, the code below checks if the command entered is !name and if so, it assigns the new nickname to the user. After that it checks if the user has any of the specified roles, and if he does not, he gets a new role 'Public'.
client.on('message', async message => {
if (message.channel.id === '535226845654810624') {
if(message.content.startsWith('!name')) {
// Users are allowed to change their nicknames no matter their roles
const newname = message.content.split(' ').slice(1).join(' ');
message.member.setNickname(newname);
// Define the roles which need to be checked
const roleNames = ['General', 'Captain', 'Lieutenant', 'Sergeant', 'Corporal', 'Recruit'];
// If the user does not have any of the roles above, assign them the role 'Public'
if (!message.member.roles.some(role => roleNames.includes(role.name))) {
const newrole = message.guild.roles.find(x => x.name === 'Public');
message.member.addRole(newrole);
message.delete();
}
}
}
});

Related

Check if the message sender has a specific role

I'm new in Discord bot coding and I want to create a command where the bot only replies if the message sender has a specific role.
According to the discord.js documentation I have to use GuildMemberRoleManager.cache. Sadly, it isn't working.
The whole command looks like this:
client.on('messageCreate', (message) => {
if (
message.content.toLowerCase() === prefix + 'test' &&
GuildMemberRoleManager.cache.has(AdminRole)
)
message.reply('test');
});
You should get the author's roles. Only members have roles, so you will need to get the author as a member using message.member. message.member returns a GuildMember and GuildMembers have a roles property that returns a GuildMemberRoleManager (the one you mentioned in your original post).
Its cache property is a collection of the roles of this member, so you can use its has() method to check if the user has the admin role:
client.on('messageCreate', (message) => {
let adminRole = 'ADMIN_ROLE';
let isAdmin = message.member.roles.cache.has(adminRole);
if (message.content.toLowerCase() === prefix + 'test' && isAdmin)
message.reply('test');
});
Define the variables which will make you easy to understand as you are new
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
and make if statement like
if(member.roles.cache.has(role.id)) {
return message.channel.send("test")
}
if you want bot to check if user have administrator perm than
message.member.hasPermission('ADMINISTRATOR')
Check all perm flags on Discord Perm Flags
So according to your code it will be
const guild = message.guild.id;
const role = guild.roles.cache.get("role id");
const cmduser = message.author;
const member = await guild.members.fetch(cmduser.id);
client.on("messageCreate",(message) => {
if(message.content.toLowerCase() === prefix + "test" && member.roles.cache.has(role.id))
message.reply("test")
})

How do I use Repl.it's database?

I need my bot to save user violations to a database when a user uses a command. For example, when #violate #user red light pass is used, the bot should save the red light pass to the database for the mentioned user. I'm using Repl.it's database and this is my code:
client.on("message", async message => {
if (message.content.toLowerCase().startsWith("#violations")) {
let violation = await db.get(`wallet_${message.author.id}`)
if (violation === null) violation = "you dont have any tickets"
let pembed = new Discord.MessageEmbed()
.setTitle(`${message.author.username} violations`)
.setDescription(`المخالفات المرورية : ${violation}`)
.setColor("RANDOM")
.setFooter("L.S.P.D")
message.channel.send(pembed)
}
if (message.channel.id === '844933512514633768') {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
console.log(args);
const command = args.shift().toLowerCase();
if (command == 'red light pass') {
const member = message.mentions.members.first(); //
let light = "red lightpass"
await db.set(`wallet_${memeber}`, light)
}
}
})
First of all, in `wallet_${memeber}`, memeber is not defined. You probably intended to use `wallet_${member}`.
I believe the issue is you're using the key `wallet_${message.author.id}` (e.g. 'wallet_12345') to get the violation/ticket, but then `wallet_${member}` (e.g. 'wallet_<#12345>') (e.g. 'wallet) to set the violation. Interpolating a GuildMember in a string calls its toString method, which creates a string of the mention of the member, not the id.
Also, it's good practice to use === instead of == as == casts the items being compared so things like 3 == '03' and [] == false are true.
The final code should like this:
if (command === "red light pass") {
const member = message.mentions.members.first();
const light = "red lightpass";
// Note how I've changed this to member.id (which is just a shortcut for
// member.user.id) from memeber
await db.set(`wallet_${member.id}`, light);
}

Why does role.permissions.remove() not work?

I tried to make a command to remove the MENTION_EVERYONE permission from all roles. It didn't work for some reason. I tried console logging which roles have the permission, and it did, but the only thing is that the permission isn't being taken away. I get no error but here is my code.
client.on('message', msg => {
if(msg.content === 'checkroleperms' && msg.author.id === 'xxxxxxxxxx') {
var roles = msg.guild.roles.cache.array()
var all = '{Placeholder}'
roles.forEach(role => {
if(role.permissions.has('MENTION_EVERYONE')) {
all+= ', ' + role.name;
//RIGHT HERE IS THE WHERE THE PROBLEM IS!!
//Changed this to msg.guild.role.cache.get(role.id).permissions.re...
role.permissions.remove('MENTION_EVERYONE');
console.log(role.name);
}
})
setTimeout(() => msg.channel.send(all), 500);
}
})
Was there something I did wrong? Also, the bot has Admin perms and is the second highest role in the server (right under me). The point is that the command is running but the perms are not being removed.
EDIT: I realized I was only modifying the array, but nothing is happening even when I get it from msg.guild.roles.cache
You were pretty close, the problem is you remove the permission but you never update the role itself.
role.permissions.remove() removes bits from these permissions and returns these bits or a new BitField if the instance is frozen. It doesn't remove or update the role's permissions though.
To apply these changes, you need to use the setPermissions() method that accepts a PermissionResolvable, like the bitfield returned from the permissions.remove() method.
It's probably also better to use roles.fetch() to make sure roles are cached.
Check the working code below:
client.on('message', async (msg) => {
if (msg.content === 'checkroleperms' && msg.author.id === 'xxxxxxxxxx') {
try {
const flag = 'MENTION_EVERYONE';
const roles = await msg.guild.roles.fetch();
const updatedRoles = [];
roles.cache.each(async (role) => {
if (role.permissions.has(flag)) {
const updatedPermissions = role.permissions.remove(flag);
await role.setPermissions(updatedPermissions.bitfield);
updatedRoles.push(role.name);
}
});
const roleList = updatedRoles.join(', ') || `No role found with \`${flag}\` flag`;
setTimeout(() => msg.channel.send(roleList), 500);
} catch (error) {
console.log(error);
}
}
});

Discord.js bot was working, added one extra command and everything broke. Can anyone help me figure out why?

Tried to venture in to the realm of making discord bots. Followed along with a fairly simple tutorial, tweaking it along the way to fit what I was trying to make. The bot originally worked, but I went back in to add the "Mistake" command, and suddenly it's not working. I added in console.log pretty much everywhere, trying to figure out how far everything was getting.
When I start the bot, it will spit out the "Bot Online" log. When I input a command, it will spit out the "Commands" log, but it won't register the command at all. I've tried looking for any minor typos, missing brackets, etc... but I just can't seem to figure out what's gone wrong. I'm hoping that someone here can help! Thank you!
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.on('ready', () => {
console.log('Bot Online');
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'goals';").get();
if (!table['count(*)']) {
sql.prepare('CREATE TABLE goals (id TEXT PRIMARY KEY, user TEXT, guild TEXT, goals INTEGER);').run();
sql.prepare('CREATE UNIQUE INDEX idx_goals_id ON goals (id);').run();
sql.pragma('synchronous = 1');
sql.pragma('journal_mode = wal');
}
//Statements to get and set the goal data
client.getGoals = sql.prepare('SELECT * FROM goals WHERE user = ? AND guild = ?');
client.setGoals = sql.prepare('INSERT OR REPLACE INTO goals (id, user, guild, goals) VALUES (#id, #user, #guild, #goals);');
});
client.on('message', (message) => {
if (message.author.bot) return;
let goalTotal;
if (message.guild) {
goalTotal = client.getGoals.get(message.author.id, message.guild.id);
if (!goalTotal) {
goalTotal = {
id: `${message.guild.id}-${message.author.id}`,
user: message.author.id,
guild: message.guild.id,
goals: 0,
};
}
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
console.log('Commands');
if (command === 'Goals') {
console.log('Goals');
return message.reply(`You Currently Have ${goalTotal.goals} Own Goals.`);
}
if (command === 'OwnGoal') {
console.log('Own Goal');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
userscore = {
id: `${message.guild.id}-${user.id}`,
user: user.id,
guild: message.guild.id,
goals: 0,
};
}
userscore.goals++;
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} has betrayed his team and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Mistake') {
console.log('Mistake');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
return message.reply('This person has no Rocket Bot activity.');
}
if (userscore === 0) {
return message.reply('This player currently has no goals.');
}
if (userscore > 0) {
userscore.goals--;
}
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} was falsely accused and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Leaderboard') {
console.log('Leaderboard');
const leaderboard = sql.prepare('SELECT * FROM goals WHERE guild = ? ORDER BY goals DESC;').all(message.guild.id);
const embed = new Discord.MessageEmbed()
.setTitle('Rocket Bot Leaderboard')
.setAuthor(client.user.username, client.user.avatarURL())
.setDescription('Total Goals Scored Against Own Team:')
.setFooter('Rocket Bot')
.setThumbnail('https://imgur.com/a/S9HN4bT')
.setColor('0099ff');
for (const data of leaderboard) {
embed.addFields({
name: client.users.cache.get(data.user).tag,
value: `${data.goals} goals`,
inline: true,
});
}
return message.channel.send({ embed });
}
if (command === 'RocketHelp') {
console.log('Help');
return message.reply(
'Rocket Bot Commands:' +
'\n' +
'!Goals - See How Many Goals You Have Scored Against Your Own Team' +
'\n' +
'!OwnGoal - Tag Another Player With # To Add One To Their Total' +
'\n' +
'!Mistake - Tag Another Player With # To Subtract One From Their Total' +
'\n' +
'!Leaderboard - Show The Current Leaderboard'
);
}
});
client.login(config.token);
You are improperly splitting the message content. You added g to the regex by accident.
Correct line:
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
Because of improper args split, it could not find any command at all, hence no console log was invoked after Commands.

Role is not getting added to member [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have some code that detects when someone enters the command role and gives them the role with the name of the first argument passed to the command (args[0]). For example, the bot would try to detect something like !role nameOfTheRole, which would give the user the role with the name nameOfTheRole.
However, the code is not working and I'm not sure why. Here is what I have mnaged to get so far:
var cmdmap = {
role: gimmerole
}
function gimmerole(member, args, message) {
var memb = message.member() //<------- ERROR
const role = memb.guild.roles.find(r => r.name == args[0])
memb.roles.add(role)
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild
if (author.id != client.user.id && cont.startsWith(config.prefix)) {
var invoke = cont.split(' ')[0].substr(config.prefix.length),
args = cont.split(' ').slice(1)
console.log(invoke, args)
if (invoke in cmdmap) {
cmdmap[invoke](msg, args)
}
}
})
I have made a few modifications to your code:
I changed the line function gimmerole(member, args, message) { to function gimmerole(message, args) {, as in the line cmdmap[invoke](msg, args);, you are calling it with the message object and the arguments, so the message was getting assigned to member instead and message would have been undefined.
I changed message.member() to message.member, as member is a property of message, not a method.
I also changed the code that parses the message and splits it into a command and arguments so that it's a lot cleaner.
Added a sanity check (if (!role) return console.log(`The role "${args[0]}" does not exist`);) to make the bot log to the console if the role does not exist.
Changed args[0] to args.join(' ') to enable roles with spaces to be specified.
var cmdmap = {
role: gimmerole
};
function gimmerole(message, args) {
const member = message.member;
const role = message.guild.roles.cache.find(r => r.name === args.join(' '));
if (!role) return console.log(`The role "${args.join(' ')}" does not exist`);
member.roles.add(role);
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild;
if (author.id !== client.user.id && cont.startsWith(config.prefix)) {
const [invoke, ...args] = cont.slice(config.prefix.length).trim().split(' ');
console.log(invoke, args);
if (invoke in cmdmap) {
cmdmap[invoke](msg, args);
}
}
})
There is the Discord.js Guide that you can use if you want something to follow along with. It is really helpful and detailed.
I have noticed you're improperly trying to find a role. In order to get a full roles collection, you will need to use the cache method of message.guild.roles, resulting in the line:
const roleObject = memb.guild.roles.cache.find(...);
var cmdmap = {
role: gimmerole
};
function gimmerole(message, args) {
const member = message.member;
const role = message.guild.roles.cache.find(r => r.name === args.join(' '));
if (!role) return console.log(`The role "${args.join(' ')}" does not exist`);
member.roles.add(role);
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild;
if (author.id !== client.user.id && cont.startsWith(config.prefix)) {
const [invoke, ...args] = cont.slice(config.prefix.length).trim().split(' ');
console.log(invoke, args);
if (invoke in cmdmap) {
cmdmap[invoke](msg, args);
}
}
}
Credits to Deamon Beast

Categories