运行Discord机器人报错:module 'discord' has no attribute 'bot' 求助
解决“module 'discord' has no attribute 'bot'”错误及Slash Command问题
错误原因分析
- 导入语句语法错误:
from discord.utils import get from discord.ext import tasks将两个导入合并在同一行,导致语法错误,进而影响模块正常加载。 - 变量名不统一:
on_ready事件中使用client.user,但你定义的机器人实例是bot = discord.Bot(),变量名不匹配。 - 语法遗漏:
print(f"WORKING AS {client.user}")缺少闭合括号,触发语法报错。 - 环境依赖冲突:代码内用
os.system("pip install py-cord")可能导致安装不彻底,或环境中同时存在discord.py与py-cord引发版本冲突。
修正后的完整代码
import discord import time import requests import datetime from discord.ext import commands from discord.utils import get from discord.ext import tasks from discord.ext.commands import Bot # 显式指定intents,py-cord 2.x版本必需 bot = discord.Bot(intents=discord.Intents.default()) @bot.event async def on_ready(): print(f"WORKING AS {bot.user}") print("Bot is online!") @bot.slash_command(description="Unlock the chat.") @commands.has_permissions(manage_channels = True) async def unlock(ctx): # 补充你的命令逻辑示例 await ctx.send("Chat unlocked successfully!") # 此处添加频道解锁的具体代码 # 替换为你的机器人令牌 bot.run("your_bot_token_here")
关键修复点
- 拆分错误的导入语句,每个
from...import单独成行。 - 统一变量名:将
client.user改为bot.user,与实例名保持一致。 - 补全
print语句的闭合括号,修正语法错误。 - 添加
intents参数:py-cord 2.x版本要求显式声明intents,否则机器人无法正常启动。 - 手动在终端安装指定版本py-cord:执行
pip install py-cord==2.4.1,避免代码内安装的环境冲突;若之前装过discord.py,先执行pip uninstall discord.py清除冲突依赖。 - 确保Slash Command函数包含
async关键字和上下文参数(如ctx),否则会触发“无slash_command属性”类的错误。
额外注意
前往Discord开发者门户,为你的机器人开启所需的intents(如服务器成员、消息内容等),否则部分功能会受限。
内容的提问来源于stack exchange,提问作者choppa
相关产品推荐
相关产品推荐

