You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py开发遇AttributeError与ImportError问题求助

解决方案

错误1:AttributeError: 'Client' object has no attribute 'client'

你的代码冗余创建了两个discord.Client实例,且app_commands.CommandTree与基础Client配合时易出现实例不匹配问题。推荐使用discord.Bot(Client的子类,内置命令树支持)简化代码:

import discord
from discord import app_commands

intents = discord.Intents.default()
intents.message_content = True
# 仅创建一个Bot实例
bot = discord.Bot(intents=intents)
# 直接使用Bot自带的tree属性
tree = bot.tree

# 示例斜杠命令
@tree.command(name="hello", description="发送问候")
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message(f"你好 {interaction.user.mention}!")

bot.run("你的Bot令牌")

如果一定要用discord.Client,需保证全程使用同一个实例,并手动同步命令树:

import discord
from discord import app_commands

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

@tree.command(name="hello", description="发送问候")
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message(f"你好 {interaction.user.mention}!")

@client.event
async def on_ready():
    await tree.sync()
    print(f"已登录为 {client.user}")

client.run("你的Bot令牌")

错误2:ImportError: cannot import name 'app_commands' from 'discord'

该错误源于discord.py版本过低,app_commands是2.0及以上版本才新增的模块。执行以下命令升级:

pip install --upgrade discord.py

若环境中存在同名的discord包导致冲突,先卸载再升级:

pip uninstall discord
pip install --upgrade discord.py

内容的提问来源于stack exchange,提问作者Panxel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:50:24