【问题标题】:Advice and suggestions on improving code efficiency by limiting file read operations for a discord bot关于通过限制不和谐机器人的文件读取操作来提高代码效率的建议和建议
【发布时间】: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


    【解决方案1】:
    1. 您的方法不会,因为它异步打开和关闭同一个文件。

    2. 每次写入文件时,您还会覆盖特定服务器的先前日志,因为 dicts 不能保留重复的键(在您的情况下为公会 ID)。

      我建议您使用流行且维护良好的 logging 库来完成此任务。

      例子:

      # you can choose both, make sure log file exists
      logging_file = 'mylog.log'
      logger_name = 'event_log'
      
      # Logger object is recognized by name in any file (you can choose this name
      event_logger = logging.getLogger(logger_name)  
      event_logger.setLevel(logging.INFO)
      
      handler = logging.FileHandler(filename=logger_name, encoding='utf-8')
      # this is the format for any message you log (message placeholder gets replaced)
      handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s', '%H:%M:%S'))
      
      event_logger.addHandler(handler)
      

      您可以将此代码 ^ 放在您的 main() 函数中或您开始使用机器人的任何位置

      使用event_logger = logging.getLogger(logger_name) 从程序中的任何位置引用相同的记录器

      之后,使用event_logger.info('This is my logged message') 记录您想要的任何消息。

      免责声明:这是从我正在研究的小型机器人的代码中获取的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 2023-03-25
      • 2015-03-21
      • 2021-06-09
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      相关资源
      最近更新 更多