py:如何在不使用Cogs的情况下在OOP中编写Discord bot?我试的时候出错了

2024-09-27 19:13:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在discord机器人上工作了相当长的时间,现在我决定是时候开始使用带有OOP的机器人了,因为我正在进入它。我给了它一个简单的尝试,并试图运行它,但它显示了一些错误,我不明白

当我使用以下代码时:

import discord
from discord.ext import commands

class JervisI(commands.Bot):
    def __init__(self, command_prefix, case_insensitive, botintents):
        self.command_prefix = command_prefix
        self.case_insensitive = case_insensitive
        self.botintents = botintents


J1 = JervisI(command_prefix="!", case_insensitive=True, botintents=discord.Intents.all())
J1.run("---HIDDEN TOKEN---")

运行代码时,出现以下错误:

Traceback (most recent call last):
  File "c:\Users\Bhavyadeep\Desktop\Discord Bot (Python)\PHub-Bot-1\jervis-1.py", line 12, in <module>
    J1.run("---HIDDEN TOKEN---")
  File "c:\Users\Bhavyadeep\Desktop\Discord Bot (Python)\PHub-Bot-1\The-Naval-Historian\lib\site-packages\discord\client.py", line 692, in run
    loop = self.loop
AttributeError: 'JervisI' object has no attribute 'loop'

我不知道怎么做。请务必让我知道错误在哪里

谢谢D


Tags: run代码selfloopprefixbot错误机器人
1条回答
网友
1楼 · 发布于 2024-09-27 19:13:36

你正在覆盖commands.Bot__init__方法,如果你看一下source code你会发现它很长很重要,如果你不调用“原始的”__init__方法,你会得到大量的AttributeError

class JervisI(commands.Bot):
    def __init__(self, command_prefix, case_insensitive, botintents):
        super().__init__( # Same arguments that you pass to `commands.Bot(...)`
            command_prefix=command_prefix, 
            case_insensitive=case_insensitive,
            intents=botintents
        )

        self.command_prefix = command_prefix # You don't need to create this, it already exists
        self.case_insensitive = case_insensitive
        self.botintents = botintents

相关问题 更多 >

    热门问题