Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14389

Cogs in discord.py

$
0
0

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 discordfrom discord.ext import commandsintents = discord.Intents.default()intents.message_content = Truebot = 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.eventasync def on_ready():    print('We have logged in as {0.user}'.format(bot))@bot.eventasync 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 discordfrom discord.ext import commandsclass 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 messageI've tried making it await bot.load_extension(f'cogs.{cog.lower()}') But it just throws another error at me:error message 2I 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 tracebackping cog loaded.2024-03-26 10:47:57 INFO     discord.client logging in using static token2024-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' expressionThe 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 ediscord.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


Viewing all articles
Browse latest Browse all 14389

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>