Howe to Upload a Custom Bnot to Discord

How to Make Discord Bot Commands in Python

Photo past the author.

Annotation: If y'all've never built a Discord bot before, check out my recent article on the subject.

If you desire to know how to have your bot to the next level, the showtime thought would be to have some commands for your bot, right? Your gut reaction would be to use the on_message() event listener and stuff it with switch cases or even if statements. However, this is not ideal since that is non the on_message() part's intended purpose. It's to listen for messages from the channel — non to kick off commands.

Luckily, there is a framework that allows united states to create specific commands for our lovely bot equally well as keep our code super make clean because the framework forces us to split up each command into a function.

Assuming you lot are using discord.py, nosotros can leverage the Commands API provided by it.

In this commodity, nosotros will be going over how to create a prefix for your bot, as most bots that you have probably interacted with accept some class of prefix (e.m. $ or !). Subsequently that, we volition be roofing how to create new commands. Finally, we will be going over the built-in help command for the listing of commands that your bot has so that you don't have to create your ain.

1. Creating Your Bot's Prefix

We are going to exist edifice a bot from scratch, simply if you have an existing bot, you are more than than welcome to use that file.

So let's get ahead and add together the items that we demand to get this bot up and running:

This code segment allows us to have a bot that can exist started and can hitting Discord'south API. We are using the load_dotenv() module so that we don't accept our bot token in evidently text.

This is the part we want to focus on the most:

            bot = commands.Bot(command_prefix="$")          

Notice how this line differs from before if you merely used the Client:

            bot = discord.Customer()          

With the first code box, we are creating a Bot object and not a Customer object. The Bot object gives us access to functionality that a Client doesn't.

Now that nosotros have that new line, we are all set to start creating some commands!

ii. Defining Your Bot'south Commands

At present that we have our new Bot object, we can go ahead and kickoff defining commands. The dazzler of commands in a Discord bot is that they are simply functions with decorators on top of them, so nosotros tin easily abstract our code.

Permit'due south build a simple ping command that our bot will recognize using the Commands framework. It volition look something similar this:

            @bot.command()
async def ping(ctx):
await ctx.channel.send("pong")

A few things are happening. First, discover how we added a decorator (@bot.control()) at the superlative of the function. bot is the proper noun of our bot that nosotros divers in the earlier parts of the script and .command() lets the bot know that this is specifically a command.

The adjacent part we need to cover is the proper noun. Whatever you name your function, that is the name of the command on the Discord side. So to invoke our bot's command, it would be "$ping" on Discord, equally y'all can see here:

Ping Pong

If y'all want to name your function something else, you totally tin. The only thing yous need to do is add the name attribute within your decorator like this:

            @bot.control(name="ping")
async def some_crazy_function_name(ctx):
expect ctx.channel.send("pong")

This will have the same outcome as the original code block, so you lot get to choose which one you want to do.

The last thing we need to talk about is the ctx object. This is known equally a Context object. Basically, this object represents everything virtually the server in which the command got invoked. Things like the message, channel, order, the user who sent it, etc. If you are curious about what'due south inside, my suggestion is to either open a debugger when you run the script and so that you can see what'due south inside or refer to the documentation.

3. Allowing Your Bot to Accept Arguments

Now that we have a basic control for our bot, what if we desire to make a control that allows the user who is invoking the bot to include some arguments? For example, what if I desire to tag someone who is on the server? How exercise I do that from a coding perspective? Well, it's pretty unproblematic. We can add some parameters into our command/role'southward parameter list and they will be available to us. Permit me show you a code snippet:

            @bot.command()
async def print(ctx, arg):
expect ctx.channel.transport(arg)

Here, nosotros created a new command called print that will let the bot to impress something that nosotros send to it. When we invoke this command, it looks like this:

An apple tree a twenty-four hour period keeps the doctor abroad.

Every bit y'all tin run into, the command/function takes in an argument that we can merely print back to the aqueduct. Or if y'all want to practice something more complex with it (e.m. grabbing a user if they are tagged), and so you can.

At present the next question in listen is "What about multiple arguments?" Well, it's just as uncomplicated. If you lot want to have multiple arguments, you can add as many as you similar into the parameter list if you are looking for a specific number. If you also want to be cool, you tin can use * in your parameter list, which is a variable list of parameters. Here is an example of the *:

Pretty absurd, huh? This is a pretty common matter in command-line programs. And so as you lot tin can encounter in the lawmaking block, nosotros are using *args in the parameter list, which is a list of arguments that are inputted from the user. Then we only walk through the argument list and add together it to a response cord. This then allows our bot to impress this lovely message:

Apple pie is indeed a yummy dessert.

Utilize whichever makes more sense for your use case, but do know that both methods are bachelor.

four. Using the Built-In Assistance Command

We have covered basically everything you demand to start developing commands for your bot. However, at that place is ane more thing I want to mention, which is a pre-built help bulletin for our commands. Allow me apace demonstrate what I am talking virtually:

A very helpful command indeed.

I went ahead typed in $help into Discord, and this is what I got. If yous look at the code, nosotros never implemented such a thing. However, the Commands framework within discord.py has this already built in. This command pulls all of the commands that are registered with your bot automagically!

Another matter yous can exercise with this is delve into the specific command for more information:

Merely every bit you can see, it doesn't really display anything useful likewise the control name. There is a place for us to put the description of our command, and that is conveniently located within of the decorator of each function:

I added merely the attributes into the decorators, as yous can run across correct above. The help bulletin is used for the in-depth description, so when you blazon $help print, the brief is used as a quick summary when $help is called. Hither is what it looks like when the code is run:

Another absurd affair that I didn't mention is that it shows the parameter list in the specific help message. This tin can be helpful for your users if you name your parameters well enough that users tin can empathize what they mean.

five. Using on_message() With Commands

Now that you have an understanding of how to apply commands, you'll rapidly see that there is an issue with combining both on_message() and your new commands. If you add:

When y'all run this, your commands will no longer piece of work, but your on_message() works. Well, doesn't that defeat the whole purpose of this article? Technically, yes, only there is a way to incorporate both in example yous want to take both the message listener too as your commands. To do so, you lot need to add together this line to your on_message():

With that new line at the bottom of the function, our commands volition now be registered! Without that line, none of the commands will be triggered, and then be sure to add that at the lesser if you want to contain both listeners and commands.

To wrap everything up, here is what the concluding file looks similar:

Determination

Congrats! You now know how to make legit commands for your Discord bot. We've only scratched the surface when it comes to this. There are so many more than things that could be discussed when it comes to the Commands framework. If you are interested, check out the official documentation.

Every bit usual, the source code is on GitHub.

Run across you lot guys in the adjacent i!

nortonsubjecould.blogspot.com

Source: https://betterprogramming.pub/how-to-make-discord-bot-commands-in-python-2cae39cbfd55

0 Response to "Howe to Upload a Custom Bnot to Discord"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel