Command that allows you to make a role - discord

I wanted to make a command that allows you to make a role, along with the permissions, colors, and whether it's hoisted or not.
I've put the command inside a cog.
#commands.command(aliases=['make_role'])
#commands.has_permissions(manage_roles=True)
async def createrole(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name)
await ctx.send(f'Role `{name}` has been created')
What else do I need to change so that I can add permissions, colors and hoist status upon making the role?

You can apply these parameters to the create_role method that you ran in your code. Here's an example that fills these parameters:
import discord
from discord.ext import commands
#commands.command(aliases=['make_role'])
#commands.has_permissions(manage_roles=True)
async def create_role(self, ctx, *, name):
guild = ctx.guild
await guild.create_role(name=name,
permissions=discord.Permissions.membership(),
color=discord.Color.default(),
hoist=True)
await ctx.send(f'Role `{name}` has been created')
With that example, you can change the initializing values of Permissions and Color.

Related

How to restrict a certain role from using a command (discord.py)

I've already seen the variant where you allow a certain role to use a command.
However, I'm trying to achieve the exact opposite: How to disallow a certain role from using a command.
I have searched around stack overflow and found no answer, nor did I found an answer on the official discord.py documentation.
Any sort of help is appreciated.
author.roles returns a list of discord.Role so just check if the role you specify is contained in that list, and if so, exit the command early.
Using Role Id (Preferred)
#bot.command()
async def command_without_specific_role(ctx):
if role_id in [role.id for role in ctx.author.roles]:
return
...
Using Role Name
#bot.command()
async def command_without_specific_role(ctx):
if role_name in [role.name for role in ctx.author.roles]:
return
...
Check inside command
#bot.command()
async def hello(ctx: commands.Context):
blacklisted_role = ctx.guild.get_role(ID)
if not any(role == blacklisted_role for role in ctx.author.roles):
await ctx.send("world!")
Own Decorator
A more elegant way is to create your own decorator. It's more like the opposite of has_any_role.
from discord.ext import commands
def has_not_any_role(*roles):
async def extended_check(ctx):
return not any(role.id in roles for role in ctx.author.roles)
return commands.check(extended_check)
#bot.command()
#has_not_any_role(492212595072434186)
async def hello(ctx: commands.Context):
await ctx.send("world!")
If extended_check returns True the message will be sent. If it return False it throws a discord.ext.commands.errors.CheckFailure error which then can be catched in on_command_error.
References:
Member.roles
commands.check

Asking for Kick Member permission despite having given admin rights to Bot

So I am setting up a bot, and I am testing it out. A little function I have there is to kick, ban and unban users, set up in a cog, which goes as follows:
import discord
from discord.ext import commands
class Moderator(commands.Cog):
def __init__(self, bot):
self.bot = bot
#KICK command
#commands.command()
#commands.has_permissions(kick_members=True)
async def kick(self, ctx, member : discord.Member, *, reason=None):
('About to kick')
await member.kick(reason = reason)
#commands.command()
#commands.has_permissions(kick_members=False)
async def kick(self, ctx, member : discord.Member, *, reason=None):
await ctx.send(f'You do not have permission to kick any member, {ctx.message.author.mention}!')
#BAN command
#commands.command()
#commands.has_permissions(ban_members=True)
async def ban(self, ctx, member : discord.Member, *, reason=None):
await member.ban(reason = reason)
await ctx.send(f'Banned {member.mention}')
#commands.command()
#commands.has_permissions(kick_members=False)
async def ban(self, ctx, member : discord.Member, *, reason=None):
await ctx.send(f'You do not have permission to ban any member, {ctx.message.author.mention}!')
#UNBAN command
#commands.command()
#commands.has_permissions(ban_members=True)
async def unban(self, ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return
#commands.command()
#commands.has_permissions(kick_members=False)
async def unban(self, ctx, member : discord.Member, *, reason=None):
await ctx.send(f'You do not have permission to unban any member, {ctx.message.author.mention}!')
#CLEAR MESSAGES
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount=2):
await ctx.channel.purge(limit=amount)
#commands.command()
#commands.has_permissions(manage_messages=False)
async def clear(self, ctx, amount=2):
await ctx.send(f'You do not have permission to delete messages in this way, {ctx.message.author.mention}!')
def setup(bot):
bot.add_cog(Moderator(bot))
Now I have formatted the above code with some spaces so that it fits in one codeblock, so you might face indentation errors if you copy paste it elsewhere.
Moving on, the bot itself has Administrator rights and separate Kicking and Banning rights too. It is also placed at the top of the role hierarchy, which is seen as:
The name of my bot is JunkBot.
Now, whenever I, being the server owner, try using the command .kick #user, it pops up the following error:
The textual form of the error is:
Ignoring exception in command kick:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 777, in prepare
if not await self.can_run(ctx):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1087, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\utils.py", line 348, in async_all
for elem in gen:
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1087, in <genexpr>
return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1790, in predicate
raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Kick Members permission(s) to run this command.
Similar errors are raised for the ban, unban and clear messages commands.
Interesting part is, I, being the owner, get this error, but supposing another user, a friend of mine who does not have the kicking, banning or message managing role, runs their lines of codes perfectly, where she gets the message from the bot that she does not have permission to kick, ban or clear messages. The screenshot is enclosed.
I don't know where I went wrong. Please help me debug it.
Your problem is in rewriting the functions. I'm assuming that you are hoping to make an errorhandler. However, this isn't the way to do so.
Instead of rewriting the functions with different has_permissions arguments, you will need to make a proper version of an error handler.
First, delete all the duplicate functions. These are the functions that require False on the has_permissions arguments.
Next, make a errorhandler function. You can make one for the Cog commands only, for all commands, or a specific command. If its for all commands, you will use the event on_command_error, (I suggest using it in the main file or as a listener). If it's for the Cog, then you will have to use cog_command_error. If it's for a specific command, you should make the Command.error decorator.
I will be showing the Cog specific handler, but switching back and forth shouldn't take too long.
# Indent into Cog level
async def cog_command_error(self, ctx, error):
# Allows us to check for original exceptions raised and sent to CommandInvokeError.
# If nothing is found. We keep the exception passed to on_command_error.
error = getattr(error, 'original', error)
if isinstance(error, commands.BotMissingPermissions): # Check if bot is missing permissions
await ctx.send(f'I am missing these permissions to do this command:\n{self.lts(error.missing_perms)}')
elif isinstance(error, commands.MissingPermissions): # Check if user is missing permissions
await ctx.send(f'You are missing these permissions to do this command:\n{self.lts(error.missing_perms)}')
#staticmethod
def lts(list_: list): # Used to make reading the list of permissions easier.
"""List to string.
For use in `self.on_command_error`"""
return ', '.join([obj.name if isinstance(obj, discord.Role) else str(obj).replace('_', ' ') for obj in list_])
Here is the list of exceptions you can use in the handler: Exceptions
FYI, the lts function I have isn't required for the handler. It's used to make the list of permissions readable in one string. You can always remove it or change it to your needs.
That is not how error handling works. You should check out the error handling section of the docs for how to deal with missing permissions.
EDIT because people reminded me to give some more information
You shouldn't be handling errors through has_permissions. From what I can tell from your code, you are looking to send a message when the invoker doesn't have the permissions required to use the command. This can be achieved with an error handler. THe error handler will catch the MissingPermissions exception and do something based on that. Here is an example:
#commands.Cog.listener()
async def on_command_error(self, ctx, error): #this is the event that catches errors
if isinstance(error, commands.MissingPermissions): #seeing if the error is the missing permissions error
await ctx.send(f"You do not have the permission to do this, {ctx.author.mention}!")
This uses a global error handler, meaning that whenever an error is caught, this will catch it. However if you want an error handler for each command, all you have to change is the decorater and function name. EX:
#kick.error
async def on_kick_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"You do not have the permission to kick any member, {ctx.author.mention} ")
This one will only trigger on the kick command error, none of the others.

How can I allow people to only kick members lower than their role with discord.py?

I'm trying to make a kick command using Python and the discord.py library, though I cannot figure out how to allow people to only be able to kick members lower than their role, so Moderators wouldn't be able to kick Admins.
enter image description here
You can compare the Member object with a function called top_role
An example code would be:
#client.command()
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if member.top_role >= ctx.author.top_role: # Check if the role is below the authors role
await ctx.send("You can only kick users with a lower role!")
return
else:
await member.kick(reason=reason)
await ctx.send(f"{member.id} got kicked with the reason: {reason}.")
Add all the moderators to a list and regular users to another list.
Like this;
string[] moderator = all moderators.
string[] regularUsers = all regular users.

guild.get_member_named(name) is returning 'NoneType' inspite of existence of such member

I have enabled intents all through my code and developer portal;got necessary permissions for the bot to 'see' the other members but still the method returns NoneType for almost all users(only exception is Dyno)
Now I need a complete check through my program and the permissions and settings
if it doesn't get sorted after the check then the question topic gets adjusted accordingly
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!',intents=intents)
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
#bot.command()
async def ping(ctx,args1):
guild = bot.get_guild(ServerID)
member = guild.get_member_named(args1) #getting NoneType here
await ctx.send('member.mention') #Assuming the existence of member coz I know there is such one
bot.run(os.getenv('TOKEN'))
Try using
discord.utils.get(guild.members, name='theusernamehere') #replace"theusernamehere" with the person username
To get by id use this
discord.utils.get(guild.members, id='idhere') #replace "idhere" with the person id
or you can just use arg1: discord.Member

How to get member object from Id discord.py

I have a user's id however I want to be able to convert this into a member object.
my bot has a leader board and stores uses the users discord id as a key. I want to be able to use these id's to get a member object. I want to be able to access this even if that user is not in the server.
Is this possible, if so how can I do it
You can do this in one line of code:
member_obj = ctx.guild.get_member(user_id)
So for example, this is how you could use it in a function:
import discord
from discord.ext import commands
#client.command()
async def id_to_name(ctx, *, id):
member_obj = ctx.guild.get_member(user_id)
await ctx.send(f'ID to name: {member_obj.display_name}')
You could do either of two things.
If you want to use ctx:
ctx.author.mention
#If you want to use the member thing.
#Bot.command()
async def example(ctx, member : discord.Member):
await ctx.send(f"name{member.mention or ctx.authour.mention}

Resources