【问题标题】:How to save a message with a command and then get the message with another command using json?如何使用命令保存消息,然后使用 json 使用另一个命令获取消息?
【发布时间】:2021-08-15 02:58:11
【问题描述】:

实在不知道标题怎么形容了,这里再澄清一下。

我和我的朋友拥有一个 Discord 服务器,我们在其中与其他同学分享作业答案。我们使用机器人来执行此操作,每次他们为特定主题(例如 !ela 或 !math)调用命令时,它都会给出该主题的答案。

问题是,这变得越来越难了,因为我和我的朋友越来越忙,没有时间继续研究和更改代码。

所以基本上,我需要创建一个命令(有点像!hwadd(主题)(链接到作业答案下载),它将主题和答案保存到 .json 文件中,然后当有人调用该主题的命令时(例如!math),它将返回该主题的链接。

问题是,我对使用 .json 文件知之甚少。有人可以帮忙吗?

【问题讨论】:

  • 只要你了解字典的工作原理,就可以使用import jsonfile = open('homework.json', 'w')json.dump(dict(), file)将字典转储到json文件中
  • @Judev1 我做到了,它有效,但是我该如何取回这些数据?
  • 您可以使用with open('homework.json', 'r') as homeworkfile检索数据,然后使用json.loads(homeworkfile.read())

标签: python json discord discord.py


【解决方案1】:

哈哈哈,我有一个非常相似的机器人,但我的同学们一直在向每个人询问应得的东西,所以我也做了一个硬件机器人。

这是一个简单的例子(cog btw);

@commands.command
async def math(self, ctx):
  with open("math.json","r") as f:
     math = json.load(f)
  await ctx.send(f"{math}")

现在制作addhw 命令

@commands.command
async def addmath(self, ctx, *, hw):
  with open("math.json","w") as f:
    json.dump(hw,f)
  await ctx.send("Added Math!")

就是这样!很简单。

【讨论】:

  • 谢谢!这种方法对我来说非常有效!
猜你喜欢
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 2022-06-25
相关资源
最近更新 更多