AttributeError:“成员”对象没有属性“客户端”

2024-03-29 07:57:15 发布

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

我是discord.py的新用户,我面临一个简单代码的问题:

from dotenv import load_dotenv

import discord
from discord.ext.commands import Bot
import os

load_dotenv()


class Bothoven:
    def __init__(self):
        self.version = 0.1
        self.client = discord.Client()
        self.bot = Bot(command_prefix='$')

        @self.bot.event
        async def on_ready():
            print('We have logged in as {0.user}'.format(self.bot))

        @self.bot.command()
        async def test(ctx):
            print(ctx)
            await ctx.send("oui maitre")

        self.bot.run(os.getenv("BOT_TOKEN"))

当我运行它时,一切看起来都很好,机器人打印:

We have logged in as Bothoven#9179

但当我在公会中键入某个内容时,会出现一个例外:

Ignoring exception in on_message
Traceback (most recent call last):
  File "D:\PROJETS\Bothoven\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\PROJETS\Bothoven\venv\lib\site-packages\discord\ext\commands\bot.py", line 942, in on_message
    await self.process_commands(message)
  File "D:\PROJETS\Bothoven\venv\lib\site-packages\discord\ext\commands\bot.py", line 935, in process_commands
    if message.author.client:
AttributeError: 'Member' object has no attribute 'client'

我理解这个错误,并且我同意作者没有属性client,但是这个语句在bot.py库文件中

你知道怎么做吗

我正在运行python3.8和discord.py1.6

编辑

尽管pip告诉我所有软件包都是最新的,但删除我的venv并重建它解决了我的问题


Tags: inpyimportselfclientmessagevenvon
1条回答
网友
1楼 · 发布于 2024-03-29 07:57:15

您的Cog设置有一些问题:

  • 您必须使用commands.Cog.listener()来利用事件
  • 要创建命令,请使用commands.command()装饰器
  • 您的self.bot定义错误,不需要self.client

以下是正确设置cog的方法:

from os import environ
from discord.ext import commands 

bot = commands.Bot(command_prefix='$')

class Bothoven(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready():
        print('Logged in as {0.user}'.format(self.bot))

    @commands.command()
    async def test(ctx):
        print(ctx)
        await ctx.send("Oui maître")

bot.add_cog(Bothoven(bot))
bot.run(environ["BOT_TOKEN"])

您可以找到有关cogshere的更多信息

编辑:原来这是一个venv问题,重新构建它解决了问题

相关问题 更多 >