尝试用python制作一个不和聊天机器人.当我尝试添加齿轮时,我遇到了一些问题



我一直在尝试制作一个不和谐机器人,直到我开始使用齿轮。

有3个外部文件:fun.py, misc.py和mod.py,其中包含应该通过以下方式加载的命令:

bot.load_extension(cog) 

每个文件的末尾都有以下功能:

async def setup(bot):
await bot.add_cog(CogName(bot))

这是我的bot代码:

import json
import json
import os
import random
import sys
import discord
from discord.ext import commands, tasks
from discord.ext.commands import Context
intents = discord.Intents.all()
if not os.path.isfile("config.json"):
sys.exit("'config.json' not found! Please add it and try again.")
else:
with open("config.json") as file:
config = json.load(file)
@tasks.loop(minutes=1.0)
async def status_task() -> None:
"""
Setup the game status task of the bot
"""
statuses = ["Made by Samxel!", "M O O N", ":D"]
await bot.change_presence(activity=discord.Game(random.choice(statuses)))

bot = commands.Bot(command_prefix=commands.when_mentioned_or(
config["prefix"]), intents=intents, help_command=None)
cogs = ['cogs.fun', 'cogs.mod', 'cogs.misc'] # 'cogs' signifies the name of the folder, 'x' signifies the file name.

@bot.event
async def on_ready():
print(f'Logged in as: {bot.user.name}')
print(f'With ID: {bot.user.id}')
for cog in cogs: # Looks for the cogs,
await bot.load_extension(cog)  # Loads the cogs.
return

@bot.event
async def on_command_error(context: Context, error) -> None:
if isinstance(error, commands.CommandOnCooldown):
minutes, seconds = divmod(error.retry_after, 60)
hours, minutes = divmod(minutes, 60)
hours = hours % 24
embed = discord.Embed(
title="Hey, please slow down!",
description=f"You can use this command again in {f'{round(hours)} hours' if round(hours) > 0 else ''} {f'{round(minutes)} minutes' if round(minutes) > 0 else ''} {f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Error!",
description="You are missing the permission(s) `" + ", ".join(
error.missing_permissions) + "` to execute this command!",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.BotMissingPermissions):
embed = discord.Embed(
title="Error!",
description="I am missing the permission(s) `" + ", ".join(
error.missing_permissions) + "` to fully perform this command!",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title="Error!",
description=str(error).capitalize(),
color=0xE02B2B
)
await context.send(embed=embed)
raise error

bot.run(config["token"], reconnect=True)

我得到的错误信息是:

C:UserslistsPycharmProjectsMOONBOTvenvScriptspython.exe C:UserslistsPycharmProjectsMOONBOTTest.py 
2022-12-14 13:08:53 INFO     discord.client logging in using static token
2022-12-14 13:08:54 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 14a697b0d7cfc70b1666d995b6c92e78).
Logged in as: M O O N
With ID: 1052180600699748402
2022-12-14 13:08:56 ERROR    discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordextcommandsbot.py", line 934, in _load_from_module_spec
spec.loader.exec_module(lib)  # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:UserslistsPycharmProjectsMOONBOTcogsfun.py", line 8, in <module>
from Test import bot
File "C:UserslistsPycharmProjectsMOONBOTTest.py", line 84, in <module>
bot.run(config["token"], reconnect=True)
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordclient.py", line 828, in run
asyncio.run(runner())
File "C:UserslistsAppDataLocalProgramsPythonPython311Libasynciorunners.py", line 186, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordclient.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:UserslistsPycharmProjectsMOONBOTTest.py", line 41, in on_ready
await bot.load_extension(cog)  # Loads the cogs.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordextcommandsbot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordextcommandsbot.py", line 937, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: RuntimeError: asyncio.run() cannot be called from a running event loop
2022-12-14 13:08:56 ERROR    discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordextcommandsbot.py", line 934, in _load_from_module_spec
spec.loader.exec_module(lib)  # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:UserslistsPycharmProjectsMOONBOTcogsfun.py", line 8, in <module>
from Test import bot
File "C:UserslistsPycharmProjectsMOONBOTTest.py", line 84, in <module>
bot.run(config["token"], reconnect=True)
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordclient.py", line 828, in run
asyncio.run(runner())
File "C:UserslistsAppDataLocalProgramsPythonPython311Libasynciorunners.py", line 186, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordclient.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:UserslistsPycharmProjectsMOONBOTTest.py", line 41, in on_ready
await bot.load_extension(cog)  # Loads the cogs.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordextcommandsbot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordextcommandsbot.py", line 937, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: RuntimeError: asyncio.run() cannot be called from a running event loop
C:UserslistsPycharmProjectsMOONBOTvenvLibsite-packagesdiscordclient.py:414: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
await self.on_error(event_name, *args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

谢谢你的帮助!

我试过删除on_command_error bot事件,我也试过不同的方法来加载cog扩展…毫无效果。

尝试bot.load_extension(cog)没有等待

最新更新