【发布时间】:2020-10-01 02:58:48
【问题描述】:
我最近在 python 中创建了一个 discord 机器人,并想为其添加一个货币系统。我希望能够存储和调用每个玩家的余额。 任何关于从哪里开始或视频链接的提示都会非常有帮助。 提前致谢!
【问题讨论】:
标签: discord discord.py discord.py-rewrite
我最近在 python 中创建了一个 discord 机器人,并想为其添加一个货币系统。我希望能够存储和调用每个玩家的余额。 任何关于从哪里开始或视频链接的提示都会非常有帮助。 提前致谢!
【问题讨论】:
标签: discord discord.py discord.py-rewrite
我有一个像这样的系统是我的机器人,我通过将我的数据存储在 JSON 文件中来做到这一点。您可以通过简单地创建一个名为 data.txt 的 TXT 文件并在其中键入它来做到这一点。另外,一定要导入 JSON 模块。
{points: []}
然后在你的python代码中,你可以做这样的事情。
with open("data.txt") as json_file:
points = json.load(json_file)
for user in points["points"]:
if user["id"] == ctx.author.id:
point_num = user["points"]
await ctx.send(f"You have {point_num} points")
with open("data.txt", "w") as outfile:
json.dump(points, outfile)
如果你想加分,你可以这样做。
with open("data.txt") as json_file:
points = json.load(json_file)
for user in points["points"]:
if user["id"] == member.id:
user["points"] += amount
with open("data.txt", "w") as outfile:
json.dump(points, outfile)
您可能会遇到问题,例如每个用户都没有自己的存储空间,因此在设置开始时,您应该像这样为每个人分配自己的存储空间。
with open("data.txt") as json_file:
points = json.load(json_file)
for user in ctx.guild.members:
points.append({
"id": member.id,
"points": 0
})
with open("data.txt", "w") as outfile:
json.dump(points, outfile)
这将确保目前在 Discord 公会中的每个人都有自己的存储空间。因此,您现在可以在运行一次并确保将其保存到 TXT 文件后删除此代码。现在我们应该添加一些代码来确保每个新用户都能获得存储空间。因此,创建 on_member_join 事件的新实例并将其放入其中。
with open("data.txt") as json_file:
points = json.load(json_file)
points["points"].append({
"id": member.id,
"points": 0,
})
with open("data.txt", "w") as outfile:
json.dump(points, outfile)
你应该完成了!抱歉,这篇文章这么长,只是这样做需要时间。希望您了解这一点,并能够成功地建立您的经济系统。如果您有任何问题,请继续对此发表评论,别担心我会看到它!
【讨论】: