Discord money bot хранит идентификаторы пользователя в файле json.Когда бот перезапускается, он создает новый (но тот же) идентификатор для всех - PullRequest
1 голос
/ 03 апреля 2019

Когда этот код запускается, он работает, получая идентификатор пользователя с разногласий и помещая в json 100 денег, но как только вы перезапустите бот, вам придется зарегистрироваться снова, и он записывает тот же идентификатор пользователя в файл 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 после того, как бот выключен и снова включен и зарегистрирован дважды (поддельные идентификаторы пользователей):

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

Нужно, чтобы он мограспознавать идентификаторы пользователя даже после того, как бот выключен и снова включен.

Ответы [ 2 ]

1 голос
/ 03 апреля 2019

Это происходит потому, что у объектов JSON всегда есть строки для «ключей».Таким образом, json.dump преобразует целочисленные ключи в строки.Вы можете сделать то же самое, преобразовав идентификаторы пользователей в строки перед их использованием.

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")
0 голосов
/ 03 апреля 2019

Вам просто нужно загрузить файл .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

UPDATE

Я полагаю, что после прочтения вашего комментария и просмотра кода проблема заключается в вашем register() коде.

У вас есть:

if id not in amounts:

Но это должно быть:

if id not in amounts.keys():
...