I have looked all over the web, and couldn't find an answer. I also asked my friend but he didn't know how to do this command. How can I make this level code display in a leaderboard command?
Here is my code:
#client.event
async def on_message(message):
if not message.author.bot:
print('function load')
with open('level.json','r') as f:
users = json.load(f)
print('file load')
await update_data(users, message.author,message.guild)
await add_experience(users, message.author, 4, message.guild)
await level_up(users, message.author,message.channel, message.guild)
with open('level.json','w') as f:
json.dump(users, f)
await client.process_commands(message)
async def update_data(users, user,server):
if not str(server.id) in users:
users[str(server.id)] = {}
if not str(user.id) in users[str(server.id)]:
users[str(server.id)][str(user.id)] = {}
users[str(server.id)][str(user.id)]['experience'] = 0
users[str(server.id)][str(user.id)]['level'] = 1
elif not str(user.id) in users[str(server.id)]:
users[str(server.id)][str(user.id)] = {}
users[str(server.id)][str(user.id)]['experience'] = 0
users[str(server.id)][str(user.id)]['level'] = 1
async def add_experience(users, user, exp, server):
users[str(user.guild.id)][str(user.id)]['experience'] += exp
async def level_up(users, user, channel, server):
experience = users[str(user.guild.id)][str(user.id)]['experience']
lvl_start = users[str(user.guild.id)][str(user.id)]['level']
lvl_end = int(experience ** (1/4))
if str(user.guild.id) != '757383943116030074':
if lvl_start < lvl_end:
await channel.send('{} has leveled up to Level {}'.format(user.mention, lvl_end))
users[str(user.guild.id)][str(user.id)]['level'] = lvl_end
#client.command(aliases = ['rank','lvl'])
async def level(ctx,member: discord.Member = None):
if not member:
user = ctx.message.author
with open('level.json','r') as f:
users = json.load(f)
lvl = users[str(ctx.guild.id)][str(user.id)]['level']
exp = users[str(ctx.guild.id)][str(user.id)]['experience']
endXP = (lvl + 1) ** 4
embed = discord.Embed(title = 'Level {}'.format(lvl), description = f"{exp} XP / {endXP} XP" ,color = discord.Color.green())
embed.set_author(name = ctx.author, icon_url = ctx.author.avatar_url)
await ctx.send(embed = embed)
else:
with open('level.json','r') as f:
users = json.load(f)
lvl = users[str(ctx.guild.id)][str(member.id)]['level']
exp = users[str(ctx.guild.id)][str(member.id)]['experience']
endXP = (lvl + 1) ** 4
embed = discord.Embed(title = 'Level {}'.format(lvl), description = f"{exp} XP / {endXP} XP" ,color = discord.Color.green())
embed.set_author(name = member, icon_url = member.avatar_url)
await ctx.send(embed = embed)
Another thing. Most of the people that comment on my posts nowadays comment about a certain question that has nothing to do with what I'm asking. If you want to bombard me with those comments, go do it in the question, not on this post. Thank you :)
#client.command()
async def leaderboard(ctx, x=10):
with open('level.json', 'r') as f:
users = json.load(f)
leaderboard = {}
total=[]
for user in list(users[str(ctx.guild.id)]):
name = int(user)
total_amt = users[str(ctx.guild.id)][str(user)]['experience']
leaderboard[total_amt] = name
total.append(total_amt)
total = sorted(total,reverse=True)
em = discord.Embed(
title = f'Top {x} highest leveled members in {ctx.guild.name}',
description = 'The highest leveled people in this server'
)
index = 1
for amt in total:
id_ = leaderboard[amt]
member = client.get_user(id_)
em.add_field(name = f'{index}: {member}', value = f'{amt}', inline=False)
if index == x:
break
else:
index += 1
await ctx.send(embed = em)
here is some code that may help
Related
this is the full error of the code
i would really love the help
mainshop = [{"name":"Time_watch","price":1000,"description":"Resets certain cooldowns (limited uses)(WIP)"}, {"name":"Gun","price":10000,"description":"A better way to rob people with a shorter cooldown!"}, {"name":"Guhhh Placeholder!!","price":10000000,"description":"I sure love placeholders"}]
#client.command()
#commands.is_owner()
async def shop(ctx):#real#:troll:.name
em = discord.Embed(title = "Shopping District")
for item in mainshop:
name = item["name"]
price = item["price"]
desc = item["description"] #i do believe its because you have like no DESCRIPTION in the item list thing
#get fake
em.add_field(name = name, value = f"${price} | {desc}")
#real
await ctx.send(embed = em)
import discord
from discord.ext import commands
import asyncio
import os
import json
##### START LEVEL COMMAND #####
#client.command(name='bal')
async def balance(ctx, user:discord.Member=None):
colour = randint(0, 0xffffff)
await open_account(ctx.author)
if user is None:
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title=f"{user}'s balance", color=colour)
em.add_field(name="Wallet", value=wallet_amt)
em.add_field(name="Bank", value=bank_amt)
await ctx.send(embed=em)
async def buy_this(user,item_name,amount):
item_name = item_name.lower()
name_ = None
for item in mainshop:
name = item["name"].lower()
if name == item_name:
name_ = name
price = item["price"]
break
if name_ == None:
return [False,1]
cost = price*amount
users = await get_bank_data()
bal = await update_bank(user)#r.i.p. KB's confindince
if bal[0]<= cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["bag"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["bag"][index]["amount"] = new_amt
t = 1
break
index+=1
if t == None:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["bag"].append(obj)
except:
obj = {"item":item_name , "amount" : amount}
users[str(user.id)]["bag"] = [obj]
with open("mainbank.json","w") as f:
json.dump(users,f)
await update_bank(user,cost*-1,"wallet")
return [True,"Worked"]
#client.command()
async def buy(ctx,item,amount):#how come these arent definded no more? oh I prollydid smth by mistake guhhhhhhh
res = await buy_this(ctx.author,item,amount)
if not res[0]:
if res[1]==1:
await ctx.send("That is not an item in shop")
return
if res[1]==2:
await ctx.send(f"You don't have enough money to buy the {amount}")
return
await ctx.send(f"Successfully bought {amount}: {item}")
#client.command()
#commands.is_owner()
async def bag(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
try:
bag = users[str(user.id)]["bag"]
except:
bag = []
em = discord.Embed(title = "Bag")
for item in bag:
name = item["item"]
amount = item["amount"]
em.add_field(name = name, value = amount)
await ctx.send(embed = em)
#Oh you mean this ? oh yeah Idk what I put that there
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("mainbank.json", "w") as f:
json.dump(users, f)
return True
async def get_bank_data():
with open("mainbank.json", "r") as f:
users = json.load(f)
return users
async def update_bank(user, change=0, mode="wallet"):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open("mainbank.json", "w") as f:
json.dump(users, f)
bal = [users[str(user.id)]["wallet"], users[str(user.id)]["bank"]]
return bal
the code that should matter. I do not understand at all what is wrong with the code. I used this code before no errors. So if anyone could please explain that would be greatly appreciated. I have tried putting this in its own thing. it didnt work still. i have also tried putting if bal <= int(cost) this also didnt work.
on the line if bal[0]<= cost: if you cast to an integer int(bal[0]) it should be comparing two integers then, and vice-versa if cost is a string
Cost is already an int, looks like bal[0] is a string. Try int(bal[0]) <= cost instead (or float(bal[0]) if it has decimals)
This is my event that configures levels for each member and stores the information in a JSON file. I would like a leaderboard that lists the top 10 people with the highest level but I am unsure how to go about doing this. Thanks in advance.
class on_message(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_message(self, message):
channel = self.bot.get_channel(config.server_chat)
with open("users.json", "r") as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 1)
await level_up(users, message.author, message, channel)
with open("users.json", "w") as f:
json.dump(users, f)
async def update_data(users, user):
if not str(user.id) in users:
users[str(user.id)] = {}
users[str(user.id)]["experience"] = 0
users[str(user.id)]["level"] = 1
users[str(user.id)]["messages"] = 0
async def add_experience(users, user, exp):
users[str(user.id)]["experience"] += exp
users[str(user.id)]["messages"] += exp
async def level_up(users, user, message, channel):
experience = users[str(user.id)]["experience"]
lvl_start = users[str(user.id)]["level"]
lvl_end = int(lvl_start * 5)
update = lvl_start + 1
if experience >= lvl_end:
users[str(user.id)]["experience"] = 0
users[str(user.id)]["level"] = lvl_start + 1
if not message.author.bot:
lvl = users[str(user.id)]["level"]
await channel.send(f"**{user.mention} reached level {update}**")
def setup(bot):
bot.add_cog(on_message(bot))
You can sort JSON data and get first 10 users:
#commands.command()
async def leaderboard(self, ctx):
with open("users.json", "w") as f:
data = json.load(f)
embed = discord.Embed(title="Leaderboard")
for user_id, user_data in sorted(data.items(), key=lambda x: x[1]['experience'], reverse=True)[:10]:
embed.add_field(name=self.bot.get_user(user_id), value=f"Experience: {user_data['experience']}\nLevel: {user_data['level']}", inline=False)
await ctx.send(embed=embed)
Hi I was wondering how I would make a leaderboard cmd in discord.py rewrite I have a fully working lvling system but I'm wondering how to show the top ten ppl that are the highest lvl. I tried this but nothing comes up when I type -leaderboard ok so I need to type more to upload this so just ignore what I'm typing now damn I need to write even more ok is this enough hopfully
async def leaderboard(ctx):
with open('users.json', 'r') as f:
data = json.load(f)
top_users = {k: v for k, v in sorted(data.items(), key=lambda item: item[1], reverse=True)}
names = ''
for postion, user in enumerate(top_users):
# add 1 to postion to make the index start from 1
names += f'{postion+1} - <#!{user}> with {top_users[user]}\n'
embed = discord.Embed(title="Leaderboard")
embed.add_field(name="Names", value=names, inline=False)
await ctx.send(embed=embed)
in my users.json folder its user id then xp then lvl.
here is the code for my mainfile
#client.event
async def on_member_join(member):
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, member)
with open('users.json', 'w') as f:
json.dump(users, f)
#client.event
async def on_message(message):
if message.author.bot == False:
with open('users.json', 'r') as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message)
with open('users.json', 'w') as f:
json.dump(users, f)
await client.process_commands(message)
async def update_data(users, user):
if not f'{user.id}' in users:
users[f'{user.id}'] = {}
users[f'{user.id}']['experience'] = 0
users[f'{user.id}']['level'] = 1
async def add_experience(users, user, exp):
users[f'{user.id}']['experience'] += exp
async def level_up(users, user, message):
with open('levels.json', 'r') as g:
levels = json.load(g)
experience = users[f'{user.id}']['experience']
lvl_start = users[f'{user.id}']['level']
lvl_end = int(experience ** (1 / 4))
if lvl_start < lvl_end:
await message.channel.send(f'{user.mention} has leveled up to level {lvl_end}')
users[f'{user.id}']['level'] = lvl_end
#client.command()
async def level(ctx, member: discord.Member = None):
if not member:
id = ctx.message.author.id
with open('users.json', 'r') as f:
users = json.load(f)
lvl = users[str(id)]['level']
await ctx.send(f'You are at level {lvl}!')
else:
id = member.id
with open('users.json', 'r') as f:
users = json.load(f)
lvl = users[str(id)]['level']
await ctx.send(f'{member} is at level {lvl}!')
Remember that commands in discord.py should use the command decorator to specify that the function is meant to be processed as a command.
Therefore, in your main file, please add:
#client.command()
async def leaderboard(ctx):
with open('users.json', 'r') as f:
data = json.load(f)
top_users = {k: v for k, v in sorted(data.items(), key=lambda item: item[1], reverse=True)}
names = ''
for postion, user in enumerate(top_users):
# add 1 to postion to make the index start from 1
names += f'{postion+1} - <#!{user}> with {top_users[user]}\n'
embed = discord.Embed(title="Leaderboard")
embed.add_field(name="Names", value=names, inline=False)
await ctx.send(embed=embed)
The client.command() decorator has been added here.
I want do add a Role which will gave to everyone who reach lvl 5. I already tried something but that didnt worked. Has somebody an idea how to start?
The stats got saved in a .json file like this:
{"719479402953572383": {"504641949068689430": {"experience": 8, "level": 1}}}
async def on_message(message):
if not message.author.bot:
print('function load')
with open('level.json','r') as f:
users = json.load(f)
print('file load')
await update_data(users, message.author,message.guild)
await add_experience(users, message.author, 4, message.guild)
await level_up(users, message.author,message.channel, message.guild)
with open('level.json','w') as f:
json.dump(users, f)
await bot.process_commands(message)
async def update_data(users, user,server):
if not str(server.id) in users:
users[str(server.id)] = {}
if not str(user.id) in users[str(server.id)]:
users[str(server.id)][str(user.id)] = {}
users[str(server.id)][str(user.id)]['experience'] = 0
users[str(server.id)][str(user.id)]['level'] = 1
elif not str(user.id) in users[str(server.id)]:
users[str(server.id)][str(user.id)] = {}
users[str(server.id)][str(user.id)]['experience'] = 0
users[str(server.id)][str(user.id)]['level'] = 1
async def add_experience(users, user, exp, server):
users[str(user.guild.id)][str(user.id)]['experience'] += exp
async def level_up(users, user, channel, server):
experience = users[str(user.guild.id)][str(user.id)]['experience']
lvl_start = users[str(user.guild.id)][str(user.id)]['level']
lvl_end = int(experience ** (1/4))
if str(user.guild.id) != '757383943116030074':
if lvl_start < lvl_end:
await channel.send('{} has leveled up to Level {}'.format(user.mention, lvl_end))
users[str(user.guild.id)][str(user.id)]['level'] = lvl_end```
I've been trying to make an economy system in discord.py. However, the system is not working whatsoever. Whenever I type in the !balance command it doesn't send an embed at all. It doesn't even give an error. Here is my code:
#client.command()
async def balance(ctx):
user = ctx.author
await open_account(ctx.author)
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
embed=discord.Embed(title=f"{ctx.author.name}'s Balance")
embed.add_field(name="Wallet:", value=wallet_amt, inline=False)
embed.add_field(name="Bank:", value=bank_amt, inline=False)
await ctx.send(embed=embed)
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = []
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("bank.json", "w") as f:
json.dump(users, f)
return True
async def get_bank_data():
with open("bank.json", "r") as f:
users = json.load(f)
return users
Can anyone help me identify the error? I'm quite new to discord.py
Your open_account() function's logic will always return True even if the if condition passes because the indentation is backed off. If it is linked with the way you retrieve the data this might be your issue.
#client.command(aliases=['bal'])
async def balance(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title=f'{ctx.author.name} Balance',color = discord.Color.red())
em.add_field(name="Wallet Balance", value=wallet_amt)
em.add_field(name='Bank Balance',value=bank_amt)
await ctx.send(embed= em)
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open('mainbank.json','w') as f:
json.dump(users,f)
return True
async def get_bank_data():
with open('mainbank.json','r') as f:
users = json.load(f)
return users
This should work change the json file name to the correct one,
one important thing , check your saving functions and file content too