discord.py实现warn命令时报错TypeError: 'Command' object is not subscriptable
问题修复方案
报错根源
你遇到的TypeError: 'Command' object is not subscriptable报错核心原因是变量名冲突:
全局定义的用于存储警告记录的report变量,被代码其他位置定义的同名report命令覆盖,此时report已经不是加载得到的JSON字典,而是discord.py的Command对象,无法用[]下标访问自然会报错。
具体修改步骤
1. 解决变量名冲突
将存储警告数据的全局变量改名,避免和命令名冲突,比如改成warn_records,所有用到该变量的位置同步替换:
# 修改加载JSON的代码 import json with open('warns.json', encoding='utf-8') as f: try: warn_records = json.load(f) except ValueError: warn_records = {} warn_records['users'] = []
后续所有report['users']的写法都替换为warn_records['users'],写入文件时也对应修改变量名。
2. 修复缩进错误
你当前warn函数内存在致命缩进问题:author、reason拼接、embed初始化三行代码现在缩进在if not reason块内部,只要reason不为空就永远不会执行,会触发变量未定义报错,修改后代码结构如下:
@client.command(pass_context=True) @commands.has_permissions(manage_roles=True, ban_members=True) async def warn(ctx, user: discord.User, *reason: str): if not reason: await ctx.send("Please provide a reason") return # 以下三行调整到和if语句同级缩进 author = ctx.author reason = ' '.join(reason) embed = discord.Embed(title=f'{author.name} warned {user.name} for {reason}') for current_user in warn_records['users']: if current_user['name'] == user.name: current_user['reasons'].append(reason) break else: warn_records['users'].append({ 'name': user.name, 'reasons': [reason,] }) # 写入时指定编码避免中文乱码 with open('warns.json', 'w+', encoding='utf-8') as f: json.dump(warn_records, f, ensure_ascii=False) await ctx.send(embed=embed)
可选优化
建议使用用户唯一IDuser.id替代user.name作为用户标识,避免用户修改用户名后警告记录匹配错误。
内容的提问来源于stack exchange,提问作者Likey
相关产品推荐
相关产品推荐

