Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Master326486/6cf48c1ca0509b98e673451e356ba625 to your computer and use it in GitHub Desktop.
Save Master326486/6cf48c1ca0509b98e673451e356ba625 to your computer and use it in GitHub Desktop.

Breaking Changes for discord.py 2.0


Upon resumation of the most popular discord API wrapper library for python, discord.py, while catching on to the latest features of the discord API, there have been numerous changes with addition of features to the library. Some additions to the library are -> Buttons support, Select Menus Support, Forms (AKA Modals), Slash Commands (AKA Application Commands) and a bunch of more handy features! All the changes can be found here. Original discord.py gist regarding resumation can be found here.


Requirements


First of all, you should have some fundamental understanding of Python:

  • Basic knowledge of variables, data types, keywords and some commonly used in-built functions in Python
  • String methods, List methods, Dictionary methods, Set methods
  • Familiar with asynchronous programming within Python. [Use case of keywords such as async and await and the library asyncio]
  • Have familiarity with Object Oriented Programming within Python
  • An understanding of indentation
  • Know scopes of variables, et cetera
  • Importing of libraries and local files into each other
  • Type Hinting of variables and parameters!

Steps to Get Started


  1. Get Python 3.8 or higher

Make sure you have python version of 3.8 or higher. discord.py requires Python of version 3.8 or higher. You can download it over here.

NOTE: Don't forget to click add to path check box when installing Python. This will definitely save you from some common issues if you are a beginner.

  • Install Python
  • Add it to PATH!
  1. Update your discord.py

The latest discord.py was released on pypi on August 18th 2022. BEFORE MIGRATING TO DISCORD.PY 2.0, PLEASE READ THE CONSEQUENCES OF THE UPDATE HERE. Since there are many breaking changes which may break your existing bot's code.

pip install -U discord.py  # or pip install discord.py 

Major changes we will be covering in this gist



In discord.py 2.0 intents is now a required keyword argument

Intents are certain gateway features that are necessary to run your bot. You can include them by passing a discord.Intents object inside the intents kwarg.

Example:

# Simple Bot creation
intents = discord.Intents.default()
intents.members = True
intents.message_content = True

bot = commands.Bot(command_prefix=["!", "?"], intents=intents)

# Advanced Bot creation
class MyCoolBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True
        
        super().__init__(
            command_prefix=["!", "?"],
            description="My Cool Bot!!!",
            intents=intents,
        )    

NOTE: Don't forget to enable them on the Developer Portal!

Choose your application -> Bot -> Privileged Gateway Intents

ScreenShot



In discord.py 2.0 .load_extension, .unload_extension, .add_cog and .remove_cog Bot methods are now asynchronous

Where do I load my cogs now?

See next paragraph for that information.



discord.py 2.0 has introduced a new Client method - setup_hook. This method is called after login but before connecting to the discord gateway.

Example of using setup_hook to load cogs and create an aiohttp session:

File: bot.py

import asyncio
import aiohttp
import discord
from discord.ext import commands

myCoolCogs = (
    'cogs.mod',
    'cogs.cool',
)


class MyCoolBot(commands.Bot):
    session: aiohttp.ClientSession

    def __init__(self):
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True

        super().__init__(
            command_prefix=["!", "?"],
            description="My Cool Bot!!!",
            intents=intents,
        )

    # This is asynchronous!
    async def setup_hook(self):
        # Creating aiohttp ClientSession
        self.session = aiohttp.ClientSession()

        # Loading cogs
        for cog in myCoolCogs:
            await self.load_extension(cog)

    async def start(self):
        await super().start("my cool token")
        
    async def close(self):
        await super().close()
        # Closing the aiohttp session that we opened
        await self.session.close()


async def main():
    bot = MyCoolBot()
    await bot.start()

asyncio.run(main())

Files: cogs/mod.py, cogs/cool.py

from discord.ext import commands


class MyCoolCog(commands.Cog):
    ...


# This is asynchronous!
async def setup(bot):
    await bot.add_cog(MyCoolCog(bot))

Do not sync your slash commands in on_ready or setup_hook! THAT IS BAD!

You only need to sync them when:

  • Added/removed a command
  • Changed a command's...
    • name (name= kwarg or function name)
    • description (description = kwarg or docstring)
  • Added/removed an argument
  • Changed an argument's...
    • name (rename decorator)
    • description (describe decorator)
    • type (arg: str is the type here)
  • Added/modified permissions:
    • guild_only decorator or kwarg
    • default_permissions decorator or kwarg
    • nsfw kwarg
  • Converted the global/guild command to a guild/global command Where should I sync instead?

Where should I sync instead

It's better to sync using a normal (message) command (or even an on_message if you prefer Client) You can even use just a simple eval to do so. Or you can use Jishaku sync command.

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