Skip to content

Instantly share code, notes, and snippets.

@scragly
Last active March 27, 2024 21:45
Show Gist options
  • Save scragly/095b5278a354d46e86f02d643fc3d64b to your computer and use it in GitHub Desktop.
Save scragly/095b5278a354d46e86f02d643fc3d64b to your computer and use it in GitHub Desktop.
Learning discord.py

Learning discord.py

This guide assumes your version of discord.py is updated to at least v1.0 or greater.
You can check your version with pip show discord.py.

Show Contents

Required Knowledge

Interest in creating a Discord bot is a common introduction to Python for those on Discord.

Using it as your first project while trying to learn is a double-edged sword due to the large number of concepts a bot can have involved. Learning while making one can be more arduous than picking more beginner friendly alternatives.

However in return, you get the opportunity to expose yourself to many more aspects of Python than you normally would!

With the right attitude and determination, learning while building a bot can be an amazingly rewarding experience as you reach your project goals.

Bots have a huge scope of things you can do with it, so over time you are able to continue to learn and apply more advanced concepts as you grow as a programmer.

This guide is not a tutorial, but instead aims to help you identify all the concepts you might need, provide resources to make the path to learning as clear and easy as possible, and collates useful examples provided by the community that may address common ideas and concerns that are seen when working on Discord bots.

Essentials

These subjects you should try get familiar with soon after deciding to build with discord.py.

Reference the list when needed and use the terms provided to find appropriate resources and tutorials on subjects you're not familiar with or feel a little lacking with.

This will prevent confusion and frustration when receiving help from others, when reading documentation and when debugging any issues in your code.

  • Primitive data types
  • Operators
  • Data structures
  • Importing
  • Variables, namespace and scope
  • Control flow
    • while
    • if
    • elif
    • else
    • for
  • Exception handling
    • try
    • except
    • finally
    • with
  • Function definitions
  • Argument definitions
    • Argument ordering
    • Default arguments
    • Variable length arguments
  • Classes, objects, attributes and methods
  • Console usage, interpreters and environments
  • Asyncio basics
    • await
    • async def
    • async with
    • What is blocking?
  • String formatting

Recommended

This section contains subjects that would be extremely helpful in knowing well as you're likely to encounter them during usage, but a deeper understanding of them aren't essential to using discord.py.

  • String formatting
    • printf-style (%)
    • Formatted string literals, known as f-strings
    • Implicit/explicit string concatenation
  • Logging
  • Decorators

Essential References

Official Documentation:
https://discordpy.readthedocs.io/

Source Repository:
https://github.com/Rapptz/discord.py

Creating a Discord Bot Account

  1. Navigate to https://discordapp.com/developers/applications and log in if not already.
  2. Click on Create an application
  3. Enter the Application's name.
  4. Click on Bot on the left side settings menu.
  5. Click Add Bot and confirm with Yes, do it!

Client ID

Your Client ID is the same as the User ID of your Bot. You will need this when creating an invite URL.

You can find your Client ID located on the General Information settings page of your Application, under the Name field.

Your Client ID is not a secret, and does not need to be kept private.

Bot Token

Your Bot Token is the token that authorises your Bot account with the API. Think of it like your Bot's API access key. With your token, you can interact with any part of the API that's available to bots.

You can find your Bot Token located on the Bot settings page of your Application, under the Username field. You can click the Copy button to copy it without revealing it manually.

Your Bot Token is a secret, and must be kept private.
If you leak your token anywhere other people has access to see it, no matter the duration, you should reset your Bot Token.

To reset your token, go to the Bot settings page of your Application, and click the Regenerate button.
Be sure to update the token you're using for your bot script to this new one, as the old one will not work anymore.

Permissions Integer

Discord Permissions are typically represented by a Permissions Integer which represents all the Permissions that have been allowed.

You can find a reference to all the available Discord Permissions, their bitwise values and their descriptions here:
https://discordapp.com/developers/docs/topics/permissions#permissions-bitwise-permission-flags

If you want to create your own Permissions Integer, you can generate it in the Bot settings page of your Application, located at the bottom of the page.

Tick the permissions you want to be allowing, and it'll update the Permissions Integer field, which you can use in your Bot Invite URL to set your bot's default permissions when users go to invite it.

Bot Invite URL

Bot's cannot use a server invite link. Instead, they have to be invited by a member with the Manage Server permission.

The Bot Invite URL is formatted like:
https://discordapp.com/oauth2/authorize?client_id={CLIENT_ID}&scope=bot&permissions={PERMISSIONS_INTEGER}

You can create the Invite URL for your bot by replacing:
{CLIENT_ID} with your Client ID
{PERMISSIONS_INTEGER} with the Permissions Integer

You can also generate it with the Permissions Calculator tool.

Using the Basic Client (discord.Client)

Below is the essential resources to read over to get familiar with the basics functionality of discord.py.

Using the Commands Extension (commands.Bot)

The Commands Extension has a explanatory documentation walking you through not only what it is and it's basic usage, but also more advanced concepts. Be sure to read the prose documentation in full at:
https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html

It fully covers:

  • How to create bot using the Commands Extension
  • How to define commands and their arguments
  • What the Context object is
  • Argument Converters
  • Error Handling basics
  • Command checks

You will also need to reference the following resources:

FAQ

The documentation covers some basic FAQ's, and they are recommended to be read beforehand, and referenced before asking for help in case it covers your issue: https://discordpy.readthedocs.io/en/latest/faq.html

Examples

Official Examples and Resources

The official examples can be found on the source repository.

The most commonly referenced examples would be:

Permissions Documentation

Community Examples and Resources

The discord.py developer community over time have shared examples and references with each other.
The following are a collated list of the most referenced community examples.

Extensions / Cogs

Error Handling

Embeds

Using Local Images in Embeds
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)
Embed Limits
Element Characters
Title 256
Field Name 256
Field Value 1024
Description 2048
Footer 2048
Entire Embed 6000
Element Count
Fields 25

Emoji

Activity Presence

Image Processing

Voice

Databases

Systemd Service

botname.service

[Unit]
Description=My Bot Name
After=network-online.target

[Service]
Type=simple
WorkingDirectory=/your/bots/directory
ExecStart=/usr/bin/python3 /your/bots/directory/file.py
User=username
Restart=on-failure

[Install]
WantedBy=network-online.target

Directory
/usr/local/lib/systemd/system

Service Commands
Refresh systemd after unit file changes:
systemctl daemon-reload
Set service to start on boot:
systemctl enable botname
Start service now:
systemctl botname start
Stop service:
systemctl botname stop

Viewing Logs
All logs:
journalctl -u botname
Recent logs and continue printing new logs live: journalctl -fu mybot

@fleesu
Copy link

fleesu commented Mar 19, 2019

The ”Using local images in embeds example”’s link has expired!

@scragly
Copy link
Author

scragly commented Mar 21, 2019

Thanks @flxtcha, I've moved the example to within the content itself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment