Thecutepug
Thecutepug

Reputation: 21

I am new to python and i am trying to create a leaderboard

I would like to, as an admin, add points to a specific member's balance Know how to create a JSON file with all the "points" someone has.

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


# this line of code gives the bot a comand prefix
bot = commands.Bot(command_prefix="/")

# This line of code tells the bot to start up
@bot.event
async def on_ready():
  print("The bot is now online!")

@bot.command(pass_context=True)
async def leaderboard(ctx):
  await ctx.send("This is a work in progress, this will dieplay the leaderboard")
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 {} ben points".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.keys:
        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()

#This line of code tells the bot to run
bot.run("Token")

I am not sure on what I am meant to do from here.

I might be over complicating the code if anyone can make it more efficient I will be incredibly grateful.

Upvotes: 1

Views: 128

Answers (1)

Diggy.
Diggy.

Reputation: 6944

Here's the essential usage and everything you'll need to know for the basics of JSON:

# Creating a dictionary with some values
>>> data = {"foo": "bar", "key": "value"}

# Opening a file and writing to it
>>> with open("db.json", "w+") as fp:
...     json.dump(data, fp, sort_keys=True, indent=4) # Kwargs for beautification

# Loading in data from a file
>>> with open("db.json", "r") as fp:
...     data = json.load(fp)

# Accessing the values
>>> data["foo"]
'bar'
>>> data["key"]
'value'

This can be adapted to suit your needs, perhaps something like:

# Let's say the JSON has the following structure:
# {"users": {112233445566778899: {"points": 0}, 224466881133557799: {"points": 0}}}
# The "users" key is a bit redundant if you're only gonna store users in the file.
# It's down to what you'll be storing in the file and readability etc.
import json
import random
import typing

def add_points(member_id: str, amount: int):
    # Open the file first as to load in all the users' data
    # Making a new dict would just overwrite the current file's contents
    with open("file.json", "r") as fp:
        data = json.load(fp)
    data["users"][member_id]["points"] += amount
    # Write the updated data to the file
    with open("file.json", "w+") as fp:
        json.dump(data, fp, sort_keys=True, indent=4)
    return data["users"][user_id]["points"]

@bot.command()
async def give(ctx, member: typing.Optional[discord.Member]=None, points:typing.Optional[int]=None):
    if not member:
        member = ctx.author
    if not points:
        points = random.randint(10, 50)

    # Have a separate getter for the points - this was just for the sake of concise code
    total_points = add_points(member.id, points)
    await ctx.send(f"Successfully gave {member.mention} {points} points! Total: {total_points}")

I'll be happy to clarify anything if need be.


References:

Upvotes: 1

Related Questions