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

Thecutepug

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.

Diggy.

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:

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

I am trying to create a new Cart schema with a request

Partial keyword match not working when I am trying to create a new column from a pandas data frame in python?

I am am trying to link the image click to a new product page

I am new to using mysql - as i was trying to create a table i got the error below

I am trying to create a box in React, and it is not working

I am trying to create a dynamic spinner

I am trying to create a seven segment scoreboard

I am trying to create a Clamp method in java

I am trying to create a table with sqlite in Kotlin

I am trying to create a subscription but an error occurs

I am trying to create a flight widget

I am new to golang, I am trying to create a zip that must have a folder inside that is: tosend.zip/archivos/file.png

What am I doing wrong? I am very new to python

I am new to ruby language , and trying to create a text adventure game , i want to include two strings

I am trying to create a new window and execute a function after that new window creation in tkinter

I am unable to create a new virtualenv in ubuntu?

I am creating a RPS program. I am new to python, I am trying to figure out how the while loop works. I want to know how to repeat and break while loop

I am trying to install python module HTTP

I am trying to write a new file and return the file size and the output should be 31 in this example but i am getting 0 .(using python)

I am trying to use selenium python to click an element in chrome new tab, but I am getting error no such element even thought the element is there

I am new to python and I am trying to build a simple Tic-Tac-Tock game.When I am taking input from user it goes to infinity loop

I am trying to create a simple search, on click of a search button it should redirect to new component .but redirect is not at all working?

Why am I getting a Connection Error When Trying to Create a New SQL Server Database?

I am trying to create a new virtual machine in bluemix, getting an error about network name not existing

I am trying to create a VBA macro that duplicates a worksheet and then copies data in the worksheet to a new column

I am trying to use the mutate function with conditions to create a new column from existing data

i am trying to access a column in a dataframe and manipulate it and create new column in the data ftame

I have an appointment scheduling application I am trying to create

I am New To Flutter And I am In Bind with SetState Operation, I am Trying to Organize Code in a Block By Block way but setState is not working,