Advice and suggestions on improving code efficiency by limiting file read operations for a discord bot

Viewed 19

I am writing a discord bot one of whose function is to log messages (edit and delete). This is what I am using for the same-

    #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

I'm saving guild id and channel id (for logging) in a json file. Now as you can observe every time a message delete or edit event occurs my code opens the file, reads it to find if some channel id exists for the guild in which the event has occurred and returns if there is no entry for that guild, if there is, it goes on to build an embed. I feel this is inefficient as code opens and reads the file even if logging was not enabled. I'm aiming to keep hosting expenses minimal.

Am I right? Also would it be a good idea to store this data in a mongodb database instead of a local file? I am already using it to store and retrieve some user information on command. Please help.

Thanks

0 Answers
Related