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

如何在Discord机器人中将每个用户的回复变量独立保存到文本文件?

Discord机器人定时DM功能存储实现方案

第一步:修正参数提取逻辑

你当前的参数提取顺序不符合输入命令结构,输入命令!dm @wabulu Sunday 13:00 math拆分后,第一个参数为被@的用户标识,需要先提取用户信息,再提取时间和科目参数:

# 提取用户完整标识,移除@前缀,得到类似wabulu#xyxy的格式
user = args[0].lstrip('@')
# 星期统一转小写,避免大小写导致后续匹配失败
day = args[1].lower()
time = args[2]
subject = args[3]

第二步:实现独立用户存储逻辑

以下提供两种符合你需求的实现方案,优先推荐第二种按用户独立存储的方案:

方案1:单文件集中存储(适合小体量用户场景)

所有用户的定时任务存在同一个文本文件,每行一条记录,完全匹配你要求的存储格式:

写入代码

# 追加模式写入,不会覆盖历史数据
with open("schedule.txt", "a", encoding="utf-8") as f:
    f.write(f"{user} {day} {time} {subject}\n")

读取解析代码

schedule_list = []
with open("schedule.txt", "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        user, day, time, subject = line.split()
        schedule_list.append({
            "user": user,
            "day": day,
            "time": time,
            "subject": subject
        })

方案2:按用户独立分文件存储(符合你要求的用户数据独立存储需求)

每个用户单独对应一个存储文件,避免单文件过大,单个用户文件损坏不会影响其他用户数据:

写入代码

# 替换用户标识中的特殊字符,避免操作系统文件名报错
safe_filename = f"{user.replace('#', '_')}_schedule.txt"
# 追加写入该用户的定时任务
with open(safe_filename, "a", encoding="utf-8") as f:
    f.write(f"{day} {time} {subject}\n")

读取解析代码

如果需要全量读取所有用户的任务,遍历所有*_schedule.txt后缀的文件即可;如果仅需读取单个用户的任务,直接对应用户的文件名读取即可:

import os

all_schedule = []
# 遍历当前目录下所有用户的任务文件
for filename in os.listdir("."):
    if filename.endswith("_schedule.txt"):
        # 从文件名还原用户标识
        user = filename.replace("_schedule.txt", "").replace("_", "#")
        with open(filename, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                day, time, subject = line.split()
                all_schedule.append({
                    "user": user,
                    "day": day,
                    "time": time,
                    "subject": subject
                })

可选优化:结构化存储扩展

如果后续需要新增Zoom链接、任务开关等扩展字段,推荐用JSON格式存储每个用户的任务,解析更方便不容易出错:

import json

safe_filename = f"{user.replace('#', '_')}_schedule.json"
# 读取该用户已有任务
try:
    with open(safe_filename, "r", encoding="utf-8") as f:
        user_tasks = json.load(f)
except FileNotFoundError:
    user_tasks = []

# 新增任务
user_tasks.append({
    "day": day,
    "time": time,
    "subject": subject,
    "zoom_link": "你的Zoom链接"
})

# 写回文件
with open(safe_filename, "w", encoding="utf-8") as f:
    json.dump(user_tasks, f, ensure_ascii=False, indent=2)

注意事项

  • 写入新任务前先校验是否已存在相同记录,避免重复推送
  • 增加参数合法性校验,比如星期是否为有效值、时间是否符合HH:MM格式,避免无效数据入库
  • 定期备份存储文件,避免意外损坏丢失数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:03:01