Change language

Creating a Discord bot in Python

|

Hi all, today we are going to write a Discord bot in Python and discord.py + a bonus look at some example bots. Let's get started 🙂

Before you get to work

Before you start, you need:

  • Python 3;
  • discord.py;
  • Discord account and your server.

Use the batch manager to install discord.py:

pip3 install discord.py

Creating our bot

Go to the Developer Portal and click on New application.

You have created your application, on the application page go to Bot >> Add Bot and create your Discord bot.

Save the bot token! We'll need it from here!

If all went well, congratulations, half the battle is done 😀

Adding bot to the server

Now you can add the bot to the server.

Go to OAuth2 >> URL Generator, in Scopes select Bot and below select bot rights, copy the generated URL. Paste into browser, and add to our server.

Echo bot

Let's write a traditional echo bot, and break down each line of code.

Code:

import discord
from discord.ext import commands

config = {
    'token': 'your-token',
    'prefix': 'prefix',
}

bot = commands.Bot(command_prefix=config['prefix'])

@bot.event
async def on_message(ctx):
    if ctx.author != bot.user:
        await ctx.reply(ctx.content)

bot.run(config['token'])

Details

The imports we need:

import discord
from discord.ext import commands

Auxiliary dictionary config in which we store the token and command prefix (I'll tell you why we need the command prefix later):

config = {
    'token': 'your-token',
    'prefix': 'prefix',
}

Create our bot, pass the prefix in the argument:

bot = commands.Bot(command_prefix=config['prefix'])

The decoder is designed to handle events:

@bot.event

We create an asynchronous function with the parameter ctx, which is a message:

async def on_message(ctx):

Check if the author of the message is our Discord bot. The point is that if the bot sends a message, it will be a new event, and then we get a loop.

if ctx.author != bot.user:

We reply to the message (ctx.reply) and pass the message (ctx.content) into the arguments:

await ctx.reply(ctx.content)

Launch our bot, pass bot's token in the arguments:

bot.run(config['token'])

I hope you have understood the code and we can move on.

Processing Commands

Before we can process commands, we need our prefix.

Consider the code:

import random
import discord
from discord.ext import commands

config = {
    'token': 'your-token',
    'prefix': '$',
}

bot = commands.Bot(command_prefix=config['prefix'])

@bot.command()
async def rand(ctx, *arg):
    await ctx.reply(random.randint(0, 100))

bot.run(config['token'])

Command processing decoder:

@bot.command()

Asynchronous rand function:

async def rand(ctx, *arg):

Responds to a message, giving a random number between 0 and 100 as an argument:

await ctx.reply(random.randint(0, 100))

Bonus

Role checking:

import random
import discord
from discord.ext import commands

config = {
    'token': 'your-token',
    'prefix': '$',
}

bot = commands.Bot(command_prefix=config['prefix'])

@bot.command()
@commands.has_role("Owner")
async def rand(ctx, *arg):
    await ctx.reply(random.randint(0, 100))

bot.run(config['token'])

Kick the user out:

import discord
from discord.ext import commands

config = {
    'token': 'your-token',
    'prefix': '$',
}

bot = commands.Bot(command_prefix=config['prefix'])

@bot.command()
async def kick(ctx, user : discord.User(), *arg, reason='Reason not specified'):
    await bot.kick(user)
    await ctx.send('User {user.name} kicked out because of "{reason}"')

bot.run(config['token'])

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically