evenn MORE modular

refines #1
This commit is contained in:
TheTechRobo 2021-06-06 16:32:38 -04:00
parent 0275904111
commit 3b02b703a6
3 changed files with 79 additions and 19 deletions

20
bot.py
View File

@ -48,34 +48,22 @@ async def ping(ctx):
hi2 = time.time()
await pong.edit(content=f':ping_pong: Pong! ({delta} ms)\n*Discord message edit latency: {hi2 - hi1}*')
@bot.command(name="hypixel",aliases=("h","stats"))
async def hypixel(ctx,player):
async def hypixel(ctx,player,ConvertToUUID=True):
"""
Checks overall stats
Change ConvertToUUID to False if you want to pass in the UUID, example: `$h <UUID> False` instead of `$h <PlayerName>`.
"""
if checkapi(HYPIXEL_API_KEY) is False:
await ctx.send(_(":warning: Ran out of API queries per minute. Please wait a little while before continuing..."))
return False
thing = await ctx.send(_("Fetching player data... If this message doesn't go away, the bot is _definitely_ not broken. :soundsrightbud:"))
req = requests.get(f"https://api.hypixel.net/player?uuid={getuuid(player)}&key={HYPIXEL_API_KEY}")
contents = json.loads(req.text)
if contents['success'] is False:
await thing.edit(content=_("Invalid player name!"))
contents = contents['player']
for i in ("prefix","rank","monthlyPackageRank","newPackageRank"):
try:
contents['rank'] = contents[i]
except KeyError:
continue
try:
contents['rank']
except KeyError:
contents['rank'] = None
contents = overall(HYPIXEL_API_KEY,player,ConvertToUUID)
print(contents)
em = discord.Embed(
title=f"{contents['displayname']}'{_('s Hypixel Stats')}",
footer=_("Thanks for using Hypibot!"))
em.add_field(name=_("UUID"),value=getuuid(player),inline=True)
em.add_field(name="Rank", value=translaterank(contents['rank']),inline=True)
em.add_field(name="Rank", value=contents['rank'],inline=True)
await thing.edit(embed=em, content="Player data down below.")
# }}}
# {{{ Run bot

View File

@ -1,11 +1,13 @@
import requests, json
from .errors import *
def getuuid(username):
"""
Gets the UUID of a player from their username, using the Mojang API
"""
req = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}").text
req = json.loads(req)
return req['id']
req = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}")
if req.status_code == 204:
raise InvalidPlayer(username)
return json.loads(req.text)['id']
def translaterank(rank):
"""
Takes the rank. You need to find the rank on your own.
@ -28,3 +30,69 @@ def checkapi(key):
req = json.loads(req)
if req['record']['queriesInPastMin'] >= 120:
return False
def overall(HYPIXEL_API_KEY,player,TranslateRank=True,ConvertToUUID=True):
"""
Downloads main player stats, gets the correct rank.
If you don't want it to translate it (from e.g. SUPERSTAR to [MVP++], VIP_PLUS to [VIP+], etc), set TranslateRank to False. (It will still add the correct rank to the dictionary.)
If you'd like to get the UUID yourself, instead of setting "player" variable to the username, set ConvertToUUID to False. That will skip changing the player variable into a UUID.
It is not async since it is meant to be used in any module, not just discord.py.
"""
if ConvertToUUID:
player = getuuid(player)
req = requests.get(f"https://api.hypixel.net/player?uuid={player}&key={HYPIXEL_API_KEY}")
contents = json.loads(req.text)
if contents['success'] is False:
raise UnknownError(contents)
contents = contents['player']
for i in ("prefix","rank","monthlyPackageRank","newPackageRank"):
try:
contents['rank'] = contents[i]
except KeyError:
continue
try:
contents['rank']
except KeyError:
contents['rank'] = None
if TranslateRank: contents['rank'] = translaterank(contents['rank'])
return contents
def friends(HYPIXEL_API_KEY,player,Uuid=False):
"""If you'd like to get the UUID yourself, instead of setting "player" variable to the username, set Uuid to True. That will skip changing the username into a UUID.
Additionally, it doesn't get any other player data, such as the rank, or any information about the friends (including their names - all it gives is the UUIDs of the sender and the receiver!). For those, you may want to use the overall() function."""
if not Uuid: player = getuuid(player)
req = json.loads(requests.get(f"https://api.hypixel.net/friends?key={HYPIXEL_API_KEY}&uuid={player}").text)
if req['success'] is False:
raise UnknownError(req)
return req
def recentgames(HYPIXEL_API_KEY,player,Uuid=False):
"""If you'd like to provide the UUID yourself, set Uuid to True. That'll skip the conversion of username provided to UUID."""
if not Uuid: player = getuuid(player)
req = json.loads(requests.get(f"https://api.hypixel.net/recentgames?key={HYPIXEL_API_KEY}&uuid={player}").text)
if req['success'] is False:
raise UnknownError(req)
return req
def status(HYPIXEL_API_KEY,player,Uuid=False):
"""If you'd like to provide the UUID yourself, set Uuid to True. That'll skip the conversion of username provided to UUID.
WARNING: Hypixel allows players to disable this api access, in which case it'll look like they're offline. For more info, see https://github.com/HypixelDev/PublicAPI/wiki/Common-Questions."""
if not Uuid: player = getuuid(player)
req = json.loads(requests.get(f"https://api.hypixel.net/status?key={HYPIXEL_API_KEY}&uuid={player}").text)
if req['success'] is False:
raise UnknownError(req)
return req
def guild(HYPIXEL_API_KEY,data,TYPE):
"""
This one's a bit complicated.
Set TYPE to "id" to retrieve the guild data by its ID.
Set TYPE to "player" to retrieve the guild data by a member's UUID. (This function does NOT change a username to a UUID; you can do that yourself with the getuuid function included in this module.
Set TYPE to "name" to retrieve the guild data by its name.
DATA should be set to the guild ID, player UUID, or guild name, depending on the TYPE you chose.
URL used: f"https://api.hypixel.net/guild?key={HYPIXEL_API_KEY}&{TYPE}={data}
"""
req = json.loads(requests.get(f"https://api.hypixel.net/guild?key={HYPIXEL_API_KEY}&{TYPE}={data}").text)
if req['success'] is False: raise UnknownError(req)
return req
def RestOfTheFunctions():
"""
The rest of the functions are still a work in progress.
"""
raise BaseException

View File

@ -0,0 +1,4 @@
class InvalidPlayer(Exception):
pass
class UnknownError(Exception):
pass