How to add multiple commands in discord.py - discord.py

How to add multiple commands in discord.py? If we put another commands right below it,the command will not work

To create a new command you just create a new command reference:
The code:
#client.command()
async def command_1(ctx):
await ctx.send("This is command #1")
#client.command()
async def command_2(ctx):
await ctx.send("THis is command #2")
So for each command you just create a new client.command() and async def function

Related

How to replace ctx in app_commands? - Discord.py

I'm using the code:
#app_commands.command(name='command', description='desc command')
async def command_(self, interaction: discord.Interaction):
#body command
For example I need to know the author who sent the team. Usually (if I use not App_Commands), I in the argument of the command of the command set ctx parameter:
#commands.command(name='command', description='desc command')
async def command_(self, ctx):
await ctx.send(ctx.author.name)
But app_commands does not support ctx. So, how can you replace the ctx in app_commands?
Somehow yes, in my opinion should look code look:
#app_commands.command(name='command', description='desc command')
async def command_(self, interaction: discord.Interaction):
ctx = <replacement of ctx>
await interaction.response.send_message(ctx.author.name)
Don't know, it is probably a MessageInteracion, but I don't know how to extract information from it like from ctx.
Many things can be done from the interaction but you can use
ctx = await bot.get_context(interaction) to get the context.
Just note (happened to me) that if you want to transform your old commands to app_commands, check that the messages are sent quickly enough, or you will get an error that didn't happen with #commands.command()

how do i display a message if user puts a non existing sub command?

So I made a sub command that just sends a message back. I found that if the user types a non existing command it still displays the message from the sub command. It sounds confusing but here's an example.
User: ;id
Bot: This command help you find the name of anyone in the server!
User: ;id Slayer
Bot: Bob Miller
So while testing I found if the user sends some thing like ;id jgfjkag the bot still sends the original message for ;id which is "This command help you find the name of anyone in the server!". How would I make the bot send a specific message if the user trys to use a non existing sub command? Here's the code:
#commands.group()
async def id(self, ctx):
if ctx.invoked_subcommand is None:
await ctx.send("This command help you find the name of anyone in the server! ")
#id.command()
async def Slayer(self, ctx):
await ctx.send("Bob Miller")
#id.command()
async def Skel(self, ctx):
await ctx.send("John Dove")
Check ctx.subcommand_passed first:
#commands.group()
async def id(self, ctx):
if ctx.subcommand_passed is None:
await ctx.send("This command help you find the name of anyone in the server!")
elif ctx.invoked_subcommand is None:
await ctx.send(f"Subcommand '{ctx.subcommand_passed}' does not exist.")
This is my favorite method of doing it:
#commands.group(invoke_without_command=True)
async def group(self, ctx):
await ctx.send_help(ctx.command) # invokes the help command for the group
#group.command()
async def subcommand(self, ctx):
await ctx.send("You passed a valid subcommand!")
The invoke_without_command parameter, when set to true, will only call the command if there are no (valid) subcommands passed. This means that if the code inside if the group() function is called, you can safely assume that they didn't pass a subcommand (or passed an invalid one).
I also like to use ctx.send_help, since that will automatically list subcommands. You could replace this with something like:
await ctx.send("You didn't pass a valid subcommand!")
[EDIT]
More careful reading of your question revealed that the subcommand already has some functionality. This makes it more difficult, but this will work:
#commands.group(invoke_without_command=True, ignore_extra=False)
async def group(self, ctx):
await ctx.send("This is a group command!")
#group.error
async def on_group_error(self, ctx, error):
if isinstance(error, commands.TooManyArguments):
await ctx.send("You passed an invalid subcommand!")
#group.command()
async def subcommand(self, ctx):
await ctx.send("You passed a VALID subcommand!")
Here is what it would look like:
!group
Bot: This is a group command!
!group bla
Bot: You passed an invalid subcommand!
!group subcommand
Bot: You passed a VALID subcommand!
NOTE: The ignore_extra field raises the commands.TooManyArguments error, which then invokes the error handler allowing the bot to send the error message. Unfortunately, the default on_command_error hook will still be called. I would suggest ignoring the commands.TooManyArguments error inside of your main error handler to fix this.

I'm trying to make a ship command in discord.py

I'm trying to add a function in discord.py that can mention any user with the user that called the command in a discord chat?
#client.command()
#commands.guild_only()
async def Ship(ctx):
await ctx.send(choice(tuple(member.mention for member in ctx.guild.members)))
You'll have to pass in two member values.
#client.command()
async def Ship(ctx, user_1 : discord.Member, user_2 : discord.Member):
await ctx.send(f"{user_1.mention} and {user_2.mention} seem nice together")
Let's say your command prefix is !, you would run this like !Ship <user> <user>, where you would replace the <user> with the username of the people whom you are trying to ship.

How to disable all commands at once with a single command

I would like to find a way to disable all commands at once using discord.py, I'm semi-new to discord.py and I have not found a way to get it working yet. Here is my code below:
ID='no'
...............
#commands.command()
#commands.is_owner()
async def nocmdrun(self,ctx):
global ID
ID = "yes"
await ctx.send('No Command Run has been activated.')
#commands.command()
#commands.is_owner()
async def yescmdrun(self,ctx):
try:
global ID
ID = "no"
await ctx.send('No Command Run has been deactivated.')
except:
await ctx.send('Failed to deactivate No Command Run.')
def is_no_cmd_run_activated(self):
global ID
ID = "no"
#commands.command()
#commands.check(is_no_cmd_run_activated)
async def tester(self,ctx):
await ctx.send('congrats')
(This is in a cog called developer.py)
Firstly, add import os to the beginning of your main .py file. Then, to load and unload all your cog commands, add this code into the main .py file:
#bot.command()
async def unload(ctx):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.unload_extension(f'cogs.{filename[:-3]}')
await ctx.send('commands unloaded successfully.')
Also, make sure that the folder that your cog files are in is named cogs.
If you want to create a command to load all of the cog commands, you can simply do this:
#bot.command()
async def load(ctx):
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
await ctx.send('commands loaded successfully.')

Is there a way to get the parameters of a command?

I was wondering if there is a way to get the parameters of a command to show how to use it. I have a custom help command, but I tried doing something that uses the same description thing that you put in the decorator. It doesn't work (doesn't give me any errors or anything) but I don't know why.
#commands.command()
async def format(self, ctx, command):
formatting = discord.Embed(title=f"Formatting for .{command}", description=command.description)
formatting.set_thumbnail(url=self.bot.avatar_url)
formatting.set_footer(text=f"Requested by {ctx.author.mention}", icon_url=ctx.author.avatar_url)
ctx.send(embed=formatting)
Here's one of my commands that has the description thing:
"""Change Nickname command"""
#commands.command(aliases=['chnick'], description="Usage: .nick [member mention] [nickname to change to]")
#commands.has_permissions(manage_channels=True)
async def change_nick(self, ctx, member: discord.Member, nick):
"""Changes a user's nickname\nAliases: chnick"""
await member.edit(nick=nick)
await ctx.send(f"Nickname was changed for {member.mention}")
You need to get the command using get_command()
#commands.command()
async def format(self, ctx, command):
command = self.bot.get_command(command)
formatting = discord.Embed(title=f"Formatting for .{command.name}", description=command.description)
formatting.set_thumbnail(url=self.bot.avatar_url)
formatting.set_footer(text=f"Requested by {ctx.author.mention}", icon_url=ctx.author.avatar_url)
await ctx.send(embed=formatting)

Resources