Discord money bot 将用户 ID 保存在 json 文件中。当 Not 重新启动时,它会为每个人创建一个新的(但相同的)ID

Discord money bot keeping user ID's in json file. When Bot restarts it creats a new (but same) ID for everyone

当这段代码运行时,它可以从 discord 获取用户 ID 并将他们有 100 钱存入 json,但是一旦您重新启动机器人,您就必须再次注册并且它会写入相同的用户 ID json 文件认为它是新用户,但实际上不是。

from discord.ext import commands
import discord
import json

bot = commands.Bot('!')

amounts = {}

@bot.event
async def on_ready():
    global amounts
    try:
        with open('amounts.json') as f:
            amounts = json.load(f)
    except FileNotFoundError:
        print("Could not load amounts.json")
        amounts = {}

@bot.command(pass_context=True)
async def balance(ctx):
    id = ctx.message.author.id
    if id in amounts:
        await ctx.send("You have {} in the bank".format(amounts[id]))
    else:
        await ctx.send("You do not have an account")

@bot.command(pass_context=True)
async def register(ctx):
    id = ctx.message.author.id
    if id not in amounts:
        amounts[id] = 100
        await ctx.send("You are now registered")
        _save()
    else:
        await ctx.send("You already have an account")

@bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
    primary_id = ctx.message.author.id
    other_id = other.id
    if primary_id not in amounts:
        await ctx.send("You do not have an account")
    elif other_id not in amounts:
        await ctx.send("The other party does not have an account")
    elif amounts[primary_id] < amount:
        await ctx.send("You cannot afford this transaction")
    else:
        amounts[primary_id] -= amount
        amounts[other_id] += amount
        await ctx.send("Transaction complete")
    _save()

def _save():
    with open('amounts.json', 'w+') as f:
        json.dump(amounts, f)

@bot.command()
async def save():
    _save()

bot.run("Token")

JSON 机器人关闭并重新启动并注册两次(假用户 ID)后:

{"56789045678956789": 100, "56789045678956789": 100}

需要它能够识别用户 ID,即使在 bot 关闭并重新打开后也是如此。

您只需加载您在程序启动时创建的 .json 文件。而不是 amounts = {} 试试这个:

import os

if os.path.exists('amounts.json'):
    with open('amounts.json', 'r') as file:
        amounts = json.load(file)
else:
    amounts = {} # default to not loading if file not found

更新

我相信在阅读了您的评论并检查了您的代码后,问题出在您的 register() 代码中。

你有:

if id not in amounts:

但应该是:

if id not in amounts.keys():

这是因为 JSON 对象总是有 "keys" 的字符串。所以 json.dump 将整数键转换为字符串。您可以通过在使用之前将用户 ID 转换为字符串来实现同样的效果。

from discord.ext import commands
import discord
import json

bot = commands.Bot('!')

amounts = {}

@bot.event
async def on_ready():
    global amounts
    try:
        with open('amounts.json') as f:
            amounts = json.load(f)
    except FileNotFoundError:
        print("Could not load amounts.json")
        amounts = {}

@bot.command(pass_context=True)
async def balance(ctx):
    id = str(ctx.message.author.id)
    if id in amounts:
        await ctx.send("You have {} in the bank".format(amounts[id]))
    else:
        await ctx.send("You do not have an account")

@bot.command(pass_context=True)
async def register(ctx):
    id = str(ctx.message.author.id)
    if id not in amounts:
        amounts[id] = 100
        await ctx.send("You are now registered")
        _save()
    else:
        await ctx.send("You already have an account")

@bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
    primary_id = str(ctx.message.author.id)
    other_id = str(other.id)
    if primary_id not in amounts:
        await ctx.send("You do not have an account")
    elif other_id not in amounts:
        await ctx.send("The other party does not have an account")
    elif amounts[primary_id] < amount:
        await ctx.send("You cannot afford this transaction")
    else:
        amounts[primary_id] -= amount
        amounts[other_id] += amount
        await ctx.send("Transaction complete")
    _save()

def _save():
    with open('amounts.json', 'w+') as f:
        json.dump(amounts, f)

@bot.command()
async def save():
    _save()

bot.run("Token")

我发现了问题并亲自测试了它,所以它不是 .keys() 或 os 的东西,而是在 _save() 函数中。我首先用 _save 函数做了一个测试,没有它,而不是使用调用函数,当我手动执行它时它起作用了。像这样

(P.S 我是在一个 cog 中做的,唯一的区别是名称 @commands.command,它是 @bot.command 并且您需要添加“self”)

@commands.command(pass_context=True)
async def register(self, ctx):
    id = str(ctx.message.author.id)
    with open("smth.json") as json_file:
        amounts = json.load(json_file)
    if id not in amounts:
        amounts[id] = 0
        await ctx.send("You are now registered")
    else:
        await ctx.send("You already have an account!")
    with open("smth.json", "w") as outfile:
        json.dump(amounts, outfile)

同样非常重要的注意事项,请确保当您创建一个 json 文件时,它的名称以“.json”结尾并且其中的所有内容都是

{

}