【发布时间】:2022-10-13 13:55:25
【问题描述】:
我正在编写一个不和谐的机器人,其功能是记录消息(编辑和删除)。这就是我正在使用的相同 -
#to select channel for logging and enable logging
async def ext_command(self, ctx: interactions.CommandContext, channel: str):
with open ('channels.json','r') as file:
data = json.load(file)
data[str(ctx.guild_id)]=str(channel.id)
with open ('channels.json','w') as outfile:
json.dump(data, outfile)
await ctx.send("logged")
#to disable logging also notify if logging was not enabled in the 1st place
async def ext_command1(self, ctx: interactions.CommandContext):
with open('channels.json','r') as file:
data = json.load(file)
if ctx.guild_id not in data.keys():
await ctx.send("Logging was not enabled")
return
removed_value = data.pop(ctx.guild_id)
with open('channels.json','w') as file:
json.dump(data, file)
await ctx.send("Logging disabled")
#to log deleted message
async def on_message_delete(self, message: interactions.Message):
with open('channels.json','r') as openfile:
channel_id = json.load(openfile)
if str(message.guild_id) not in channel_id.keys():
return
#code to build embed
#same logic as above for logging edited message
我将公会 ID 和频道 ID(用于记录)保存在 json 文件中。现在,您可以观察到每次发生消息删除或编辑事件时,我的代码都会打开文件,读取它以查找发生事件的公会是否存在某个频道 ID,如果该公会没有条目,则返回,如果有,它继续构建一个嵌入。我觉得这是低效的,因为即使未启用日志记录,代码也会打开并读取文件。我的目标是尽量减少托管费用。
我对吗?将这些数据存储在 mongodb 数据库而不是本地文件中也是一个好主意吗?我已经在使用它来存储和检索命令中的一些用户信息。请帮忙。
谢谢
【问题讨论】:
标签: python-3.x file-io discord discord-interactions