我正在try 制作一个discord机器人,但标题中出现了错误.这是我的代码:

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

为什么会发生这种情况?如何解决它?

推荐答案

The basic problem

范围已关闭.您正在添加命令,但它有self,因为它在类中.当您使用decorator 时,您不能有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)

Also, why do you have a bunch of intents enabled if 100 enables them anyway?

More in depth

如果我们要在decorator 中打印函数的参数,请使用以下代码:

    # Cut off for space, but it's inside the class for Bot you had previously
    @commands.command()
    async def hello(self, ctx):
        await ctx.channel.send('Hello')
        print("HELLO!")


@commands.command()
async def Testing(ctx):
    await ctx.channel.send('Hello')
    print("HELLO!")

如果我们要编辑decorator 的源代码以打印以下内容:

    def decorator(func):
        if isinstance(func, Command):
            raise TypeError('Callback is already a command.')
        print(func.__code__.co_varnames)
        print(func.__name__)
        return cls(func, name=name, **attrs)

它会返回:

('self', 'ctx')
hello
('ctx',)
Testing

self就是问题的根源.

Python相关问答推荐

Asyncio与队列的多处理通信-仅运行一个协程

将词典写入Excel

收件箱转换错误- polars.exceptions. ComputeHelp- pandera(0.19.0b3)带有polars

如何终止带有队列的Python进程?+ 队列大小的错误?

请从Python访问kivy子部件的功能需要帮助

ambda将时间戳与组内另一列的所有时间戳进行比较

实现的差异取决于计算出的表达是直接返回还是首先存储在变量中然后返回

如何使用Google Gemini API为单个提示生成多个响应?

如果条件为真,则Groupby.mean()

比较两个数据帧并并排附加结果(获取性能警告)

根据不同列的值在收件箱中移动数据

try 在树叶 map 上应用覆盖磁贴

为什么符号没有按顺序添加?

用NumPy优化a[i] = a[i-1]*b[i] + c[i]的迭代计算

如何使用Python以编程方式判断和检索Angular网站的动态内容?

如何在UserSerializer中添加显式字段?

joblib:无法从父目录的另一个子文件夹加载转储模型

用砂箱开发Web统计分析

如何启动下载并在不击中磁盘的情况下呈现响应?

python中csv. Dictreader. fieldname的类型是什么?'