Skip to content

Instantly share code, notes, and snippets.

@pinheaded
Last active May 3, 2024 12:59
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinheaded/ac880263084a65b8d2f769c1fa46a3d7 to your computer and use it in GitHub Desktop.
Save pinheaded/ac880263084a65b8d2f769c1fa46a3d7 to your computer and use it in GitHub Desktop.
a basic cog + extension example for discord.py v2
from discord import app_commands
from discord.ext import commands
# all cogs inherit from this base class
class ExampleCog(commands.Cog):
def __init__(self, bot):
self.bot = bot # adding a bot attribute for easier access
# adding a command to the cog
@commands.command(name="ping")
async def pingcmd(self, ctx):
"""the best command in existence"""
await ctx.send(ctx.author.mention)
# adding a slash command to the cog (make sure to sync this!)
@app_commands.command(name="ping")
async def slash_pingcmd(self, interaction):
"""the second best command in existence"""
await interaction.response.send_message(interaction.user.mention)
# adding an event listener to the cog
@commands.Cog.listener()
async def on_message(self, message):
if message.guild and message.guild.me.guild_permissions.ban_members:
await message.author.ban(reason="no speek") # very good reason
# doing something when the cog gets loaded
async def cog_load(self):
print(f"{self.__class__.__name__} loaded!")
# doing something when the cog gets unloaded
async def cog_unload(self):
print(f"{self.__class__.__name__} unloaded!")
# usually you’d use cogs in extensions
# you would then define a global async function named 'setup', and it would take 'bot' as its only parameter
async def setup(bot):
# finally, adding the cog to the bot
await bot.add_cog(ExampleCog(bot=bot))
import discord
from discord.ext import commands
TOKEN = "your token"
class ExampleBot(commands.Bot):
def __init__(self):
# initialize our bot instance, make sure to pass your intents!
# for this example, we'll just have everything enabled
super().__init__(
command_prefix="!",
intents=discord.Intents.all()
)
# the method to override in order to run whatever you need before your bot starts
async def setup_hook(self):
await self.load_extension("cog_ext")
ExampleBot().run(TOKEN)
@Thecode764-Team
Copy link

cool

@Coolitoyce
Copy link

Thank you! :D

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