You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python开发Discord机器人:命令日志追加写入问题求助

解决Discord命令日志覆盖问题

你的问题出在文件打开模式上:'w+' 模式会在打开文件时清空原有内容,再写入新数据,所以每次新日志都会覆盖旧的。

要实现追加日志,把打开模式改成 'a'(追加模式)即可,这个模式会把新内容写到文件末尾,不会清空原有内容。如果需要同时读取文件,可以用 'a+',但这里只需要写入,'a' 足够。

修改后的代码:

from datetime import datetime  # 别忘了导入datetime模块,否则会报错

@bot.event
async def on_command(ctx):
    with open('logs.txt', 'a') as f:
        command = str(ctx.command)
        user = str(ctx.message.author)
        now = datetime.now()
        time = now.strftime("[%H:%M:%S]")
        date = now.strftime("[%d-%m-%Y]")
        f.write(f"{user} a éxécuter la command {command} à {time} le {date}\n")

另外注意字符串里的小错误:a {time} 应该改为 à {time}(法语介词规范用法),已帮你修正。

内容的提问来源于stack exchange,提问作者Xerty - Minecraft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:39:25