A simple tutorial to get you started with Discord and it's Python API

Overview

Hello there

Feel free to fork and star, open issues if there are typos or you have a doubt.

I decided to make this post because as a newbie I never found out how to make a Discord bot easily. It was a lot of trial and error.

The prerequisites

  1. Basic Python knowledge
  2. Know how APIs work
  3. Must have a Discord and a Discord Developer account.

Let's dive right into it!

We'll first be making our Discord API ready.

Discord and it's API

Here we'll be configuring the bot user and the Discord API.

To get started head to the Discord developer portal. DDP

Should look something like this.

Next up, head to the applications section in the menu at the left.

Applications menu

This is where we'll be making our new application.

The application dashboard should look something like this.

Application dashboard

Click on the New Application Button as highlighted.

This leads to a dialogue box being opened which looks something like this:

DB Enter your bots name.

After this the Application Dashboard will now redirect to a page which looks like this:

Page redirect This is the application control page.

After that is done, head towards the Bot option under the menu in the left

Menu left

Click on the Add Bot option as highlighted.

A dialogue box appears prompting you to add a bot.

Bot

This leads you to the Bot page,

Bot page

Here you can add a cool pfp for your bot!

Here you'll notice something called, a "Token", do not share this with anyone, it can be misused. This Token is something like the API key.

We will need this as we're about to start coding!

The actual code

Our Directory should look something like this:

Directory

Now lemme explain what the env file is, it is usually used to store environment variables. Here we'll be using it to store Discord API "Token". Here's how you must fill an env file, first in notepad, write the following:

text

Now save this file as an env file by changing it's extension and you're good to go.

Bot scope

Here we'll be dealing with what we want our bot to do, that is moderation in this case. A simple Ban command, Kick command, Fetch user avatar command should be good enough for this tutorial.

The Discord API has 2 user classes:

  1. The bot class
  2. The client class

Note that the bot class is more versatile than the client class and we'll be using bot class in this tutorial here. Since we're coding a bot, it should run on multiple instances, for example if the bot is in multiple servers, it should be able to handle multiple commands at the same time. For this we use something known as asynchronous programming and we'll be skimming through the basics here.

Imports

Before starting here are a few imports you should make, assuming you have already pip installed the discord module. also install the asyncio module.

import os
from discord.ext import commands
import discord
from dotenv import load_dotenv
from discord import Member
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
import random
import asyncio

These should be enough for what we'll be doing

The .ENV invoker

load_dotenv('DISCORD_TOKEN.env')#loads client secret from the .env file in the same directory
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='^') #change it to whatever you want
bot.remove_command("help")

This code snippet basically loads the Token that we had saved earlier in our .env file into the code so that it can be used to connect to the API.

Adding functions

@bot.command()
@commands.has_permissions(ban_members=True)#bans members if admin role is true
async def ban(ctx, user: discord.Member, *, reason="No reason provided"):
        await user.ban(reason=reason)
        ban = discord.Embed(title=f":boom: Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}",color=0xB026FF)
        await ctx.message.delete()
        await ctx.channel.send(embed=ban)
        await user.send(embed=ban)

The first line @bot.command() here invokes the bot class. The second line checks if the person using the command has the required permission or not. The third line is where we define our function and it's arguments. It takes members and a reason as arguments, where reason for banning is optional. The fourth line onwards it simply builds an embed, an embed here has many features, it is out of scope of this tutorial though.

Upon executing this command the person mentioned is banned if they have the ban perms or the admin perms.

Next up the kick command:

@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, user: discord.Member, *, reason="No reason provided"):
        await user.kick(reason=reason)
        ban = discord.Embed(title=f":boot: Kicked {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}",color=0xB026FF)
        await ctx.message.delete()
        await ctx.channel.send(embed=ban)
        await user.send(embed=ban)

The explanation is the same as the ban command except this time the bot simply kicks the mentioned user.

Finally the avatar command:

@bot.command()## get mentioned users avatar
async def av(ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)

The first line again invokes the bot class The second one is where the function is defined, it takes username as the argument. The bot then displays the mentioned users avatar url.

We'll also be adding a very simple help command:

@bot.command()##help command
async def help(ctx):
    em = discord.Embed(title="Tutorial Bot command list:", description="", color=0x2f3136)
    em.add_field(name="`^ban {user}`", value="Bans the user.")
    em.add_field(name="`^kick {user}`", value="Kicks user.")
    em.add_field(name="`^av {user}`", value="Gets the mentioned users pfp.")
    
    em.set_footer(text="GitHub Discord bot made by cyber")
    await ctx.send(embed=em)

Final code snippet, this helps us know when the bot is online.

@bot.event
async def on_ready():
    activity = discord.Game(name="A game", type=3) #you can change from playing to watching, etc 
    await bot.change_presence(status=discord.Status.online, activity=activity)
    print("Bot is ready!")

It also helps us set the bots status.

Ending the script

Finally add this in your code, it runs the Token and helps connect the API to your code.

bot.run(TOKEN)

Now let's invite this to a server!

Head to the Developer Portal again, Go to the OAuth2 dashboard. Scroll down and you'll find scopes section, click on the bot scope.

Image description

Scroll down and you'll find a Permission checker for the Bot. Since these are the Perms needed by my bot I will be checking those off.

Image description

Now copy the Link provided, this is your bots invite link!

Image description

Paste it in your browser and you will be redirected to the Invite page.

Image description

It should lead you to this page once authorised.

Image description

Now let's test it out in our server! First run the script and this should appear in the shell.

Image description

In the server the bot should appear online.

Image description

Now let's test all the features:

  1. Ban
  2. Kick
  3. User avatar
  4. Help command

Test case-1: Show help command

Image description

Result: Passed

Test case-2: Kick user

Image description

This is the other user named Earth Chan, we are going to try and kick it.

Image description

The user is now kicked. Result: Passed

Test case-3: Ban user We are going to invite the same user and try banning them.

Image description

The user has been banned.

Image description

Result: Passed

Test case-4: Get user avatar

Image description

Result: Passed

Our bot has passed all the test cases! You can add tons of other features to it and make it more versatile. The possibilities are endless.

Bot hosting

You might observe that the bot goes offline once the script stops running, to combat this problem we use hosting solutions like repl.it or Cloud Services, I personally use a Raspberry Pi to host my bots.

Hosting won't be covered in this tutorial, there are tons of YouTube tutorials on them.

What next?

Well you can build whole economies, moderation bots, music bots, image manipulation, memes from reddit using the reddit API and so much more, here is an example of what I did.

The Discord API also exists in JavaScript, Java, Typescript and Ruby.

Final code

Your code must look something like this:

import os
from discord.ext import commands
import discord
from dotenv import load_dotenv
from discord import Member
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
import random
import asyncio

load_dotenv('DISCORD_TOKEN.env')#loads client secret from the .env file in the same directory
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='^') #change it to whatever you want
bot.remove_command("help")

@bot.event
async def on_ready():
    activity = discord.Game(name="A game", type=3) #you can change from playing to watching, etc 
    await bot.change_presence(status=discord.Status.online, activity=activity)
    print("Bot is ready!")
    
@bot.command()
@commands.has_permissions(ban_members=True)#bans members if admin role is true
async def ban(ctx, user: discord.Member, *, reason="No reason provided"):
        await user.ban(reason=reason)
        ban = discord.Embed(title=f":boom: Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}",color=0xB026FF)
        await ctx.message.delete()
        await ctx.channel.send(embed=ban)
        await user.send(embed=ban)

@bot.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, user: discord.Member, *, reason="No reason provided"):
        await user.kick(reason=reason)
        ban = discord.Embed(title=f":boot: Kicked {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}",color=0xB026FF)
        await ctx.message.delete()
        await ctx.channel.send(embed=ban)
        await user.send(embed=ban)

@bot.command()## get mentioned users avatar
async def av(ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)

@bot.command()##help command
async def help(ctx):
    em = discord.Embed(title="Tutorial Bot command list:", description="", color=0x2f3136)
    em.add_field(name="`^ban {user}`", value="Bans the user.")
    em.add_field(name="`^kick {user}`", value="Kicks user.")
    em.add_field(name="`^av {user}`", value="Gets the mentioned users pfp.")

    em.set_footer(text="GitHub Discord bot made by cyber")
    await ctx.send(embed=em)

bot.run(TOKEN)

Happy Coding! And if any doubts please do leave it in the comments or contact me on Discord (cyber#7596), you can also follow my Twitter @thereal_cyber

You might also like...
A simple document management REST based API for collaboratively interacting with documents

documan_api A simple document management REST based API for collaboratively interacting with documents.

A collection and example code of every topic you need to know about in the basics of Python.
A collection and example code of every topic you need to know about in the basics of Python.

The Python Beginners Guide: Master The Python Basics Tonight This guide is a collection of every topic you need to know about in the basics of Python.

This is a repository for "100 days of code challenge" projects. You can reach all projects from beginner to professional which are written in Python.

100 Days of Code It's a challenge that aims to gain code practice and enhance programming knowledge. Day #1 Create a Band Name Generator It's actually

This repo contains everything you'll ever need to learn/revise python basics
This repo contains everything you'll ever need to learn/revise python basics

Python Notes/cheat sheet Simplified notes to get your Python basics right Just compare code and output side by side and feel the rush of enlightenment

A Python Package To Generate Strong Passwords For You in Your Projects.

shPassGenerator Version 1.0.6 Ready To Use Developed by Shervin Badanara (shervinbdndev) on Github Language and technologies used in This Project Work

API spec validator and OpenAPI document generator for Python web frameworks.

API spec validator and OpenAPI document generator for Python web frameworks.

The blazing-fast Discord bot.
The blazing-fast Discord bot.

Wavy Wavy is an open-source multipurpose Discord bot built with pycord. Wavy is still in development, so use it at your own risk. Tools and services u

FxBuzzly - Buzzly.art links do not embed in Discord, this fixes them (rudimentarily)
FxBuzzly - Buzzly.art links do not embed in Discord, this fixes them (rudimentarily)

fxBuzzly Buzzly.art links do not embed in Discord, this fixes them (rudimentaril

Highlight Translator can help you translate the words quickly and accurately.
Highlight Translator can help you translate the words quickly and accurately.

Highlight Translator can help you translate the words quickly and accurately. By only highlighting, copying, or screenshoting the content you want to translate anywhere on your computer (ex. PDF, PPT, WORD etc.), the translated results will then be automatically displayed before you.

Releases(v0.1)
Owner
Sachit
Class 11, Med 2023
Sachit
A fast time mocking alternative to freezegun that wraps libfaketime.

python-libfaketime: fast date/time mocking python-libfaketime is a wrapper of libfaketime for python. Some brief details: Linux and OS X, Pythons 3.5

Simon Weber 68 Jun 10, 2022
💻An open-source eBook with 101 Linux commands that everyone should know

This is an open-source eBook with 101 Linux commands that everyone should know. No matter if you are a DevOps/SysOps engineer, developer, or just a Linux enthusiast, you will most likely have to use

Ashfaque Ahmed 0 Oct 29, 2022
PythonCoding Tutorials - Small functions that would summarize what is needed for python coding

PythonCoding_Tutorials Small functions that would summarize what is needed for p

Hosna Hamdieh 2 Jan 03, 2022
Documentation and issues for Pylance - Fast, feature-rich language support for Python

Documentation and issues for Pylance - Fast, feature-rich language support for Python

Microsoft 1.5k Dec 29, 2022
Generate a single PDF file from MkDocs repository.

PDF Generate Plugin for MkDocs This plugin will generate a single PDF file from your MkDocs repository. This plugin is inspired by MkDocs PDF Export P

198 Jan 03, 2023
This program has been coded to allow the user to rename all the files in the entered folder.

Bulk_File_Renamer This program has been coded to allow the user to rename all the files in the entered folder. The only required package is "termcolor

1 Jan 06, 2022
Read write method - Read files in various types of formats

一个关于所有格式文件读取的方法 1。 问题描述: 各种各样的文件格式,读写操作非常的麻烦,能够有一种方法,可以整合所有格式的文件,方便用户进行读取和写入。 2

2 Jan 26, 2022
A plugin to introduce a generic API for Decompiler support in GEF

decomp2gef A plugin to introduce a generic API for Decompiler support in GEF. Like GEF, the plugin is battery-included and requires no external depend

Zion 379 Jan 08, 2023
SCTYMN is a GitHub repository that includes some simple scripts(currently only python scripts) that can be useful.

Simple Codes That You Might Need SCTYMN is a GitHub repository that includes some simple scripts(currently only python scripts) that can be useful. In

CodeWriter21 2 Jan 21, 2022
Jupyter Notebooks as Markdown Documents, Julia, Python or R scripts

Have you always wished Jupyter notebooks were plain text documents? Wished you could edit them in your favorite IDE? And get clear and meaningful diff

Marc Wouts 5.7k Jan 04, 2023
Materi workshop "Light up your Python!" Himpunan Mahasiswa Sistem Informasi Fakultas Ilmu Komputer Universitas Singaperbangsa Karawang, 4 September 2021 (Online via Zoom).

Workshop Python UNSIKA 2021 Materi workshop "Light up your Python!" Himpunan Mahasiswa Sistem Informasi Fakultas Ilmu Komputer Universitas Singaperban

Eka Putra 20 Mar 24, 2022
Course materials and handouts for #100DaysOfCode in Python course

#100DaysOfCode with Python course Course details page: talkpython.fm/100days Course Summary #100DaysOfCode in Python is your perfect companion to take

Talk Python 1.9k Dec 31, 2022
Code and pre-trained models for "ReasonBert: Pre-trained to Reason with Distant Supervision", EMNLP'2021

ReasonBERT Code and pre-trained models for ReasonBert: Pre-trained to Reason with Distant Supervision, EMNLP'2021 Pretrained Models The pretrained mod

SunLab-OSU 29 Dec 19, 2022
Pyoccur - Python package to operate on occurrences (duplicates) of elements in lists

pyoccur Python Occurrence Operations on Lists About Package A simple python package with 3 functions has_dup() get_dup() remove_dup() Currently the du

Ahamed Musthafa 6 Jan 07, 2023
This repo contains everything you'll ever need to learn/revise python basics

Python Notes/cheat sheet Simplified notes to get your Python basics right Just compare code and output side by side and feel the rush of enlightenment

Hem 5 Oct 06, 2022
Grokking the Object Oriented Design Interview

Grokking the Object Oriented Design Interview

Tusamma Sal Sabil 2.6k Jan 08, 2023
Python 3 wrapper for the Vultr API v2.0

Vultr Python Python wrapper for the Vultr API. https://www.vultr.com https://www.vultr.com/api This is currently a WIP and not complete, but has some

CSSNR 6 Apr 28, 2022
BakTst_Org is a backtesting system for quantitative transactions.

BakTst_Org 中文reademe:传送门 Introduction: BakTst_Org is a prototype of the backtesting system used for BTC quantitative trading. This readme is mainly di

18 May 08, 2021
Sane and flexible OpenAPI 3 schema generation for Django REST framework.

drf-spectacular Sane and flexible OpenAPI 3.0 schema generation for Django REST framework. This project has 3 goals: Extract as much schema informatio

T. Franzel 1.4k Jan 08, 2023
Mkdocs obsidian publish - Publish your obsidian vault through a python script

Mkdocs Obsidian Mkdocs Obsidian is an association between a python script and a

Mara 49 Jan 09, 2023