How to fix error: module 'discord' has no attribute 'Bot'

How to fix error: module 'discord' has no attribute 'Bot'

情况:

我正在尝试使用 pycord 制作一个简单的 discord 机器人,但每次我 运行 代码都会出现此错误:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'

代码:

import discord

bot = discord.Bot()

@bot.slash_command()
async def test(ctx):
  await ctx.send('Success!')

bot.run('token')

我做了什么:

我已经检查过我是否安装了 pycord 以及我的令牌是否正确。

查看您的错误消息时:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'

关键是要注意AttributeError是告诉你你导入的模块没有属性Bot()

这说明你用错了

看看documentation for the correct usage and also at this tutorial

你会看到你需要使用


# bot.py
import os

import discord
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

client.run(TOKEN)

在@Taku评论后编辑

在下面的评论之后,我相信可能需要像 example

中那样升级库

以及要求在 example in the url

中完成的命令前缀
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix=">")

@bot.command()
async def ping(ctx):
    await ctx.send("pong")

bot.run("token")

出现这个错误的原因是你的pycord版本是v1.7.3,不支持你使用的语法。您需要使用这些命令升级到 v2.0.0(Windows):

git clone https://github.com/Pycord-Development/pycord
cd pycord
pip install -U . 

pip install -U .[voice]如果您需要语音支持

PyCord 2 beta 1 刚刚发布,因此您现在可以使用

安装它
pip install py-cord==2.0.0b1

而不是从源安装版本。

为了让示例正常工作,您需要将 applications.commands 作用域添加到您的 OAuth2 URL 并且 re-register 您的机器人与您的测试服务器。

此外,quickstart guide 现在建议在创建 slash_command 时添加公会(服务器)ID 列表:

The guild_ids attribute contains a list of guilds where this command will be active. If you omit it, the command will be globally available, and may take up to an hour to register.