Home > Software engineering >  Discord.py - How do I save commands in a different folder?
Discord.py - How do I save commands in a different folder?

Time:10-24

I'm trying to save my commands in a folder instead of in one file to keep things organized, but I don't know how to import the commands.

This is the main file:

import discord
from discord.ext import commands

client = commands.Bot(command_prefix=">")

@client.event
async def on_connect():
    print(f'Logged In As {client.user}')

client.run(token)

And this is a test command I made:

import discord
from discord.ext import commands

@client.command()
async def ping(ctx):
    delay = client.latency * 1000
    await ctx.reply(f'Ping is {int(delay)} Milliseconds')
    print(f"Pinged In {ctx.guild} -- {ctx.channel}")

The command is saved in a folder named "commands" in the same directory as main.py. How would I import the commands?

Sorry If The Question Is Hard To Understand, I Couldn't Find A Better Way To Put It

CodePudding user response:

You're looking for Cogs and Extensions.

Cogs will group commands together (possibly in separate files), extensions allow you to register commands in a different file. Don't import your commands in your main, that's very ugly.

Cogs docs (with examples): https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html

Extensions docs (with examples): https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html

Beware of online tutorials because chances are very high they will be outdated. Cogs & extensions were made asynchronous in discord.py v2.0, so none of the tutorials that are more than a few months old will work. The migration guide explains how to do it in 2.0: https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous

CodePudding user response:

The test command you made should use the command decorator function from discord.ext.commands module. That way the dependency on the client is removed until you can register the command to the bot.

import discord
from discord.ext import commands

@commands.command()
async def ping(ctx):
    delay = ctx.bot.latency * 1000
    await ctx.reply(f'Ping is {int(delay)} Milliseconds')
    print(f"Pinged In {ctx.guild} -- {ctx.channel}")

Then register the ping command above in your main module as follows:

import discord
from discord.ext import commands
from commands.ping import ping

client = commands.Bot(command_prefix=">")

@client.event
async def on_connect():
    print(f'Logged In As {client.user}')

client.add_command(ping)
client.run(token)
  • Related