Cogs in discord.py

51 Views Asked by At

So I've made a discord bot with a lot of commands (I'll show one only here to make it clearer), but the code is now really messy. I've always wanted to move the commands into a seperate folder names cogs with files in it. But it doesn't seem to work:

main.py:

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix = "m.", intents = intents)

token = "1234567890"

cogs = ["ping"]
for cog in cogs:
  try:
    bot.load_extension(f'cogs.{cog.lower()}')
    print(f'{cog} cog loaded.')
  except Exception as e:
    print(f'Failed to load {cog} cog: {e}')

@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    await bot.process_commands(message)
  
try:
  bot.run(token)
except discord.HTTPException as e:
    if e.status == 429:
        print("The Discord servers denied the connection for making too many requests")
        print("Get help from https://stackoverflow.com/questions/66724687/in-discord-py-how-to-solve-the-error-for-toomanyrequests")
    else:
        raise e

ping.py:

import discord
from discord.ext import commands

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

    @commands.command()
    async def ping(self, ctx):
        message = await ctx.send('Pong!')
        latency = self.bot.latency * 1000  # Convert to milliseconds
        await message.edit(content=f'Pong! **{latency:.2f} ms**')

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

But this is what it shows: error message I've tried making it await bot.load_extension(f'cogs.{cog.lower()}') But it just throws another error at me: error message 2 I am wondering wether I should put the await bot.load_extension(f'cogs.{cog.lower()}') into a async def function. But I don't know how to do that, and when I should call the function. Also, this is what is shown in the console:

/home/runner/Python-Discord-Bot/main.py:14: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension(f'cogs.{cog.lower()}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
ping cog loaded.
2024-03-26 10:47:57 INFO     discord.client logging in using static token
2024-03-26 10:47:58 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: xxxxxxxxxxxxxxxxxxxxxx).
We have logged in as xxx#9743

I've already looked at Cogs discord.py but the answers just either use bot.load_extension('maincog') or client.load_extension(f'cogs.{filename[:-3]}'), which doesn't help since it doesn't use await and isn't in a function. I've also looked at discord.py How i make cogs in discord.py? and tried out the solutions that Noob_Coder_GALAXY gave, but then, it throws me this error:

Traceback (most recent call last):
  File "/home/runner/Python-Discord-Bot/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 947, in _load_from_module_spec
    await setup(self)
TypeError: object NoneType can't be used in 'await' expression

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

Traceback (most recent call last):
  File "/home/runner/Python-Discord-Bot/.pythonlibs/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/Python-Discord-Bot/main.py", line 20, in on_ready
    await preload()
  File "/home/runner/Python-Discord-Bot/main.py", line 16, in preload
    await bot.load_extension(f"cogs.{file[:-3]}")
  File "/home/runner/Python-Discord-Bot/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "/home/runner/Python-Discord-Bot/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 952, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ping' raised an error: TypeError: object NoneType can't be used in 'await' expression

I've already made sure that the ping.py in in the folder cogs and everything, so now the only problem is the code. Thanks for any help

0

There are 0 best solutions below