Discord Bot检测消息中JSON键存在性异常:执行命令无响应
问题修复:Discord Bot执行!rijal a无响应
问题原因分析
你的代码存在三个关键错误,导致Bot无法正常响应:
- 混淆命令参数与消息对象:命令定义里的
message参数就是用户输入的a,但代码里错误使用了ctx.message(这是包含命令前缀、命令名的完整消息对象,并非用户传入的目标参数)。 - 存在性判断逻辑错误:
narrators.keys()是字典键的集合,不能直接用in和ctx.message(消息对象)做比较,应该检查传入的参数是否在字典的键列表中。 - 字典取值参数错误:
narrators.get()应该使用用户传入的参数,而非整个消息对象。
修正后的代码
from discord.ext import commands import json with open(r"C:\Users\intel\Desktop\rijalbot\rijaldata\narrators.json") as f: narrators = json.load(f) class cmds(commands.Cog): def __init__(self, client): self.bot = client @commands.command() async def rijal(self, ctx, arg): # 检查传入的参数是否在narrators的键中 if arg in narrators: val = narrators.get(arg) if val == "weak": await ctx.send("True")
额外注意事项
- 确保Bot已正确加载该Cog,否则命令不会生效。加载Cog的示例代码:
import discord client = commands.Bot(command_prefix="!", intents=discord.Intents.all()) async def setup(): await client.add_cog(cmds(client)) # 启动Bot的代码 - 确认Bot的权限设置包含发送消息权限,否则即使逻辑正确也无法发送回复。
内容的提问来源于stack exchange,提问作者kararmightbehere
相关产品推荐
相关产品推荐

