【问题标题】:Discord Bot - Java script code to PythonDiscord Bot - 到 Python 的 Javascript 代码
【发布时间】:2018-05-31 05:31:21
【问题描述】:

好的,所以我的 java 脚本机器人有一行代码,我正试图在 python 中重新创建!如果有人能告诉我我需要制作的作品。或者甚至如何在 python 中制作它,我会非常感激它!

const fs = require("fs");
let points = JSON.parse(fs.readFileSync("./points.json", "utf8"));

client.on("message", message => {
  if (message.author.bot) return; // always ignore bots!

  // if the points don"t exist, init to 0;
  if (!points[message.author.id]) points[message.author.id] = {
    points: 0,
    level: 0
  };
  points[message.author.id].points++;

  // And then, we save the edited file.
  fs.writeFile("./points.json", JSON.stringify(points), (err) => {
    if (err) console.error(err)
  });
});

如果可能,我想继续使用 .json!但如果他们有更好的方法,请告诉!

【问题讨论】:

  • 我还应该解释一下它是一个用于发送消息的分级系统,但我不知道如何使用 python 导出和导入文件。所以这基本上就是我想要的!
  • 我很确定您需要的所有答案都可以通过一系列 Google 找到。

标签: javascript python discord


【解决方案1】:

对于 python 2,可以使用open 打开文件。使用 rw 标志,具体取决于您要读取还是写入。例如:

with open('input.txt', 'r') as f:
    for line in f.readlines():
        print(line)
with open('output.txt', 'w') as f:
    f.write('my output')

对于json,使用内置库https://docs.python.org/2/library/json.html

这个 sn-p 显示了将 json 对象写入文件

import json

# store data in a dictionary
obj = {'name': 'joe'}

# write object to an output file
with open('output.txt', 'w') as f:
    json.dump(obj, f)

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2021-11-04
    • 2021-07-18
    • 2020-03-24
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多