如何让Discord bot在redeem命令触发时删除JSON文件中的指定数据
实现逻辑说明
- 当你校验到
code存在于读取到的JSON字典中后,直接用del data[code]删除对应键值对 - 删除内存中的数据后,需要以写入模式重新打开JSON文件,将修改后的字典序列化后写回文件,才能持久化保存修改
- 原有代码还存在两处可修复问题:
- check函数中的返回值逻辑错误,
hwidchannel == hwidchannel永远返回True,会误触发其他无关消息 - 消息格式化的占位符缺少索引,
{.content}会触发语法报错
- check函数中的返回值逻辑错误,
修正后完整代码
import json import discord from discord.ext import commands @client.command(name='redeem', pass_content=True) async def redeem(message, code): # 只读模式读取JSON文件 with open('keys.json', 'r', encoding='utf-8') as f: data = json.load(f) if code in data: # 删除指定code对应的条目 del data[code] # 将修改后的数据写回JSON文件 with open('keys.json', 'w', encoding='utf-8') as f: json.dump(data, f, indent=4) role = message.guild.get_role(910056424812466176) await message.author.add_roles(role) await message.author.send("message here") hwidchannel = client.get_channel(909907655324205088) def check(m): print("message detected") # 校验是触发命令的用户发送的DM消息 if isinstance(m.channel, discord.channel.DMChannel) and m.author.id == message.author.id: print("is dm, correct user") return True return False msg = await client.wait_for('message', check=check) await message.author.send('Please be patient as your purchase is reviewed.') # 修正格式化语法 await hwidchannel.send(f'Hwid is {msg.content}') await hwidchannel.send(f'Userid is {msg.author.id}') else: await message.author.send("Invalid Code")
注意:如果多并发触发redeem命令可能会出现文件读写冲突,高并发场景下建议换用数据库存储密钥数据,避免JSON文件损坏。
内容的提问来源于stack exchange,提问作者furious
相关产品推荐
相关产品推荐

