I'm new to creating bots on discord and can't figure out how I can add a role to multiple users simply by writing a chat message.
I have tried to search various methods on the internet but all I add the role to the author of the message while I need it to add the role to specific users
You can add a command using discord.ext.commands.
#bot.command(pass_context=True)
#bot.has_permissions(manage_roles=True)
async def add_role(ctx, role: discord.Role, *users: discord.Member):
for user in users:
await user.add_roles(role)
You should call it as follows {prefix}add_role #role #user1 #user2
Your setup should look like this
import discord
from discord.ext import commands, tasks
bot = commands.Bot(command_prefix="$")
#code here
bot.run("TOKEN")
Related
I'm trying to make a discord bot which will list all the admins of a server. It currently finds all roles with admin privileges and lists each member in them to the console. however, the bot only prints itself as an admin and doesn't show any of the other roles containing any members. I've got my code below:
async def get_admins(ctx):
admin_roles = [role for role in ctx.guild.roles if role.permissions.administrator]
admins = []
for role in admin_roles:
print(role)
print(role.members)
for member in role.members:
admins.append(member)
return admins
expected output:
Admin
[people, people, more people]
Bot
[itself]
actual output:
Admin
[]
Bot
[<Member id=844113179386707998 name='Orca' discriminator='1134' bot=True nick=None guild=<Guild id=807173965776027648 name='yea test medical bot' shard_id=None chunked=False member_count=5>>]
Any help would be greatly appreciated.
Make sure to enable intents. I hope it works when you enable them. Go to your bot application on discord.dev and enable the intents. If you create a commands.Bot instance, also add this:
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="ยง",intents=intents)
If you enable intents, your bot can get all the members of a server.
I'm trying to read the kick permission of all the roles on my discord server, but when I do so I get this error "'Role' object has no attribute 'kick_members'". https://discordpy.readthedocs.io/en/latest/api.html?highlight=kick_members#discord.Permissions The code is this one:
#client.command()
async def Check_kick_permission(ctx):
for role in ctx.guild.roles:
print(str(role.role.kick_members))
The problem is that you are accessing the role object incorrectly.
You do the following:
print(str(role.role.kick_members))
But the role object does not have a role object in it. Thus the second role is unnecessary and will cause problems.
When you change this to the following:
print(str(role.permissions.kick_members))
It will work. As you are asking what permissions the role has. And then ask if it has the kick_members permission.
For more information read the documentation.
You have to get the permissions from the role via role.permissions documentation
I have a slack application and I have authenticated using this application. When I list all the channels, some of the private channels are not listed. Do we need the access token of workspace admin to list all the private and public channels?
Stumbled across this question when Googling for a similar issue in a large org - I was getting the public channels, but not all of them were showing.
Turns out Slack has a default limit of returning 100 channels. To bypass this, simply pass a limit: 9999 parameter, eg:
app.client.conversations.list({
token: process.env.SLACK_BOT_TOKEN,
limit: 9999
}).then((res: any) => {...})
See also: conversations.list API
Here is how Slack's security architecture works, which explains why you don't get all private channels with conversations.list.
A user only can only see private channel he is a member of. That includes users with admins and owner role, so even the creator of a workspace does not see private channels he is not invited to.
There are two types of tokens:
User token inherit the access rights from the user who installs the
Slack app. So if you installed a Slack app it can only see the
private channels that you are a member of.
Its a bit different with bot token. With a bot token the app can
only see private channel the bot user is a member of.
There are two workarounds to get access to all channels:
Generic user
Ensure a the generic user (e.g. slackadmin) is a member of all private channels. Then using his access token a Slack app also has access to all those private channels. This is an organizational solution.
Collect all user tokens
Collect the tokens of all users on your workspace and then use those tokens to access all conversations incl. private channels their are a member of.
This can be achieved by asking every user to install your Slack app once (via standard OAuth "Add to Slack" process), which is called a configuration in Slack terms.
response = client.conversations_list(types="public_channel, private_channel")
See https://slack.dev/python-slackclient/conversations.html
My Python script retrieves infos about users and groups from a G Suite (testing, for now, with the 14 days free account). I'm using domain-wide delegation and OAuth 2.0 for server to server applications because I don't want to display a pop window where users from hosted domains would allow me to see their groups and users.
These are the steps I followed in order to get users and groups:
create and download all the necessary credentials, such as Client ID;
from my G Suite admin console, allow access to my Client ID and give it the rights to access to users and groups API with the same scopes of my script;
in my script, create the credentials with the .json and make requests on behalf of G Suite admin;
start calling APIs.
Now, the G Suite admin has to allow, in its Security settings, to a certain Client ID some scopes: this I made by hand, manually entering Client ID and scopes. In the OAuth 2.0 for Server to Server Applications tutorial it reads:
If you have delegated domain-wide access to the service account and you want to impersonate a user account, use the with_subject method of an existing service_account.Credentials object.
So: I gave myself access from G suite admin panel to some APIs, my script creates credentials for using that APIs but the .json I downloaded is not enough: it seems that with domain-wide delegation my script still have to make requests on behalf of a user from that hosted domain, in my case the admin of the hosted domain. I tried to create the credentials wihtout impersonating a user, but I did not have enough permissions to do so and the call to APIs returns me 401 or 403.
I thought that a delegated access did not need to act on behalf of a user, since the service account is not associated to any user.
Can I create credentials for a service account without impersonating a user belonging to the hosted domain I'm working with? Are my Client ID and .json file containing my private key and other stuff not enough?
Here's my code:
from google.oauth2 import service_account
import googleapiclient.discovery
import json
""" CONSTANTS AND GLOBAL VARIABLES
"""
# The API we request to use
SCOPES = ['https://www.googleapis.com/auth/admin.directory.group.readonly',
'https://www.googleapis.com/auth/admin.directory.user.readonly']
# json containing keys, account service email, id client and other stuff
SERVICE_ACCOUNT_FILE = 'my_file.json'
# The hosted domain we want to work with
DOMAIN = 'some_hd.it'
# The user I'm using to create credentials
USER_EMAIL = 'name.surname#some_hd.it'
""" SETTING AND GETTING CREDENTIALS
"""
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
if credentials is None:
print "BAD CREDENTIALS"
delegated_credentials = credentials.with_subject(USER_EMAIL)
"""
build('api_name', 'api_version', ...)
https://developers.google.com/api-client-library/python/apis/
"""
service = googleapiclient.discovery.build('admin', 'directory_v1',
credentials=delegated_credentials)
""" GETTING GROUPS AND USERS
"""
request = service.groups().list(domain=DOMAIN)
response = request.execute()
groups = response.get('groups', [])
if not groups:
print "No groups in %s" % (DOMAIN)
print
request = service.users().list(domain=DOMAIN)
response = request.execute()
users = response.get('users', [])
if not users:
print "No users in %s" % (DOMAIN)
else:
for user in users:
for email in user['emails']:
print email['address']
print 'User ID: %s' % (user['id'])
print 'Is admin? %s' % (str(user['isAdmin']))
print
I've been working with Google API for a while and we have the same scenario and no, as far as i know, you'll need to impersonate.
Note that simply allowing the API, download the credential and give scopes permissions to the client ID isnt enough.
For certain services like Directory API, you need to give specifc read and write permissions to the user that you're going to impersonate from the admin gsuite panel to be able to access your groups and users.
I am a self learning computer programming and now I am learning ASP.NET Core. In my first ASP.NET Core application I have created roles and users, then I have added a user to a role using userManager.addtorole. Now I want to replace the role that I added to the user with another role, for example:
I created a user with email user#yahoo.com and a role with name role1
I used usermanager.addtorole(role1)
Everything is good.
I want to enable the administrator of the application to edit the user-role by replacing role 1 with another role.
I have found a method that removes a specified role from the user which was added to the role.
I have tested the method it works very good, after removing the user from the role i could add a new role to the user.
I have found the method by browsing the code intellisense of the userManager object, her is the code:
public void Test(ApplicationUser user1, ApplicationRole role1,
ApplicationRole role2)
{
UserManager<ApplicationUser> _userManager;
await _userManager.AddToRoleAsync(user1, role1.Name);
// Remove user1 from role1.
await _userManager.RemoveFromRoleAsync(user1, role1.Name);
// add user1 to role2.
await _userManager.AddToRoleAsync(user1, role2.Name);
}
Very simple.