Checking if someone has a role to prevent reactions - python

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.

Related

How to make an addrole command in discord.py?

#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.

Music bot returning errors at core.py and bot.py

The code for the music bot I'm trying to write in python keeps returning an error with the following code:
#bot.command(name='play_song', help='To play song')
async def play(ctx,url):
#if not ctx.message.author.name=="Rohan Krishna" :
# await ctx.send('NOT AUTHORISED!')
# return
if 1==1:#try :
server = ctx.message.guild
voice_channel = server.voice_client
print("try 1 was a success")
async with ctx.typing():
filename = await YTDLSource.from_url(url, loop=bot.loop)
#voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename)) #ISSUE HERE
print("try 2 was a success")
voice = get(ctx.bot.voice_clients, guild=ctx.guild)
#voice.play(discord.FFmpegPCMAudio('test.mp3'), after=your_check)
#voice.source = discord.PCMVolumeTransformer(voice.source)
#voice.source.volume = 0.5
await ctx.send('**Now playing:** {}'.format(filename))
if 1==0:#except:
await ctx.send("The bot is not connected to a voice channel.")
print("try 3 was unfortunately a success")
It normally has a try/except function but I replaced it with if true and false statements to force it to run instead of breaking to determine the exact line of it breaking. The issue supposedly lies in
voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename)) #ISSUE HERE
The error I get returned is:
Traceback (most recent call last):
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "app2.py", line 75, in play
voice.play(discord.FFmpegPCMAudio('test.mp3'), after=your_check)
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\player.py", line 225, in __init__
super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\player.py", line 138, in __init__
self._process = self._spawn_process(args, **kwargs)
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\player.py", line 147, in _spawn_process
raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\heyin\anaconda3\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: ClientException: ffmpeg was not found.
I added the print statements to determine which lines were working so those can obviously be ignored. It seems to be working fine except for this, other commands in the bot are working appropriately.

Make the bot discord send a message when someone type "!clear" has no permission

#client.command(pass_context=True)
#commands.has_permissions(administrator=True)
async def clear(ctx,amount=1000):
await ctx.channel.purge(limit=amount)
#clear.error
async def clear_error(ctx,error):
if isinstance(error, MissingPermissions):
text = "Sorry {}, you do not have permissions to do that!".format(ctx.message.author)
await client.send_message(ctx.message.channel, text)
output: ( I want it to send a message to that user, who have no permission administration, and delete his message I dont understand this error, it happeen when I try to send please fix it ty would you fix it for me guys thank you im new here. )
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\cyberx\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\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 777, in prepare
if not await self.can_run(ctx):
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\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\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\utils.py", line 348, in async_all
for elem in gen:
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\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\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1790, in predicate
raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Administrator permission(s) to run this command.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 71, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\cyberx\Desktop\Paid projects\Discord bot\bot.py", line 25, in clear_error
await client.send_message(ctx.message.channel, text)
AttributeError: 'Bot' object has no attribute 'send_message'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\cyberx\Desktop\Paid projects\Discord bot\bot.py", line 14, in on_message
await client.process_commands(message)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 976, in process_commands
await self.invoke(ctx)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 943, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 424, in dispatch_error await injected(ctx, error)
File "C:\Users\cyberx\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 77, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'send_message'
You need to make an error handler, like this:
#<commandname>.error
async def <commandname>_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions): #could be other type of error
await ctx.send(f"Sorry {ctx.author.mention}, you do not have permissions to do that!")
If you are a newcomer, I recommend reading this: https://vcokltfre.dev/tutorial/12-errors/
Also, to delete the trigger just use await ctx.message.delete()
Firstly, the error handler should be commands.MissingPermissions not MissingPermissions.
Secondly, client.send_message() was deprecated in the rewrite.
Thirdly, I don't think you can use discord.py in python 2.7, maybe upgrade to python 3.

Discord on_reaction_add error Unknown Role

i want to create a bot, who will get user a role via reaction.
The code seems to be working but i get an error in console.
But i get an error.
Ignoring exception in on_reaction_add
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "slh.py", line 47, in on_reaction_add
await user.add_roles(user, newrole)
File "/home/pi/.local/lib/python3.7/site-packages/discord/member.py", line 641, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/pi/.local/lib/python3.7/site-packages/discord/http.py", line 223, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
Ignoring exception in on_reaction_add
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "slh.py", line 47, in on_reaction_add
await user.add_roles(user, newrole)
File "/home/pi/.local/lib/python3.7/site-packages/discord/member.py", line 641, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/pi/.local/lib/python3.7/site-packages/discord/http.py", line 223, in request
raise NotFound(r, data)
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
I don't know why i get this error. Because the role "testrole" is exist in my discord. I have try to use discord.utils.get withe name="channelname" and with id="723xxxxx". Both brings the same error.
The Bot has all privilegs/rights on discord.
Who can help me to fix this issue ?
Here is the code:
#bot.event
async def on_reaction_add(reaction, user):
if reaction.emoji == '✅':
newrole = discord.utils.get(user.guild.roles, name="testrole")
await user.add_roles(user, newrole)
Hope someone can help me please.
The problem is that it's trying to add user as a role. You can simply delete that, you do not need to pass it in as an argument as you are already calling the function from the class. Use this instead:
await user.add_roles(newrole)

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