Creating a Discord Bot with Python - Part 1: Creating credentials and a test command

in utopian-io •  7 years ago  (edited)

image alt

Introduction

What Will I Learn?

In this tutorial, we will create a new Discord Bot Profile and retrieve its API key. Then we will add the bot to our server and create a first test command. This tutorial is needed for the tutorials following in this series.

Requirements

  • A discord account. Create one here.
  • Python 3. Download it here.

Difficulty

  • Beginner

References

All the files and scripts presented in this series are available on my GitHub Page here. The files needed for this tutorial are available in this commit
This tutorial is part of a series. I will explain in detail how I made this Discord bot. This is the first part, so look out for more!

So, let's get started!

1. Creating the Discord App

Head over to the Discord "My Apps Page" and create a new app by clicking the "New App" Button. Give your new app a name. This name will be shown to other users. Optionally, you can add an app icon and a description for your app. And that's that. You should now see a message stating "Your sweet new application has been created successfully!".

2. Creating the Bot

You now have created the app, but it has not been assigned a bot user yet. Head over to the configuration page of your app and under the category "Bot" click on "Create a Bot User". Confirm the dialog with "Yes, do it!". Congratulations, your bot is now created!

3. Test the credentials & API

Get the bot username and token from the bot category of the settings page of your app. Do not confuse Client Secret and Bot Token! You do not need the Client Secret, but the token listed under the Bot category. Anyone with this token can access your bot, so be careful not to share it.

Use pip (via the command line) to install the discord.py API: python -m pip install -U discord.py[voice]

Create a new file with the following contents and run it.

import discord

client = discord.Client()
token = "YOUR TOKEN HERE"

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run(token)

If you get an error at import discord, make sure the discord library was installed correctly. Re-run the command python -m pip install -U discord.py[voice] and leave the output in the comments. I will help you resolve your problem.

If you get an error later in the code, you probably used the wrong token. Make sure you used the bot token and not the client secret. If you did use the correct token, please leave your error & stack trace in the comments. Make sure to blank out your token.

4. Adding the Bot a server

We now will generate an OAuth link for our bot. Head to the Bot control panel and click "Generate OAuth2 URL". Leave the Redirect URI empty and leave the scope set to "Bot". For development, I recommend setting the permissions to Administrator, so that you won't have to deal with that. Click the box next to "Administrator" and then click "Copy". If you want to publish your bot, you should not require Administrator permissions. Only select the permissions your bot needs, like view channels, send messages and whatever else you might need. Once you have the link copied, paste it into your URL bar and open it. In the drop-down menu, select your development server and click "Authorize". You will now see the bot join your server, but he will be offline. In the next step, we will create our first command and let the bot come to life.

5. First command creation

And now we begin the creation of the first function of our bot. For demonstration purposes, we will make a simple function wherein the bot replies "Hello, User" when a user sends "!test".
First, we import the discord library: import discord.
Then we create a variable which holds our token. When sharing your code, remember to replace this variable with something like token = "token".
We then create a new Client object. This object will be used to keep track of our bot:
client = discord.Client().
We will listen to 2 events that the client class provides: on_ready and on_message. on_ready fires when the bot logged into discord, so we log that to the console:

@client.event 
async def on_ready(): 
    print('Logged in as')
    print(client.user.name) 
    print(client.user.id) 
    print('------') 

client.user.name provides the display name of the bot and client.user.id provides the id.

on_message fires when a new message is sent to any discord server that the bot is in. We use this event to check if a command was executed. We can retrieve the message that was sent with message.content and the channel that it was sent in with message.channel.

async def on_message(message): 
    if message.content == "!test": 
        print("Received test command!") 
        await client.send_message(message.channel, "Hello, " + message.author.name)

For now, we will use a simple if statement to check if the message has the content "!test". If it does, send a message to the channel that the message originated from with the message "Hello," and the display name of the user who sent the message. We also log in the console that the command was executed.

At last, we have to start the bot with client.run(token). Here is the final script.

import discord # Discord API Wrapper 


token = "YOUR TOKEN HERE" 
# Create new client 
client = discord.Client() 

# Log to console when the client is started 
@client.event 
async def on_ready(): 
    print('Logged in as')
    print(client.user.name) 
    print(client.user.id) 
    print('------') 


# Fires every time a new message is received 
@client.event 
async def on_message(message): 
    if message.content == "!test": 
        print("Received test command!") 
        await client.send_message(message.channel, "Hello, " + message.author.name) 
        
        
# Connect the client to Discord 
client.run(token)

Save this file and run it. You should see that the bot will now appear online on your server and the console should state that it logged in as the bot user. Now send "!test" in the discord server and the Discord Bot will reply with "Hello, " followed by your display name. If you have any problems with this script, please let me know in the comments and I will resolve your problem.

Curriculum

If you got this far without errors, that means you are ready to start creating a discord bot. Follow me to see the next tutorial as soon as possible, where we will create a command class to simplify the creation of commands.

Thank you for reading my tutorial! I hope you liked it. If you have any recommendations for future tutorials please leave a comment. I'll upvote any constructive criticism!



Posted on Utopian.io - Rewarding Open Source Contributors

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

Explanation:

  • Discord itself is not open source, only the documentation of its API is. So if you for example would have added content the the API documentation itself, that could have qualified;
  • also, your content it too trivial / not explained well enough: you dropped in some code, but didn't really explain what the code does / is about.

You can contact us on Discord.
[utopian-moderator]

Congratulations @dev.central! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

Are you a DrugWars early adopter? Benvenuto in famiglia!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!