【问题标题】:Discord.py how can I use json to store a users id and only a users idDiscord.py 如何使用 json 来存储用户 ID 并且仅存储用户 ID
【发布时间】:2018-12-28 00:02:48
【问题描述】:

那么,我将如何在 json 中存储用户不和谐 id,并且只有用户 id,仅此而已。不知道该怎么做。

感谢您的帮助!

【问题讨论】:

  • 什么,比如 id 列表,或者文件中的单个 id?
  • id 列表,但是当用户使用命令时,它会获取用户 id。对于每个使用它的用户,id 都会添加到文件@PatrickHaugh
  • 字符串列表已经是有效的 json。你在哪个部分苦苦挣扎?您可以使用json.load 从文件中获取列表,然后使用常规python 对其进行修改,然后使用json.dump 将其写回文件。我什至不认为你需要json。只需保留一个带有换行符分隔 ID 的文本文件。当您看到它们时,使用“附加”文件模式添加新文件。然后将该文件加载到您的on_ready 事件中的set 中。
  • 你能用一个例子来解释它吗? @PatrickHaugh

标签: json python-3.x discord.py


【解决方案1】:

您可以为此使用常规的 txt 文件。当你看到它们时附加新的 id。启动机器人时,将所有 id 加载到 set 以防止重复

ids = set()

@bot.event
async def on_ready():
    with open("ids.txt") as f:
        for id in f:
            ids.add(id.strip())

@bot.command(pass_context=True)
async def register(ctx):
    id = ctx.message.author.id
    if id not in ids:
        ids.add(id)
        with open("ids.txt", "a") as f:
            print(id, file=f)
        await bot.say("ID {} added".format(id))

【讨论】:

  • 如果有的话,我需要在 .txt 文件中放入什么?
  • 我认为它应该只适用于一个空文件。如果您确实在其中放入了一些 id 以开始,请确保它们由单个换行符分隔,并且文件以换行符结尾
猜你喜欢
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多