discord.py 中的齿轮

问题描述 投票:0回答:1

所以我制作了一个带有很多命令的discord bot(我只会在这里显示一个命令以使其更清楚),但代码现在非常混乱。我一直想将命令移动到一个名为 cogs 的单独文件夹中,其中包含文件。但似乎不起作用:

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))

但这就是它所显示的: error message 我尝试过制作它

await bot.load_extension(f'cogs.{cog.lower()}')
但它只是向我抛出了另一个错误: error message 2 我想知道是否应该将
await bot.load_extension(f'cogs.{cog.lower()}')
放入
async def
函数中。但我不知道该怎么做,也不知道何时应该调用该函数。 另外,这是控制台中显示的内容:

/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

我已经看过 Cogs discord.py 但答案只是使用

bot.load_extension('maincog')
client.load_extension(f'cogs.{filename[:-3]}')
,这没有帮助,因为它不使用等待并且不在函数中。 我还查看了 discord.py How i make cogs in discord.py? 并尝试了 Noob_Coder_GALAXY 给出的解决方案,但是随后,它向我抛出了这个错误:

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

我已经确定了文件夹

ping.py
中的
cogs
以及所有内容,所以现在唯一的问题是代码。感谢您的帮助

python discord discord.py discogs-api
1个回答
0
投票

所以基本上,在你的齿轮中,你可以保持一切相同,但在

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 = "your-bot-token"

cogs = ["ping"]
async def load_cogs():
    for cog in cogs:
        try:
            await 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():
    await load_cogs()
    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

您在这里所做的是将 load_extension 函数放入名为 load_cogs 的函数中,然后在 on_ready 中调用它。我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.