Lennox Mann
Lennox Mann

Reputation: 9

I dont know how to import a Cog funtion into my main.py for my discord bot

I'm trying to make a Discord bot that will enable me to run a command from another file using cog, yet it seems to have problems when i try to add my Cog to my main.py file.

Here is the code I have for my main.py:

import discord
import os
import asyncio
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith(".py"):
            cog_name = filename[:-3]  # Remove the '.py' extension
            cog_path = f'cogs.{cog_name}'  # Construct the full path to the cog
            try:
                bot.load_extension(cog_path)
                print(f"Loaded extension: {cog_name}")
            except commands.ExtensionAlreadyLoaded:
                print(f"Extension {cog_name} is already loaded.")
            except commands.ExtensionNotFound:
                print(f"Extension {cog_name} not found.")


@bot.event
async def on_ready():
    await bot.change_presence(status=discord.Status.dnd, activity=discord.Game('Playing Call of Duty: Modern Warfare 3'))
    print("--------------------------------------------")
    print("Bot is ready")
    print("--------------------------------------------")

@bot.command()
async def hello(ctx):
    await ctx.send(f"Hello there, {ctx.author.mention}!")



my_files = ["ban"]

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

with open("token.txt") as file:
    token = file.read()
    
bot.run(token)

and here is the code for my command i want it to be able to run (its a ban command):

import discord
from discord.ext import commands

class Ban(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        await member.ban(reason=reason)
        await ctx.send(f"{member} has been banned!")

def setup(bot):
    bot.add_cog(Ban(bot))

Each time i run it it always give me following error message:

2024-05-08 10:53:31 ERROR    discord.ext.commands.bot Ignoring exception in command ban
Traceback (most recent call last):
  File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/DEATH-TO-THE-MPLA/main.py", line 35, in ban
    await ctx.invoke(bot.get_command('ban'), ctx, member, reason=reason)  # Invoke the ban command defined in the Ban cog
  File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/context.py", line 336, in invoke
    return await command(self, *args, **kwargs)
  File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 590, in __call__
    return await self.callback(context, *args, **kwargs)  # type: ignore
TypeError: ban() takes 2 positional arguments but 3 positional arguments (and 1 keyword-only argument) were given

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/DEATH-TO-THE-MPLA/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: ban() takes 2 positional arguments but 3 positional arguments (and 1 keyword-only argument) were given

If anyone could help me out id appreciate it

I've tried using a different post on here: How can I import a cog into my main.py file? to resolve this matter but when i used it, all it did was cause following error:

/home/runner/DEATH-TO-THE-MPLA/main.py:38: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension(f"cogs.ban")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-05-08 11:00:53 INFO     discord.client logging in using static token
2024-05-08 11:00:54 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 46f7aa5cd5816a4b67bec47342e1e375).
--------------------------------------------
Bot is ready
--------------------------------------------

The bot itself ran, but the command didn't work.

Upvotes: 0

Views: 61

Answers (2)

Rafael
Rafael

Reputation: 574

The logs mention

  File "/home/runner/DEATH-TO-THE-MPLA/main.py", line 35, in ban
    await ctx.invoke(bot.get_command('ban'), ctx, member, reason=reason)  # Invoke the ban command defined in the Ban cog

In ctx.invoke(bot.get_command('ban'), ctx, member, reason=reason) you are effectively providing ctx twice. Try ctx.invoke(bot.get_command('ban'), member, reason=reason)

This part of the code is not not included in the code you shared with us. If you still encounter issues, please share all the relevant code.

Upvotes: 0

DZultra
DZultra

Reputation: 68

I have made a Music Bot in the past which also uses cogs, and I imported the cogs via asyncio like this:

import asyncio

from NAME_OF_YOUR_COG_FILE import NAME_OF_YOUR_CLASS_INSIDE_THE_COG

loop = asyncio.new_event_loop()
loop.run_until_complete(bot.add_cog(NAME_OF_YOUR_COG_FILE(bot)))

I hope I could help! If it doesn't don't hesitate to contact me!

Upvotes: -1

Related Questions