Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

discord.py - Are Cogs supposed to be in the same code?

I have seen a lot of things about cogs but I never understood if the cogs are supposed to be in the same code or in a different file. If it is in a different file, how do I load it in to main code file? I asked this question a lot of times and got millions of different answers. One answer which is supposed to work was bot.load_extension('name') but I have no idea what to substitute 'name' for. I tried writing the name of the cog file and the name of the cog, but PyCharm did accept it.

question from:https://stackoverflow.com/questions/65560238/are-cogs-supposed-to-be-in-the-same-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I m new to discord.py too but here i m sharing my little knowledge! [Sorry if i have some problems in my vocab!]

Cogs are like subclasses that helps you to organise your code and distribute your code in different sections, but still having a single bot and not to have a very long long code with different types of commands in a single file. More Info At: Discord.py Documentation For Cogs

  1. Create a folder named cogs in directory same as of your bot.py

  2. To load and unload cogs using command you can use this code:

import discord
from discord.ext import commands
import os

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')

This will load cogs whenever you make one.

  1. Create a cog example [example.py] in cogs folder.
  2. You need to define class cog at beginning of every cog and define cog setup at end of every cog as such:
import discord

class Example(commands.Cog): #Here Example is name of cog example.py

    def __init__(self, client):
        self.client = client


#Your code 
#Your code
#Your code


def setup(client):
    client.add_cog(Example(client)) #Here Example is name of cog example.py

Just Use load command once if it doesnt load at first. Cogs will automatically load as soon as you restart bot or you can simply unload and load them by using load [cogname] and unload [cogname] command.

  • @client.event changes to @commands.Cog.listener decorator
  • @client.commands changes to @commands.command decorator

Please Forgive Me For Any Mistakes And Mislead ^^!

Credits : A Simple Tutorial By Lucas On Youtube!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...