How to make an addrole command in discord.py? - python

#bot.command(pass_context=True)
#commands.has_permissions(ban_members = True)
async def addrole(ctx, member : discord.Member, *,role="Members"):
role = discord.utils.get(ctx.guild.roles, name=role)
await member.add_roles(member, role)
await ctx.reply(f'I have added the {role} to {member}')
Last week, i was creating a bot and when i added this command, it gave me an error.
Ignoring exception in command addrole:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 130, in addrole
await member.add_roles(member, role)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 250, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10011): Unknown Role
Can someone tell me why is this error happening?

#bot.command(pass_context=True)
#commands.has_permissions(ban_members = True)
async def addrole(ctx, member : discord.Member, *,role="Members"):
role = discord.utils.get(ctx.guild.roles, name=role)
await member.add_roles(role)
await ctx.reply(f'I have added the {role} to {member}')
guys the error was the member coming before the role, the working piece of code is here

The error that you're experiencing is because the bot cannot find the role. See the MDN documentation for more information on a status 404 error. Common causes of this issue with discord.py are that the bot isn't in the guild with the role, capitalization is wrong, or an assortment of other issues. It is easier to use role IDs to find roles rather than role names for this reason, however, this does not prevent the guild issue. Consult the documentation for more information on Member.add_roles.

Related

Why can't my bot kick users despite having admin perms and both intents enabled?

I made a kick command for my discord bot (hosted on repl.it). I enabled all of the intents and the bot has admin privileges, but still it raises an error
Code:
intents = discord.Intents.all()
bot = Bot("$",help_command=None,intents=intents)
#bot.command()
async def k(ctx,member:discord.Member):
await member.kick()
Error as text:
Ignoring exception in command k:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 91, in k
await member.kick()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 568, in kick
await self.guild.kick(self, reason=reason)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/guild.py", line 1997, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
the error image
I made a totally new bot and made the same kick command
but it still raises an exeption!
Impossible...
...because the Member you tried to kick had an highest role higher than the Bot one.
For example, even if a Bot is an administrator, he can't kick the server owner.
Remember that a discord.Bot object is a way to interact with a discord Bot, which (using the API) can do the same things that a client would manage to do with the same permissions.
Try to kick the same discord.Member that your Bot tried to kick while having the same permissions: you won't be able to do it.
You should check the JSON Error Codes of the Discord API when you don't understand what a Discord.py exception is caused by.
This is because you have not provided a valid reason!
Try this:
#bot.command()
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'User {member} has kicked.')
Hope it works!

Checking if someone has a role to prevent reactions

Making a support ticket like thing. To prevent spamming of the reaction to make loads of tickets, I give them the role "help". If they have this role, the check will not work, and not allow the reaction to do anything. I am getting no errors, but it is not working either - you can still spam.
Btw the role adding works fine
Edit: new code (deletes message and resends new one) - now the second message when reacted to doesnt do anything - long error
def check(reaction, user):
helprole = discord.Object("851168291770597376")
if user != bot.user and helprole not in user.roles:
return str(reaction) == '⛑'
while True:
reaction, user = await bot.wait_for("reaction_add", check=check)
channel = await ctx.guild.create_text_channel("⛑{}s-support-ticket".format(user.name))
await channel.send("**This is your support ticket**\nPlease state your problem below\nA mod will be with you shortly")
modchannel = bot.get_channel(839265539741188157)
await modchannel.send("**NEW SUPPORT TICKET**\n<#&774589745664753665>\n<#{}>".format(channel.id))
supportrole = await ctx.guild.create_role(name="{}'s Ticket".format(user.name))
role = supportrole
helprole = discord.Object("851168291770597376")
await user.add_roles(role)
await user.add_roles(helprole)
await msg.delete()
await supportticket(ctx)
Ignoring exception in command supportticket:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 325, in supportticket
await user.add_roles(role)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 374, in __call__
return await self.callback(*args, **kwargs)
File "main.py", line 308, in supportticket
try:
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/message.py", line 1022, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 250, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
Have you verified that the bot has an administrator? If not, put it, in case it has it, check that if the bot has a role, it is above the other, and also that the role is properly configured.

Discord.py | How to assign someone a role?

I am trying to mute someone using a role Muted
The Code:
#bot.command()
async def mute(ctx, member:commands.MemberConverter):
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.guild.roles)
await member.edit(roles=[role])
But I get this weird error:
Ignoring exception in command mute:
Traceback (most recent call last):
File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\gathi\Vscode\Discord_Bot\tutorial.py", line 61, in mute
await member.edit(roles=[role]) # 848410518154117130
File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\member.py", line 681, in edit
await http.edit_member(guild_id, self.id, reason=reason, **payload)
File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
I don't understand what to do.
Here is the perms of the bot:
The bots perms
The answer is within the bot Forbidden: 403 Forbidden (error code: 50013): Missing Permissions should instantly tell you it's a permissions issue.
The bot fails on await member.edit(roles=[role]) # 848410518154117130 which tells you the code works but it can't assign the role.
Make sure the bot:
Is higher than you in the role hierarchy
Has Manage Roles or the Administrator permission
If this continues to not work then consider going to my previous answer about intents.
You can use discord.Member.add_roles to assign a role.
#bot.command()
async def mute(ctx, member: commands.MemberConverter):
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.guild.roles)
await member.add_roles(role)
And this is the unmute command.
#bot.command()
async def unmute(ctx, member: commands.MemberConverter):
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.guild.roles)
await member.remove_roles(role)

discord.py how to assign roles to users v1.0 version

import discord
import logging
from discord.utils import get
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
#bot.command(pass_context=True)
async def setrole(ctx, a: str):
member = ctx.message.author
role = discord.utils.get(member.guild.roles, name=a)
await member.add_roles(member, role)
This is the code i use trying to assign roles to people entering the command. The role available in my server is rs6 so the code should be !setrole rs6 but its not working.
Ignoring exception in command setrole:
Traceback (most recent call last):
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Workshop\example_bot.py", line 19, in setrole
await member.add_roles(member, role)
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\member.py", line 641, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\http.py", line 223, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Ruiyang(Harry)Wang\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10011): Unknown Role
I tried to do print(role) after line role = discord.utils.get(member.guild.roles, name=a)
and it printed rs6 which is correct. Someone please help me! Thanks!
You can do a snazzy thing using command decorators. In the same way that you've set the type of arg to be a str, you can also set it to be a discord object:
#bot.command() # Note that context is automatically passed in rewrite
async def setrole(ctx, role: discord.Role):
await ctx.author.add_roles(role)
await ctx.send(f"I gave you {role.mention}!")
You might want an error handler to deal with if the role isn't found:
#setrole.error
async def _role_error(ctx, error):
if isinstance(error, commands.errors.BadArgument):
await ctx.send("I couldn't find that role!")
References:
commands.BadArgument
Member.add_roles()
Error handler per command

Kick Command Is Giving Errors

My kick command is below:
#bot.command()
async def kick(ctx, member: discord.Member, *,reason=None):
d = datetime.datetime.now()
channel = bot.get_channel(556058910566514688)
embed=discord.Embed(title='**Kicked By:** {}#
{}'.format(ctx.message.author.name,
ctx.message.author.discriminator), colour=discord.Colour(0x7ed321), description='**Reason:** {} \n **Time:** {}/{}/{}'.format(reason, d.year, d.month, d.day))
embed.set_author(name='{}#{}'.format(member.name, member.discriminator), url="https://discordapp.com", icon_url='{}'.format(member.avatar_url, member.name, member.discriminator))
embed.set_thumbnail(url="{}".format(ctx.message.author.avatar_url))
role = discord.utils.get(ctx.guild.roles, name="Retired Staff")
if ctx.message.author.top_role < role:
await ctx.send('```Only staff Can kick anyone```')
elif reason is None:
await ctx.send('You can\'t kick anyone without a reason')
elif ctx.message.author.top_role > role:
if ctx.message.author.top_role < member.top_role:
await ctx.send('```You can\'t ban a staff member higher than you```')
else:
if ctx.message.author.top_role > member.top_role:
await member.kick()
await channel.send(embed=embed)
Error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\BKhushi\AppData\Local\Programs\Python\Python36-3
2\lib\site-packages\discord\ext\commands\core.py", line 64, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\BKhushi\Desktop\gg\Discordgang.py", line 42, in kick
await member.kick()
File "C:\Users\BKhushi\AppData\Local\Programs\Python\Python36-
32\lib\site-packages\discord\member.py", line 433, in kick
await self.guild.kick(self, reason=reason)
File "C:\Users\BKhushi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\guild.py", line 1268, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "C:\Users\BKhushi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\http.py", line 210, in request
raise Forbidden(r, data)
discord.errors.Forbidden: FORBIDDEN (status code: 403): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\BKhushi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\client.py", line 227, in _run_event
await coro(*args, **kwargs)
File "C:\Users\BKhushi\Desktop\gg\Discordgang.py", line 96, in on_command_error
raise error
File "C:\Users\BKhushi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\bot.py", line 814, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\BKhushi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 682, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\BKhushi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 73, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: FORBIDDEN (status code: 403): Missing Permissions
i don't know wheres the error wheres the error
Your bot does not have the permissions necessary to kick the member in question. Make sure your bot has the KICK_MEMBERS permission and that your bot can interact with the member (your bot's highest role is above their highest role and the member is not the owner of the guild).

Categories