为什么我的json文件不与其他文件同步

问题描述 投票:0回答:1

在我的 dig.py 中:

import discord
from discord.ext import commands
import json
import os
import random
import asyncio
from helpers import checks

class Dig(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.registered = checks.load_registered_users()
        self.balance = self.load_balance()
      
    def load_balance(self):
        if not os.path.exists("balance.json"):
            return {}
        with open("balance.json", "r") as file:
            try: 
                balance = json.load(file)
            except json.JSONDecodeError:
                balance = {}
        return balance

    @checks.has_registered()
    @commands.command(aliases=["mine"])
    @commands.cooldown(1, 1, commands.BucketType.user)
    async def dig(self, ctx):
        user_id = str(ctx.message.author.id)
        if user_id not in self.registered:
            need_to_register_embed = discord.Embed(
                title="Account not registered", 
                description="Your account is not registered yet! Please register with `.register`!", 
                color=discord.Color.red()
            )
            await ctx.send(embed=need_to_register_embed)
        elif user_id in self.registered:
            with open("balance.json", "r") as f:
                balance = json.load(f)
            if user_id in balance:
                randomn = 0
                randomn = random.randint(1, 1024)
                coins_earned = 0
                if 1 <= randomn <= 2:
                    coins_earned = 1000
                elif 3 <= randomn <= 7:
                    coins_earned = 500
                elif 8 <= randomn <= 22:
                    coins_earned = 200
                elif 23 <= randomn <= 52:
                    coins_earned = 100
                elif 53 <= randomn <= 98:
                    coins_earned = 95
                elif 99 <= randomn <= 145:
                    coins_earned = 90
                elif 146 <= randomn <= 193:
                    coins_earned = 85
                elif 194 <= randomn <= 242:
                    coins_earned = 80
                elif 243 <= randomn <= 292:
                    coins_earned = 75
                elif 293 <= randomn <= 343:
                    coins_earned = 70
                elif 344 <= randomn <= 395:
                    coins_earned = 65
                elif 396 <= randomn <= 448:
                    coins_earned = 60
                elif 449 <= randomn <= 502:
                    coins_earned = 55
                elif 503 <= randomn <= 556:
                    coins_earned = 50
                elif 557 <= randomn <= 611:
                    coins_earned = 45
                elif 612 <= randomn <= 667:
                    coins_earned = 40
                elif 668 <= randomn <= 724:
                    coins_earned = 35
                elif 725 <= randomn <= 782:
                    coins_earned = 30
                elif 783 <= randomn <= 841:
                    coins_earned = 25
                elif 842 <= randomn <= 901:
                    coins_earned = 20
                elif 902 <= randomn <= 962:
                    coins_earned = 15
                elif 963 <= randomn <= 1024:
                    coins_earned = 10
                gem = 0
                gem = random.randint(1,10)
                coins = balance[user_id].get("coins")
                coins += coins_earned
                balance[user_id]["coins"] = coins
                with open("balance.json", "w") as f:
                    json.dump(balance, f)
                dig_embed = discord.Embed(
                    title = "Digging coins...", 
                    color=discord.Color.blue()
                )
                earned_embed = discord.Embed(
                    title = f"{ctx.author.display_name} went digging!", 
                    description = f"You found {coins_earned} 🪙!", 
                    color=discord.Color.blue()
                )
                send = await ctx.send(embed = dig_embed)
                await asyncio.sleep(0.1)
                await send.edit(embed = earned_embed)
                if gem == 1:
                    gems_earned = 1
                    gems = balance[user_id].get("gems")
                    gems += gems_earned
                    balance[user_id]["gems"] = gems
                    with open("balance.json", "w") as f:
                        json.dump(balance, f)
                    await asyncio.sleep(0.1)
                    gem_embed = discord.Embed(
                        title = "Wait a second...",
                        color = discord.Color.blue()
                    )
                    gem_embed.add_field(
                        name = "You lucky ducky!",
                        value = "You found a gem 💎 ! Added to your balance!",
                        inline = False
                    )
                    await ctx.send(embed = gem_embed)
    @dig.error
    async def dig_error(self,ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            x = round(error.retry_after)
            y = await ctx.send(f"**{ctx.author.display_name}**\n > You are digging too fast!\n > Please try again in **{x}** seconds.", delete_after = x)
            while x > 0:
                await y.edit(content = f"**{ctx.author.display_name}**\n > You are digging too fast!\n > Please try again in **{x}** seconds.")
                x = x - 1
                await asyncio.sleep(1)
        elif isinstance(error, checks.NotStarted):
            need_to_register_embed = error.embed
            await ctx.send(embed=need_to_register_embed)
                
async def setup(bot):
    await bot.add_cog(Dig(bot))

在我的 helpers 文件夹中,文件checks.py:

import os
import json
import discord
from discord.ext import commands

class NotStarted(commands.CheckFailure):
    def __init__(self, *, embed=None):
        self.embed = embed
      
def load_registered_users():
    if not os.path.exists("registered.json"):
        return {}
    with open("registered.json", "r") as file:
        try:
            registered = json.load(file)
        except json.JSONDecodeError:
            registered = {}
    return registered
  
def has_registered():
  async def predicate(ctx):
      registered = load_registered_users()
      user_id = str(ctx.message.author.id)
      if user_id not in registered:
          need_to_register_embed = discord.Embed(
              title="Account not registered", 
              description="Your account is not registered yet! Please register with `.register`!", 
              color=discord.Color.red()
          )
          raise NotStarted(embed=need_to_register_embed)
      return True
  return commands.check(predicate)

注册.py:

import discord
from discord.ext import commands
import json
import os

class Register(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.registered = self.load_registered_users()
        self.balance = self.load_balance()

    def load_registered_users(self):
        if not os.path.exists("registered.json"):
            return {}
        with open("registered.json", "r") as file:
            try:
                registered = json.load(file)
            except json.JSONDecodeError:
                registered = {}
        return registered
      
    def load_balance(self):
        if not os.path.exists("balance.json"):
            return {}
        with open("balance.json", "r") as file:
            try: 
                balance = json.load(file)
            except json.JSONDecodeError:
                balance = {}
        return balance
      
    @commands.command(aliases=["reg"])
    async def register(self, ctx):
        user_id = str(ctx.message.author.id)
        if user_id not in self.registered:
            self.registered[user_id] = True
            self.save_registered_users()
            self.balance[user_id] = {
                "coins": 0,
                "gems": 0
            }
            self.save_balance_users()
            register_embed = discord.Embed(
                title="Account Successfully Registered ✅", 
                description="You are now registered!", 
                color = discord.Color.green()
            )
            await ctx.send(embed=register_embed)
        else:
            registered_embed = discord.Embed(
                title="Account Already Registered", 
                description="You already have an account!", 
                color = discord.Color.red()
            )
            await ctx.send(embed=registered_embed)

    def save_registered_users(self):
        with open("registered.json", "w") as file:
            json.dump(self.registered, file)
    def save_balance_users(self):
      with open("balance.json", "w") as file:
          json.dump(self.balance, file)

async def setup(bot):
    await bot.add_cog(Register(bot))

问题是,当我注册时,一切都工作得很好,但是当我注册并输入

.dig
时,它说我没有注册,我必须注册。但是当我再次输入
.register
时,它说我已经注册了。所以我想知道为什么当我输入
.dig
时,代码没有与我的 json 文件中存储的数据同步。请帮忙。

python json discord.py
1个回答
0
投票

这是因为您的

register
字典是在
__init__
方法中定义的,该方法不与
Dig
cog 共享。 要解决这个问题,你必须在
register
cog 中定义
Dig
字典,如下所示:

import discord
from discord.ext import commands
import json
import os
import random
import asyncio
from helpers import checks

class Dig(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
      
    def load_balance(self):
        if not os.path.exists("balance.json"):
            return {}
        with open("balance.json", "r") as file:
            try: 
                balance = json.load(file)
            except json.JSONDecodeError:
                balance = {}
        return balance

    @checks.has_registered()
    @commands.command(aliases=["mine"])
    @commands.cooldown(1, 10, commands.BucketType.user)
    async def dig(self, ctx):
            self.registered = checks.load_registered_users() #call here
            self.bal: dict = self.load_balance()             #make sure it is a dict
            user_id = str(ctx.message.author.id)
            with open("balance.json", "r") as f:
                balance = json.load(f)
            if user_id in balance:
                randomn = 0
                randomn = random.randint(1, 1024)
                coins_earned = 0
                if 1 <= randomn <= 2:
                    coins_earned = 1000
                elif 3 <= randomn <= 7:
                    coins_earned = 500
                elif 8 <= randomn <= 22:
                    coins_earned = 200
                elif 23 <= randomn <= 52:
                    coins_earned = 100
                elif 53 <= randomn <= 98:
                    coins_earned = 95
                elif 99 <= randomn <= 145:
                    coins_earned = 90
                elif 146 <= randomn <= 193:
                    coins_earned = 85
                elif 194 <= randomn <= 242:
                    coins_earned = 80
                elif 243 <= randomn <= 292:
                    coins_earned = 75
                elif 293 <= randomn <= 343:
                    coins_earned = 70
                elif 344 <= randomn <= 395:
                    coins_earned = 65
                elif 396 <= randomn <= 448:
                    coins_earned = 60
                elif 449 <= randomn <= 502:
                    coins_earned = 55
                elif 503 <= randomn <= 556:
                    coins_earned = 50
                elif 557 <= randomn <= 611:
                    coins_earned = 45
                elif 612 <= randomn <= 667:
                    coins_earned = 40
                elif 668 <= randomn <= 724:
                    coins_earned = 35
                elif 725 <= randomn <= 782:
                    coins_earned = 30
                elif 783 <= randomn <= 841:
                    coins_earned = 25
                elif 842 <= randomn <= 901:
                    coins_earned = 20
                elif 902 <= randomn <= 962:
                    coins_earned = 15
                elif 963 <= randomn <= 1024:
                    coins_earned = 10
                gem = 0
                gem = random.randint(1,10)
                coins = balance[user_id].get("coins")
                coins += coins_earned
                balance[user_id]["coins"] = coins
                with open("balance.json", "w") as f:
                    json.dump(balance, f)
                dig_embed = discord.Embed(
                    title = "Digging coins...", 
                    color=discord.Color.blue()
                )
                earned_embed = discord.Embed(
                    title = f"{ctx.author.display_name} went digging!", 
                    description = f"You found {coins_earned} 🪙!", 
                    color=discord.Color.blue()
                )
                send = await ctx.send(embed = dig_embed)
                await asyncio.sleep(0.1)
                await send.edit(embed = earned_embed)
                if gem == 1:
                    gems_earned = 1
                    gems = balance[user_id].get("gems")
                    gems += gems_earned
                    balance[user_id]["gems"] = gems
                    with open("balance.json", "w") as f:
                        json.dump(balance, f)
                    await asyncio.sleep(0.1)
                    gem_embed = discord.Embed(
                        title = "Wait a second...",
                        color = discord.Color.blue()
                    )
                    gem_embed.add_field(
                        name = "You lucky ducky!",
                        value = "You found a gem 💎 ! Added to your balance!",
                        inline = False
                    )
                    await ctx.send(embed = gem_embed)
    @dig.error
    async def dig_error(self,ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            x = round(error.retry_after)
            y = await ctx.send(f"**{ctx.author.display_name}**\n > You are digging too fast!\n > Please try again in **{x}** seconds.", delete_after = x)
            while x > 0:
                await y.edit(content = f"**{ctx.author.display_name}**\n > You are digging too fast!\n > Please try again in **{x}** seconds.")
                x = x - 1
                await asyncio.sleep(1)
        elif isinstance(error, checks.NotStarted):
            need_to_register_embed = error.embed
            await ctx.send(embed=need_to_register_embed)
                
async def setup(bot):
    await bot.add_cog(Dig(bot))

不是你的问题,但你的冷却时间有问题,尤其是当它

1, 1
时,我已将其更改为
1, 10
以使其更有意义。 您的
checks.py
register.py
没有任何问题,因此在修复
dig.py
中的代码后,一切都应该正常。 希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.