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

Discord Bot报错NameError: name 'intents' is not defined 求助

问题解决:Discord Bot 中的 NameError 及参数错误

错误原因拆解

  • intents变量未定义:代码里直接引用了intents,但从未声明或赋值这个变量。
  • 参数名拼写错误:commands.Bot的参数是复数形式intents,不是单数intent。
  • prefix变量未定义:代码里用了prefix,但实际应该从配置文件的config['prefix']取值。
  • 文件资源未妥善处理:直接open()文件后未关闭,容易引发资源泄漏问题。

修正后的完整代码

import discord
import json
from discord.ext import commands

# 用with语句安全读取配置,自动处理文件关闭
with open("config.json", "r") as file:
    config = json.load(file)

# 先初始化intents变量
intents = discord.Intents.default()
# 若Bot需要读取消息内容(比如处理带参数的命令),需开启此权限,同时在Discord开发者后台开启对应特权
# intents.message_content = True

# 正确初始化Bot实例
bot = commands.Bot(command_prefix=config['prefix'], intents=intents)

@bot.command(name="ping")
async def ping(ctx):
    await ctx.send(f"{ctx.author.mention} pong!")

bot.run(config['token'])

关键修正说明

  1. 用with open()读取配置文件,无需手动关闭文件,避免资源泄漏。
  2. 提前声明intents变量并赋值为discord.Intents.default(),再传入Bot的构造参数(注意参数名是复数intents)。
  3. 从config字典中正确获取前缀config['prefix'],替换原来未定义的prefix变量。
  4. 如果你的Bot需要处理消息内容,必须在Discord开发者平台的Bot设置里开启消息内容特权,同时在代码中添加intents.message_content = True。

内容的提问来源于stack exchange,提问作者Саш ОК

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:10:27