这是我第一次创建不和谐机器人,我遇到了一个问题,我缺少位置参数“ctx”,但它在函数中。
我不太确定为什么会发生/不起作用。任何帮助表示赞赏! (我尝试在不和谐聊天中执行以下命令:“$hello”)
代码:
import discord
import os
from dotenv import load_dotenv
from discord.ext import commands
import logging
class DiscordBot:
def __init__(self) -> None:
self.intents = discord.Intents.all()
self.intents.messages = True
self.intents.message_content = True
self.intents.guilds = True
self.intents.members = True
self.intents.presences = True
self.bot = commands.Bot(command_prefix='$', intents=self.intents)
async def on_ready(self):
print("Bot is ready.")
@commands.command()
async def hello(self, ctx):
await ctx.channel.send('Hello bitch')
print("HELLO!")
if __name__ == '__main__':
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN_KEY')
logging.basicConfig(level=logging.DEBUG)
bot = DiscordBot()
bot.bot.add_command(bot.hello)
bot.bot.run(TOKEN)
输出:
ERROR:discord.ext.commands.bot:Ignoring exception in command hello
Traceback (most recent call last):
File "/home/dimo/programming/discord-bot/mybot-env/lib/python3.12/site-packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
TypeError: DiscordBot.hello() missing 1 required positional argument: 'ctx'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/dimo/programming/discord-bot/mybot-env/lib/python3.12/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/dimo/programming/discord-bot/mybot-env/lib/python3.12/site-packages/discord/ext/commands/core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/dimo/programming/discord-bot/mybot-env/lib/python3.12/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: DiscordBot.hello() missing 1 required positional argument: 'ctx'
范围已关闭。您正在添加命令,但它有
self
,因为它在类中。当你使用装饰器时,你不能有 self
,因为这样第一个位置参数将是类本身而不是 ctx
。
以下(我测试过)有效:
@commands.command()
async def hello(ctx):
await ctx.channel.send('Hello')
print("HELLO!")
class DiscordBot:
def __init__(self) -> None:
self.intents = discord.Intents.all()
self.intents.messages = True
self.intents.message_content = True
self.intents.guilds = True
self.intents.members = True
self.intents.presences = True
self.bot = commands.Bot(command_prefix='$', intents=self.intents)
self.bot.add_command(hello)
另外,如果
self.intents = discord.Intents.all()
无论如何都启用了它们,为什么还要启用一堆意图?