I've coded a python discord BOT and I've had this problem for quite some time now. It doesn't except the errors even though I have mentioned it in the code. This is the snippet that has the issue ==>
#client.command()
async def spoiler(ctx, *,text):
author = ctx.author
author = author.mention
try:
await ctx.channel.purge(limit=1)
await ctx.send("Spoiler from " + author + "\n" "||" + text + "||")
except discord.errors.Forbidden:
await ctx.send("Grant me the permission to purge channels and try again.")
except asyncio.TimeoutError:
await ctx.send(author + " Are you typing an essay or what?")
except discord.ext.commands.errors.MissingRequiredArgument:
await ctx.send(author + " You need to type the text you want to disclose!")
It's basically a command that uses the spoiler feature in discord. I want the BOT to ask the user to type a text after the command "$spoiler" in case they haven't done it already. I tried typing just the command in my server and I got this error - "discord.ext.commands.errors.MissingRequiredArgumen". I did except that error in the code, but then python just ignores it like it's not even specified.
This is the error that I recieve ==>
Ignoring exception in command spoiler:
Traceback (most recent call last):
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\bot.py",
line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\core.py",
line 851, in invoke
await self.prepare(ctx)
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\core.py",
line 786, in prepare
await self._parse_arguments(ctx)
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\core.py",
line 706, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\core.py",
line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: text is a required
argument that is missing.
Does anyone know a fix for this?
This may not be the way you were handling the error, but it is one of the ways in case all else fails.
#client.command()
async def spoiler(ctx, *,text):
author = ctx.author
author = author.mention
try:
await ctx.channel.purge(limit=1)
await ctx.send("Spoiler from " + author + "\n" "||" + text + "||")
except asyncio.TimeoutError:#using try and except for handling timeout error
await ctx.send("Are you typing an essay or what?")
#spoiler.error
async def spoiler_error(ctx, error):
if isinstance(error, discord.errors.Forbidden):#permission error, may need to change
await ctx.send("Grant me the permission to purge channels and try again.")
if isinstance(error, discord.ext.commands.errors.MissingRequiredArgument):#if text is a missing required argument
await ctx.send("You need to type the text you want to disclose!")
Related
I'm trying to do something like the 'tempmute' command, but an error keeps popping up
:
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
And here is the command code
#commands.command()
#commands.has_permissions(ban_members=True)
async def tempmute(self, ctx, member: discord.Member = None, * time):
if not member:
await ctx.send(embed=discord.Embed(title='Вы должны указать участника!', color=random.choice(colors)))
else:
LMUTED = discord.utils.get(ctx.message.guild.roles, name='LMUTED')
if not LMUTED:
perms=discord.Permissions(send_messages=False)
await ctx.guild.create_role(name='LMUTED',
colour=discord.Colour(0x0000FF),
permissions = perms)
await ctx.send(f'Я создал роль `{LMUTED}`!')
await member.add_roles(member, LMUTED)
await ctx.send(f'Я замьютил {member} на {time}!')
await s(time * 60)
await ctx.remove_roles(member, LMUTED)
Make sure you know how to read python errors.
But the main issue here is that you don't assign LMUTED a value after you create a new role, so it is still None and thus discord.py fails to add the role.
Also, keep in mind that when you do things that expire over time, simply sleeping/waiting in the method is not a good way to handle it, as the thread might be locked. Instead you should use some sort of scheduler. Basically a thing that waits a certain amount of time before running some code.
so I tried to make a discord bot, and whenever I type the .clear command it will delete the message but I have to type the number of messages I want to delete in the command e.g .clear 5. However, I want to send a message whenever someone types the command without defining the number, and I use try exceptions but it still doesn't work as I expected
here's the code
#client.command()
async def clear(ctx, amount):
try:
await ctx.channel.purge(limit=int(amount))
except MissingRequiredArgument:
await ctx.send(f"give the number of message you want to delete - e.g '.clear 5' ")
error messages
Traceback (most recent call last):
File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/home/yves/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: amount is a required argument that is missing.
Python supports default arguments:
#client.command()
async def clear(ctx, amount=None):
if amount is None:
await ctx.send(f"give the number of message you want to delete - e.g '.clear 5' ")
else:
await ctx.channel.purge(limit=int(amount))
Basically, if amount is None, you know that the user didn't supply the amount argument in their command.
You can write a command extension that accepts a variable number of arguments. You can then test len(args) in your code.
For example:
#client.command()
async def clear(ctx, *args):
if len(args) != 1:
await ctx.send(f"give the number of message you want to delete - e.g '.clear 5' ")
else:
await ctx.channel.purge(limit=int(args[0]))
I want to create a bot that will display server information such as server name, server owner's name, total number of members, etc. whenever called upon. I read up on the module's document many times and tried many things. Regardless of all attempts, I have been getting this error whenever I invoke the bot by command. I am using Python 3.9.2 and discord.py module of version 1.6.0, by the way. How can I solve the issue? Thanks in advance!
My Code:
#bot.command()
async def server(ctx, guild: discord.Guild):
await ctx.send(guild.name)
await ctx.send(guild.owner)
await ctx.send(guild.owner_id)
await ctx.send(guild.members)
await ctx.send(guild.member_count)
Error:
Ignoring exception in command server:
Traceback (most recent call last):
File "...\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "...\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 856, in invoke
await self.prepare(ctx)
File "...\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 790, in prepare
await self._parse_arguments(ctx)
File "...\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 706, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "...\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: guild is a required argument that is missing.
Do you need the guild parameter, why don't you just do:
#bot.command()
async def server(ctx):
await ctx.send(ctx.guild.name)
await ctx.send(ctx.guild.owner)
await ctx.send(ctx.guild.owner_id)
await ctx.send(ctx.guild.members)
await ctx.send(ctx.guild.member_count)
You have requested 2 arguments , ctx and guild : discord.Guild when you run the command , you have to use the command in the format !server <guild id/name> , since you didn't mention the <guild id/name> the error was triggered , either you can remove the argument as mentioned in answer given by #PythonProgrammer or you can mention the guild you want to request info of
I am writing an error handler with my discord bot and it was working well until I installed and imported youtube_dl and pynacl (which I am using to make it play music).
Code:
#client.event
async def on_command_error(ctx,error):
if isinstance(error,commands.MissingPermissions):
await ctx.send("You do not have rights to this command.")
await ctx.message.delete()
elif isinstance(error,commands.MissingRequiredArgument):
await ctx.send("You need an argument.")
await ctx.message.delete()
elif isinstance(error,commands.CommandNotFound):
await ctx.send("Invalid Command.")
await ctx.message.delete()
else:
raise error
error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\hensd\bots\bot.py", line 127, in on_command_error
if isinstance(error,commands.MissingPermissions):
AttributeError: 'Command' object has no attribute 'MissingPermissions'
when I test the other possible error I get the same message with the corresponding errors instead of MissingPermissions\
EDIT: The reason this happened is because I created a command called "commands"
which basically showed the commands and what they do. python thought that I was trying to import "commands" from there. All I had to do was rename the command so python was not confused between the two. thanks for the help everyone!
I want to check if user that does command has a Admin role
That is my code:
#client.command(pass_context=True)
#commands.has_role(name='Admin')
async def unban(self, ctx, user):
"""
unbans a user name
:user: user name not mentioned
"""
try:
ban_list = await client.get_bans(ctx.message.server)
if not ban_list:
await self.client.send_message(ctx.message.channel, 'Ban list is empty')
return
for bans in ban_list:
if user.lower() in str(bans).lower():
try:
await self.client.unban(ctx.message.server, bans)
await self.client.send_message(ctx.message.channel, 'Unbanned')
except discord.Forbidden:
await client.send_message(ctx.message.channel, "I don't have permissions to unban")
return
except discord.HTTPException:
await client.send_message(ctx.message.channel, 'Unban failed')
return
else:
await client.send_message(ctx.message.channel, 'This user is not banned from this server')
except:
await client.send_message(ctx.message.channel, "You don't have ``Admin`` role")
But when I try to do the command without an Admin role it shows me this error:
Ignoring exception in command unban
Traceback (most recent call last):
File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
yield from command.invoke(ctx)
File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 367, in invoke
yield from self.prepare(ctx)
File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 344, in prepare
self._verify_checks(ctx)
File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 339, in _verify_checks
raise CheckFailure('The check functions for command {0.qualified_name} failed.'.format(self))
discord.ext.commands.errors.CheckFailure: The check functions for command unban failed.
How to check if user has role Admin in his role list and then he could do this command?
Using the decorator #commands.has_role(name='Admin') is protecting the method from non Admin users already.
It is raising an exception when calling the method, not inside the method.
EDIT: As mentionned by Patrick in the comments, you will need to implement error handling in order to catch the error: https://discordpy.readthedocs.io/en/rewrite/ext/commands/commands.html#error-handling