不和谐金钱机器人将用户ID保留在json文件中。当Bot重新启动时,它将为每个人创建一个新的(但相同的)ID

时间:2019-04-03 02:03:42

标签: python json discord discord.py discord.py-rewrite

运行此代码时,它可以从不和谐中获取用户ID,并将他们的json存入100美元,但是一旦您重新启动bot,就必须再次注册,并在json文件中写入相同的用户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 = 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")

关闭僵尸程序然后重新打开并注册两次(伪造的用户ID)后的JSON:

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

即使在关闭并重新打开漫游器后也需要能够识别用户ID。

3 个答案:

答案 0 :(得分:1)

之所以会这样,是因为JSON对象始终具有用于“键”的字符串。因此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")

答案 1 :(得分:0)

您只需要加载在程序启动时创建的.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():

答案 2 :(得分:-1)

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

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

var myValue = 0 ;
// function that add 5 to the variable that i type its name in the function parameters .
function modifyVariable(variableName){
    variableName += 4
}
modifyVariable(myValue);
console.log(myValue);

同样非常重要的注意事项,请确保在创建 json 文件时,其名称以“.json”结尾,并且其中包含的所有内容

@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)