我正在尝试制作一个 Discord 机器人,它将使我能够使用 cog 从另一个文件运行命令,但当我尝试将我的 Cog 添加到我的 main.py 文件时,它似乎出现问题。
这是我的 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)
这是我的命令的代码,我希望它能够运行(它是一个禁止命令):
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))
每次运行它时,它总是给我以下错误消息:
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
如果有人可以帮助我,我会很感激
我尝试在这里使用不同的帖子:如何将齿轮导入到我的 main.py 文件中?来解决这个问题,但是当我使用它时,它所做的只是导致以下错误:
/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
--------------------------------------------
机器人本身运行了,但命令不起作用。
日志提到
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
在
ctx.invoke(bot.get_command('ban'), ctx, member, reason=reason)
中,您有效地提供了 ctx
两次。试试ctx.invoke(bot.get_command('ban'), member, reason=reason)
这部分代码并未包含在您与我们分享的代码中。如果您仍然遇到问题,请分享所有相关代码。
我过去制作了一个音乐机器人,它也使用齿轮,我通过 asyncio 导入齿轮,如下所示:
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)))
希望我能帮上忙!如果没有的话请联系我!