开发Discord自定义机器人遇报错:module 'discord' has no attribute 'Intents'
解决discord.py报错AttributeError: module 'discord' has no attribute 'Intents'
问题根源
discord.Intents是discord.py从v1.5.0版本才开始支持的功能,版本低于这个就会触发该错误。另外也可能是你装错了包,或者Python环境混乱,导致调用的不是官方的discord.py模块。
具体解决步骤
1. 确认当前discord.py版本
你的代码里已经加了print(discord.__version__),运行后查看输出的版本号:
- 若版本低于1.5.0,必须升级到至少该版本(推荐安装最新稳定版)
- 版本符合要求的话,直接进行环境排查
2. 确保安装的是官方discord.py包
不少人会误装名为discord的第三方包(非官方discord.py),按以下命令清理后重装:
# 卸载错误的同名包 pip uninstall discord # 卸载已安装的discord.py(如有) pip uninstall discord.py # 安装官方最新稳定版 pip install discord.py
3. 检查Python环境是否对应
如果你的电脑有多个Python版本(比如Python2和3,或多个虚拟环境),大概率你安装的discord.py不在当前运行代码的环境中:
- 运行代码时明确指定Python版本,比如用
python3代替python:python3 你的机器人代码文件名.py - 用虚拟环境隔离依赖更稳妥:
# 创建虚拟环境(Python3) python3 -m venv bot-env # Windows激活虚拟环境 bot-env\Scripts\activate # Linux/macOS激活虚拟环境 source bot-env/bin/activate # 在虚拟环境中安装discord.py pip install discord.py # 运行代码 python 你的机器人代码文件名.py
4. 不要急着重装Python
重装Python是最后才考虑的操作,上面的步骤基本能解决问题。真走到这一步的话,安装时记得勾选"Add Python to PATH"选项,避免环境变量异常。
补充:正确的Intents代码示例
版本没问题的话,你的代码写法是正确的,这里提供一个更清晰的示例(可按需开启权限,无需全选):
import discord from discord.ext import commands # 打印版本确认 print(f"discord.py版本: {discord.__version__}") # 初始化全权限Intents intents = discord.Intents.all() # 也可只开启需要的权限,比如消息内容和成员权限: # intents.message_content = True # intents.members = True client = commands.Bot(command_prefix=".", intents=intents) @client.event async def on_ready(): print(f"{client.user.name} 已准备就绪") client.run("你的机器人令牌")
内容的提问来源于stack exchange,提问作者diabetico
相关产品推荐
相关产品推荐

