Discord bot with Python
Tags: python, discord, bot
Published: 2022-03-27 05:03:21

## Table of Contents

[Create a test server](#create-a-test-server)
[Get a bot application](#get-a-bot-application)
[Invite your bot](#invite-your-bot)
[Initial Files](#initial-files)
[Bot Files](#bot-files)

## Create a test server

Creating a server will first require you to have signed up for a Discord account if you haven't already. Assuming the reason you're reading this is because you do have an account...so onward!

> In case you haven't registered an account with Discord you can register <a href="https://discord.com/register" target="_blank">here</a>

Log into Discord and at the bottom of the servers will be a "`+`" symbol.

- Give your server a name like `awesome test server` or `test server` or whatever you wish.
- Upload an icon
- Then create it!

## Get a bot application

To get started we'll need to get a bot application from the [Discord Developer Portal](https://discord.com/developers/docs/intro)

You may be asked to log into a Discord account. Once logged in follow the steps below to get a bot application setup.

- Go to *Applications* tab found at the top left
- Click *New Application* at the to right
- Give your bot a name (this can be changed later if you wish)

You should now be taken to the *General Information* of your newly created application.

From here you will be able to change the icon, name, give a description, tags and more.

> **Note:**
> The description you give your bot will show in Discord once it has joined the server.

From here navigate to the *Bot* tab on the left under settings.
Click `Add Bot`. If the username has been taken you'll need to go back and change the name until Discord allows the bot with that username to be used.

Once the bot has been created you'll have options to select that will become more important later on.

## Invite your bot

Open the `OAuth2` -> `URL Generator`, where you'll be able to create a redirect for your bot invitation.

![OAuth2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yz2v1ihw1nllg6v8g60w.png)

For the sake of simplicity, we'll just be using *Administrator* permissions to allow the bot to work however it will need.

### Scope

![Scope](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vf139x1ook3hhebhi2o5.png)

This will generate a URL which can copy and paste in a browser and it will take you to the invite screen where you will then be able to invite your bot to any server that you have **Manage Server** permissions within your current role on said server.

### Invite

![Invite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qri25wrfsbtim5mqase7.png)

Follow the prompts that follow when invite is granted to a server. I will ask for permissions that are enabled on the current [scope](#scope)

Once the bot has been authorized check the server that you invited it to or the [server you created](#create-a-test-server) at the beginning of this tutorial and check to see that your bot is now a part of your member list!

Now we can see the bot has join! It shows that the bot is offline and we'll fix that soon enough!


![Bot Offline](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p02zgmdlcoxw361j74ug.png)

## Initial Files

Open or create a directory where you'll store the code for your bot in the terminal.

This will be where all necessary files required throughout the process.

Use the following commands below to get started

```shell
mkdir references
touch references/token.txt
touch bot.py
touch .gitingnore
```

### Install Python

We are going to need to be using Python version 3.8 and higher.
To check what version of Python you have type `python3 --version` in a terminal window.

If you have 3.8 or higher you can continue to [installing pip](#install-pip).

To install Python go [python.org](https://www.python.org/downloads/) where you can download the current stable version of Python3.

Call `python3 --version` again to see if Python has been installed. This may require you to open a new terminal window.

### Install Pip

Pip is a package manager for Python and will be used to get the Discord library in the next step.

- `curl https://bootstrap.pypa.io/get-pip.py -o references/get-pip.py`
- `python3 references/get-pip.py`

Check if pip is installed
- `python3 -m pip --version`

### Install Nextcord.py library

> `python3 -m pip install -U nextcord`

Nextcord is a modern, easy-to-use, feature-rich, and async-ready API wrapper for Discord written in Python.

Resource information can be found [here](https://pypi.org/project/nextcord/).

The documentation for using this library can be found at [nextcord.readthedocs.io](https://nextcord.readthedocs.io/en/stable/).

## Bot files

We will need to go back to the [Developer Portal](https://discord.com/developers/applications) and choose the bot we are setting up.

In the `Bot` tab we can find the token needed

### Token

![bot token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezia45oe7sr1dx9o239z.png)

Copy your bot token and paste it in `references/token.txt`.

Inside the `bot.py` file begin by writing some initial code to get the bot online.

```Python
# Import the nextcord library
import nextcord

# Additional resources
from nextcord.ext import commands

# set client variable for the bot
client = commands.Bot(command_prefix="$")

# Paste your token ID here
token = <your-token-here>

# Call the bot!
client.run(token)
```

This is a quick and dirty way to do this and if you make this repo public, we will need to do some housekeeping.

In `.gitignore`, to hide your token ID we'll want to add `references/*`

This will ignore all files inside the references folder.

Now to rewrite how we access our token in a better fashion.

```Python
with open("./references/token.txt", "r") as f:
    token = f.read()
```

We can run the bot now with

```Python
python3 bot.py
```

You should now see your bot has come online, but it can't do anything. Let's add some thing for it to do.

Use "control + C" to stop. Put this code above

```Python
# on_ready() is a special event listener that runs once on bot start
@client.event
async def on_ready():
    # Print line to the console
    print("Ready!")
    # Show the bot's registered name with denominator
    print(f"Logged in as {client.user}\n")

# This is a command that will respond when '$ping' is used in the Discord client window for any user.
@client.command()
async def ping(ctx):
    await ctx.send("pong")
```

## Conclusion

Now we have a bot that can have commands added and help moderate your server through extensions known as `cogs`.

We'll get to that next time, but for now try making some commands and making your bot do some great things!

[Back to top](#table-of-contents)