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'])
关键修正说明
- 用
with open()读取配置文件,无需手动关闭文件,避免资源泄漏。 - 提前声明
intents变量并赋值为discord.Intents.default(),再传入Bot的构造参数(注意参数名是复数intents)。 - 从
config字典中正确获取前缀config['prefix'],替换原来未定义的prefix变量。 - 如果你的Bot需要处理消息内容,必须在Discord开发者平台的Bot设置里开启消息内容特权,同时在代码中添加
intents.message_content = True。
内容的提问来源于stack exchange,提问作者Саш ОК
相关产品推荐
相关产品推荐

