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

Discord Bot文本保存异常求助:文件仅更新时间戳无内容

Discord Bot 写入文件为空问题修复

问题根源

你的代码存在缩进错误:on_message函数中,file1.write(f" {message.content}")语句没有缩进在with open(Templetext, "w") as file1:的代码块内。这会导致文件对象file1在执行write操作前就被自动关闭,内容无法写入文件,最终文件为空。

日志里出现大量逗号,是因为当message.content为空时,file2.write(f" {message.content}, {newline}")会写入, \n,这说明Bot确实能捕获到消息事件,但第一个文件的写入逻辑因缩进错误完全失效。

修正后的代码

import discord

Templetext = 'writefile.txt'
Logfile = 'templelog.txt'
newline = '\n'
closetemple = 'exit()'
Token = 'my token string'
client = discord.Client()

print('I am on')

@client.event
async def on_ready():
    print('Ready and Listening')

@client.event
async def on_message(message):
    # 修复缩进:将write操作放入with代码块内
    with open(Templetext, "w") as file1:
        file1.write(f" {message.content}")
    with open(Logfile, "a") as file2:
        # 可选:避免空消息只写入逗号
        content = f" {message.content}, {newline}" if message.content else newline
        file2.write(content)

client.run(Token)

额外说明

  • 使用"w"模式写入Templetext时,每次收到消息都会覆盖文件原有内容;如果需要追加而非覆盖,可改为"a"模式。
  • 新增的空消息判断可以避免日志里出现大量无意义的逗号,让日志更整洁。

内容的提问来源于stack exchange,提问作者Jammie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:05:26