DEV Community

Cover image for Create a Discord Bot in Minutes with Python
Simon Pfeiffer for Codesphere Inc.

Posted on

Create a Discord Bot in Minutes with Python

Written by Lior Ben David.


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.

Image description

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

Image description

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:

Image description


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!

Image description

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!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.