简体   繁体   中英

How can I import a cog into my main.py file?

My cog file isn't sending any errors but does not work. A friend of mine suggested importing the cog to my main file. I previously checked on Stackoverflow on how to import it but the method along the line of import (file name here, without extension) doesn't exactly work. I am using the Pycord library by the way.

import discord
from discord.ext import commands
from datetime import datetime


class Secondary(commands.Cog):
  def __init__(self, client):
    
    self.client = client

  @commands.slash_command()
  async def cog_test(self, ctx):
    await ctx.respond("Working.", ephemeral = False)
      
def setup(client):
  client.add_cog(Secondary(client))

The code in the cog is as above, it's just a little thing I did to test the cog.

If you want to import your cog into your discord bot, you have to use the bot.load_extension() method which takes the file in parameter:

At the end of your main file:

my_files = ["YOUR FILES HERE WITHOUT EXTENSION"]
#For example, if my files are cog1.py and cog2.py and is located in the cogs folder:
my_files = ["cog1", "cog2"]

for file in my_files:
    bot.load_extension(f"cogs.{file}")

Don't forget to put the setup function in your cog file

See https://docs.pycord.dev/en/master/api.html?highlight=load_extension#discord.Bot.load_extension

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM