Check if a user is an admin in a setup function - discord.js

I would like to make a setup function to put my bot up, but it has to be usable ONLY by admins.
if (message.content.startsWith("!setup")) {
if (message.auther.admin) {
//my code
}
}

If you want to check if that user has the 'Administrator' permission just use this:
if(!message.member.hasPermission('ADMINISTRATOR')) return message.reply('No Perms!');

Assuming your admin role is named "Admin", the following code should do what you're wanting:
const adminRole = message.guild.roles.find(role => role.name == "Admin");
if (message.member.roles.has(adminRole.id)) {
if (message.content.startsWith("!setup")) {
//setup command code
}
} else {
message.reply("Sorry, you don't have permission to use this command!").catch(console.error);
}
You'll want the if statement for the admin check to be first, that way you can define all of your administrative commands within it. Otherwise, if you have more than one admin-only command you would have to have the admin check multiple times.

Related

How can I make a clear command only for moderators (discord bot)

my clear command works on the server, but everyone can use it, how can i make it only for moderators? Here is my code:
case 'clear':
if(!args[1]) return message.reply('Error please define how many messages you wanna delete, ***Ex: !clear 10*** ')
message.member.hasPermission("MANAGE_CHANNELS");
message.channel.bulkDelete(args[1]);
break;
Thanks for reading and have a good day!
You need to check if member has a permission. All you need to do is create an IF Statement.
case 'clear':
if(!args[1]) return message.reply('Error please define how many messages you wanna delete, ***Ex: !clear 10*** ')
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.reply(`You can't use this command.`);
message.channel.bulkDelete(args[1]);
break;
You can check more about permissions here and here. Also I highly suggest you to create a command handler.
There are 2 main ways I would do this, restrict it to a role or restrict it to a permission.
If the user has a role
The good things about this are that you don't need to assign permissions, however if you have multiple roles you will need to check multiple times with &&
Here is one way:
if (message.member.roles.cache.some(role => role.name === 'admin')) {
// success code
}
However i would do this:
if (!message.member.roles.cache.some(role => role.name === 'admin')) {
// They don't have permission
return
}
Because it is easier to add multiple roles
if (!message.member.roles.cache.some(role => role.name === 'admin') && !message.member.roles.cache.some(role => role.name === 'moderator')) {
// They don't have permission
return
}
permission
The advantages of this are that it's much simpler, their role doesn't matter.
Here is the most simple way
if (!message.member.hasPermission("MANAGE_MESSAGES")) {
// They don't have permission
return
}
and like before you can have multiple permissions
if (!message.member.hasPermission("MANAGE_MESSAGES") && !message.member.hasPermission("KICK_MEMBERS")) {
// They don't have permission
return
}

Trying to implement Patreon-only commands/functions on my discord bot, how would I accomplish this?

My discord bot gives the role of 'Patreon' to my patreon supporters. This role is given on my main discord bot server. So right now I'm trying to write some commands that would be only available to users who have the role 'Patreon' in the BOTS discord server, how can I accomplish this?
Like is there a way I can be like -
message.member.has('Patreon Role').in('My Discord Server)?
Let's go over the tasks you need to accomplish this.
Get the "home guild" with your users and corresponding Patreon role.
See Client.guilds and Map.get().
Find the user in the guild.
See Guild.member().
Check whether or not the user has the Patreon role.
See GuildMember.roles and Collection.find().
You can define a function to help you out with this, export it and require it where you need it (or define it within relevant scope), and then call it to check if a user is one of your Patreon supporters.
Here's what this function would look like...
// Assuming 'client' is the instance of your Discord Client.
function isSupporter(user) {
const homeGuild = client.guilds.get('idHere');
if (!homeGuild) return console.error('Couldn\'t find the bots guild!');
const member = homeGuild.member(user);
if (!member) return false;
const role = member.roles.find(role => role.name === 'Patreon');
if (!role) return false;
return true;
}
Then, as an example, using this function in a command...
// Assuming 'message' is a Message.
if (!isSupporter(message.author)) {
return message.channel.send(':x: This command is restricted to Patreon supporters.')
.catch(console.error);
}
message.member.roles.find('name', 'Patreon Role');//this returns either undefined or a role
What that does is it searches the users collection to see if the have "Patreon Role"
If the message is on the same server, otherwise you could do
client.guild.find('name','My Discord Server').member(message.author).roles.find('name', 'Patreon Role'); //this also returns undefined or a role
Clearly that second option is long, but what is basically does is searches the servers the bot is in for a server called 'My Discord Server' then it finds the GuildMember form of the message.author user resolvable, then it searches their roles for the role 'Patreon Role'
There is a chance it will crash though if they aren't on the server(the documentation doesn't say if it returns and error or undefined for some reason) so if it does crash you could instead do
client.guild.find('name','My Discord Server').members.find('id', message.author.id).roles.find('name', 'Patreon Role'); //this also returns undefined or a role
You can read more here: https://discord.js.org/#/docs/main/stable/class/User
and here
https://discord.js.org/#/docs/main/stable/class/Client
and here
https://discord.js.org/#/docs/main/stable/class/Guild
To try and give a full example, assuming this is in your message event
if (message.member.roles.find(r => r.name === 'Patreon') == undefined &&
commandIsExclusive || message.guild.id !== 'this-id-for-BOTS-server') {
// Don't allow them in here
}
Essentially, to run a command they must be a supporter, in a specific server and if it is exclusive and the other criteria aren't met, they are denied

How to let an admin change user properties in Meteor?

Are there any special hoops one has to jump through when modifying user objects in Meteor? I have no problem changing other collections but the users are strangely and persistently resistant to the many suggestions I have found.
I can see that there are some user attributes such as profile that are published and presumably quite easy to change. I need more control over the access so just bunging my data into user.profile won't do. At the moment I'm trying to give users a grant table, so that for example I can write:
var user = Meteor.users.findOne();
var may_eat_popcorn = user.grants.popcorn;
This works:
$ meteor shell
// First check that the user is not allowed to eat popcorn:
> Meteor.users.findOne({_id:"iCTnpqwCR6jj9xxxx"});
....
grants: { popcorn: false } }
// Give the non-gender specific entity access to popcorn:
> Meteor.users.update({_id:"iCTnpqwCR6jj9xxxx"},{$set:{"grants.popcorn":true}}, function(err,res){console.log("grant:",err,res);});
> Meteor.users.findOne({_id:"iCTnpqwCR6jj9xxxx"});
....
grants: { popcorn: true } }
// Hooray.
This doesn't, even though equivalent code works fine with other collections:
Meteor.methods(
{ User_grant_popcorn: function(userId, granted){
// authentication. Then:
var grants = {"grants.popcorn": granted};
console.log(userId,grants);
Meteor.users.update({_id:userId},{$set:grants}, function(err,res){console.log("grant:",err,res);});
// This callback prints that there is no error, yet the database doesn't change on the server.
}
});
// On the client the admin picks the target user and sets their degree of pop:
Meteor.call('User_grant_popcorn', user._id, false);
Do you know how user is different? More importantly, how can I debug issues like this? Winning means getting awesome things done fast. That's meteor's promise. If debugging takes this long the advantage is lost.
Many thanks, Max
Programmatically create $set
Meteor.methods({
User_grant_popcorn: function(userId, granted) {
// authentication. Then:
var grants = {
"grants.popcorn": granted
};
var setHash = {
$set: grants
};
console.log(userId, grants);
Meteor.users.update({_id: userId}, setHash, function(err, res) {
console.log("grant:", err, res);
});
// This callback prints that there is no error, yet the database doesn't change on the server.
}
});

yii2 rbac check for role user->can()

i installed and configured rbac in yii2 with DBManager but i don't get the "check" working with:
if (Yii::$app->user->can('waitAccess')) {
echo "yes it is pending.";
} else {
echo "nothing";
}
I made 3 users with my different roles but each of them is able to see the first line despite they don't have the permission. "In my opinion"
This here is my rbacController
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
class RbacController extends Controller
{
public function actionInit()
{
$auth = Yii::$app->authManager;
// add "user2View" permission
$user2View = $auth->createPermission('user2View');
$user2View->description = 'user2 view';
$auth->add($user2View);
// add "user1View" permission
$user1View = $auth->createPermission('user1View');
$user1View->description = 'user1 view';
$auth->add($user1View);
// add "waitAccess" permission
$waitAccess = $auth->createPermission('waitAccess');
$waitAccess->description = 'wait for Access';
$auth->add($waitAccess);
// add "seeConfig" permission
$seeConfig = $auth->createPermission('seeConfig');
$seeConfig->description = 'Access to the administrative Config';
$auth->add($seeConfig);
// add "user2" role and give this role the "user2View" permission
$user2 = $auth->createRole('user2');
$auth->add($user2);
$auth->addChild($user2, $user2View);
// add "user1" role and give this role the "user1View" permission
$user1 = $auth->createRole('user1');
$auth->add($user1);
$auth->addChild($user1, $user1View);
// add "pending" role and give this role the "waitAccess" permission
$pending = $auth->createRole('pending');
$auth->add($pending);
$auth->addChild($pending, $waitAccess);
// add "superadmin" role and give this role the "seeConfig" permission
$superadmin = $auth->createRole('superadmin');
$auth->add($superadmin);
$auth->addChild($superadmin, $seeConfig);
$auth->addChild($superadmin, $user2View);
$auth->addChild($superadmin, $user1View);
$auth->addChild($superadmin, $waitAccess);
}
}
Maybe anyone have a clue what I can look for.
Update: This is my DB Structure
Update 2:
I solved it!
The stupidity didn't took a look on the default rules where all users where written down. So everyone had access. Deleting that line and adding pending for standard it resolved it.

Drupal 7:User information not saving when edited by allowed users

I'm currently developping a new website for an artists organization. The administrator role is allowed to create accounts and some other node content, the created accounts have the same default role called "artisan". Administrators are Artisans as well. Artisans can create and edit their own content. Both administrators and artisans should be able to edit user profile (all for admin, only their own for artisan). The fact is admin can create a user but nobody (except user1) can save user profile after edit (but it works great for other nodes). Permissions have been scanned multiple times. I have been searching everywhere with no success, what am I missing ? I made very few changes, the only related code I wrote is the following :
<?php
function canardesign_system_form_alter(&$form, &$form_state, $form_id){
global $user;
switch ($form_id){
case 'oeuvre_node_form':
$form['actions']['submit']['#submit'][] = 'canardesign_system_oeuvre_redirect';
if (in_array('artisan', array_values($user->roles))){
$form['field_auteur']['#type']= 'hidden';
$form['field_auteur']['und']['#default_value']= $user->uid;
}
break;
case 'user_profile_form':
if (in_array('artisan', array_values($user->roles))){
$form['actions']['submit']['#submit'][] = 'canardesign_system_user_profile_form_submit';
}
break;
}
}
function canardesign_system_oeuvre_redirect($form, &$form_state) {
$type=$form['#node']->type;
if(isset($type))
{
$node = node_load($form_state['nid']);
$uid=field_get_items('node', $node, 'field_auteur')[0]['target_id'];
$form_state['redirect'] = 'oeuvres/'.$uid;
}
}
function canardesign_system_user_profile_form_submit($form, &$form_state) {
drupal_goto('artisans');
}
/*default role when administrator (who is artisan as well) creates an account*/
function canardesign_system_user_insert(&$edit, $account, $category) {
global $user;
if (in_array('artisan', array_values($user->roles))){
$account->role = 'artisan';
}
}
?>
Thank you for your help.
I'm not sure if this is the cause of your issue, but calling drupal_goto() inside a submit hook is definitely problematic. It essentially shorts out the handling of the form.
This may be causing the issue by preventing other necessary code from executing.
You should instead set the redirect key of $form_state to the destination you would like the user to end up on.
Once the form handling is complete, Drupal will send the user there.
function canardesign_system_user_profile_form_submit($form, &$form_state) {
$form_state['redirect'] = 'artisans';
}

Resources