discord.py警告指令启动时报“data is not defined”错误如何解决?
问题修复方案
错误原因
- 核心问题为代码缩进不符合Python语法规则:你写的
user_data = data[str(user.id)]及后续所有代码,缩进层级和async def test平级,属于指令函数外部的全局代码。机器人启动时会直接执行所有全局代码,此时data变量仅在触发test指令、进入with块时才会被定义,启动阶段自然抛出data is not defined错误。 - 额外潜在问题:缺少文件不存在、目标用户无警告记录的异常处理,后续运行仍有可能触发其他报错。
修复后的完整代码
# 顶部确保已经导入json模块 import json import discord from discord.ext import commands # 此处bot配置按你自己的实际参数调整即可 bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @bot.command() async def test(ctx, user:discord.Member): # 捕获文件不存在的异常 try: with open("warns.json", "r") as f: data = json.load(f) except FileNotFoundError: await ctx.send("暂无任何警告记录") return # 处理用户无警告记录的场景,避免触发KeyError user_data = data.get(str(user.id), []) await ctx.send(f"Total warnings: {len(user_data)}") for warn in user_data: warn_id, mod, reason, time = warn.values() await ctx.send(f"ID: {warn_id}, mod: {mod}, reason: {reason}")
调整说明
- 所有指令相关逻辑全部缩进放在
test函数内部,只有触发指令时才会执行,不会在机器人启动阶段提前运行 - 新增文件不存在的异常捕获,避免文件未创建时触发报错
- 改用
dict.get()方法读取用户数据,用户没有警告记录时默认返回空列表,不会触发KeyError - 原代码的
print仅会在机器人控制台输出,调整为用await ctx.send把结果发送到指令触发的频道,符合Discord机器人的使用逻辑,如果确实只需要控制台输出可以改回print
内容的提问来源于stack exchange,提问作者Jack Mills
相关产品推荐
相关产品推荐

