Heya! We use cookies

Codesphere uses cookies to understand your preferences and make sure you have the best experience on our site. By using Codesphere, you accept our use of cookies.

Understood. Yum!

Create a Discord Bot in Minutes with Python

11.11.2021

If there’s any platform that’s become the darling of online communities, it's Discord. Its intuitive UX, vibrant communities, and diverse feature set have allowed it to grow rapidly over the 6 years.

Among developers at least, a lot of the love for Discord comes from its high programmability. In this tutorial, we are going to be making a simple Discord Bot with Python that you can add to your servers.

Setting Up Your Bot in the Developer Portal

To get started, first head to

https://discord.com/developers/applications

And Create a New Application

From there, head to the “Bot” tab and create a new bot.

Finally, to add our bot to a server, go to the oAuth2 tab, scroll down to scopes, check bot and visit the generated URL.

You can then select the server you want to add the bot to and you should see it on your server under offline users

That’s all we need to do from the Discord side!

Project Setup

Now let’s code our bot.

First, install discord.py with:

pip install discord

And create a new file called main.py

We can then authenticate our discord like so:

You can find your authentication token in the Bot Tab in your developer portal

Responding to Messages

Now let’s read and respond to messages that people send in channels

We need to include the bot.process_commands at the end in order to make sure the bot also checks if the message is a valid command.

And here you can see it working:

Creating Commands

Now let’s add commands. Commands are just responses that are specifically invoked. We designated at the beginning that each command has to start with ‘!’, which will act as the “Alexa” to start listening for a command.

We are going to add two commands, one that returns the square of a number, and one that tells us the scrabble points for a specific word.

And here we can see it working!

Deploying Your Bot

Now, of course, you’re not going to want to be running your script from your local machine 24/7. That’s why it’s crucial to deploy your script in the cloud.

If you want to skip the whole cumbersome cloud setup process, try out Codesphere. On Codesphere, you can just import your project and run it from a virtual machine as if it was being deployed locally.

It only takes minutes to deploy!

So what are you going to build? Let us know down below!

SHARE

  • Share on Twitter
  • Share on Facebook
  • Share on LinkedIn
  • Copy the link