proper error handling for when the api is down
This commit is contained in:
parent
c667212b0b
commit
dffb5257f9
28
bot.py
28
bot.py
|
@ -3,6 +3,7 @@ import discord, requests, json, time
|
|||
from discord.ext import commands
|
||||
from hypixel_bot_tools import *
|
||||
import hypixel_bot_tools.errors
|
||||
hypierror = hypixel_bot_tools.errors
|
||||
# }}}
|
||||
# {{{ Get token
|
||||
try:
|
||||
|
@ -60,7 +61,7 @@ async def hypixel(ctx,player,ConvertToUUID=True):
|
|||
thing = await ctx.send(_("Fetching player data... If this message doesn't go away, the bot is _definitely_ not broken. :soundsrightbud:"))
|
||||
try:
|
||||
contents = overall(HYPIXEL_API_KEY,player,ConvertToUUID)
|
||||
except hypixel_bot_tools.errors.InvalidPlayer:
|
||||
except hypierror.InvalidPlayer:
|
||||
await thing.edit(content=_(":warning: Invalid player!"));raise
|
||||
lenfriends = countfriends(friends(HYPIXEL_API_KEY,player,ConvertToUUID))
|
||||
try:
|
||||
|
@ -97,11 +98,34 @@ async def hypixel(ctx,player,ConvertToUUID=True):
|
|||
em.add_field(name=_("Network Level"),value=f"{round(RawXPToLevel(contents['networkExp']),2)} ({_('raw')} {contents['networkExp']})",inline=True)
|
||||
em.add_field(name=_("Karma"),value=contents['karma'],inline=True)
|
||||
em.add_field(name=_("Friends"),value=lenfriends,inline=True)
|
||||
em.add_field(name="\u200b",value="\u200b",inline=False)#newline; \u200b is a zero width space that is allowed by dcord
|
||||
em.add_field(name="\u200b",value="\u200b",inline=True)#newline; \u200b is a zero width space that is allowed by dcord
|
||||
em.add_field(name=_("Online?"),value=statusAPI_Message,inline=True)
|
||||
em.add_field(name=_("Current Game"),value=currentStatus_Message,inline=True)
|
||||
await thing.edit(embed=em, content="Player data down below.")
|
||||
# }}}
|
||||
# Error handling {{{
|
||||
@bot.event
|
||||
async def on_command_error(ctx, error):
|
||||
"""
|
||||
Does some stuff in case of cooldown error.
|
||||
Stolen from brewbot.
|
||||
"""
|
||||
if hasattr(ctx.command, 'on_error'): #https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612
|
||||
return
|
||||
error = getattr(error, 'original', error)
|
||||
if isinstance(error, commands.CommandOnCooldown):
|
||||
potentialMessages = [f'This command is on cooldown, please wait {int(error.retry_after)}s.']
|
||||
await ctx.send(random.choice(potentialMessages))
|
||||
print('\nSomeone tried to do a command that was on cooldown')
|
||||
return
|
||||
if isinstance(error, hypierror.HypixelApiDown):
|
||||
await ctx.send(":warning: Oops! :warning:\nWe couldn't contact the hypixel API. Is the service down?")
|
||||
return
|
||||
else:
|
||||
await ctx.send(error)
|
||||
await ctx.send(isinstance(error,hypierror.HypixelApiDown))
|
||||
raise(error)
|
||||
# }}}
|
||||
# {{{ Run bot
|
||||
if __name__ == "__main__":
|
||||
bot.run(DISCORD_API_KEY)
|
||||
|
|
|
@ -27,7 +27,10 @@ def checkapi(key):
|
|||
Checks if the API key is exhausted from requests; if so, returns False. If not, returns None.
|
||||
"""
|
||||
req = requests.get(f"https://api.hypixel.net/key?key={key}").text
|
||||
req = json.loads(req)
|
||||
try:
|
||||
req = json.loads(requests.get(f"https://api.hypixel.net/key?key={key}").text)
|
||||
except Exception as ename:
|
||||
raise HypixelApiDown("Couldn't contact the server. (%s)"%ename)
|
||||
if req['record']['queriesInPastMin'] >= 120:
|
||||
return False
|
||||
|
||||
|
@ -40,8 +43,11 @@ def overall(HYPIXEL_API_KEY,player,TranslateRank=True,ConvertToUUID=True):
|
|||
"""
|
||||
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)
|
||||
try:
|
||||
req = requests.get(f"https://api.hypixel.net/player?uuid={player}&key={HYPIXEL_API_KEY}")
|
||||
contents = json.loads(req.text)
|
||||
except Exception as ename:
|
||||
raise HypixelApiDown("Couldn't contact the server. (%s)"%ename)
|
||||
if contents['success'] is False:
|
||||
raise UnknownError(contents)
|
||||
contents = contents['player']
|
||||
|
@ -65,7 +71,10 @@ def friends(HYPIXEL_API_KEY,player,ConvertToUUID=True):
|
|||
"""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 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 ConvertToUUID: player = getuuid(player)
|
||||
req = json.loads(requests.get(f"https://api.hypixel.net/friends?key={HYPIXEL_API_KEY}&uuid={player}").text)
|
||||
try:
|
||||
req = json.loads(requests.get(f"https://api.hypixel.net/friends?key={HYPIXEL_API_KEY}&uuid={player}").text)
|
||||
except Exception as ename:
|
||||
raise HypixelApiDown("Couldn't contact the server. (%s)"%ename)
|
||||
if req['success'] is False:
|
||||
raise UnknownError(req)
|
||||
return req
|
||||
|
@ -77,7 +86,10 @@ def countfriends(data):
|
|||
def recentgames(HYPIXEL_API_KEY,player,ConvertToUUID=True):
|
||||
"""If you'd like to provide the UUID yourself, set ConvertToUUID to False. That'll skip the conversion of username provided to UUID."""
|
||||
if ConvertToUUID: player = getuuid(player)
|
||||
req = json.loads(requests.get(f"https://api.hypixel.net/recentgames?key={HYPIXEL_API_KEY}&uuid={player}").text)
|
||||
try:
|
||||
req = json.loads(requests.get(f"https://api.hypixel.net/recentgames?key={HYPIXEL_API_KEY}&uuid={player}").text)
|
||||
except Exception as ename:
|
||||
raise HypixelApiDown("Couldn't contact the server. (%s)"%ename)
|
||||
if req['success'] is False:
|
||||
raise UnknownError(req)
|
||||
return req
|
||||
|
@ -85,7 +97,10 @@ def status(HYPIXEL_API_KEY,player,ConvertToUUID=True):
|
|||
"""If you'd like to provide the UUID yourself, set ConvertToUUID to False. 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 ConvertToUUID: player = getuuid(player)
|
||||
req = json.loads(requests.get(f"https://api.hypixel.net/status?key={HYPIXEL_API_KEY}&uuid={player}").text)
|
||||
try:
|
||||
req = json.loads(requests.get(f"https://api.hypixel.net/status?key={HYPIXEL_API_KEY}&uuid={player}").text)
|
||||
except Exception as ename:
|
||||
raise HypixelApiDown("Couldn't contact the server. (%s)"%ename)
|
||||
if req['success'] is False:
|
||||
raise UnknownError(req)
|
||||
return req
|
||||
|
@ -98,7 +113,10 @@ def guild(HYPIXEL_API_KEY,data,TYPE):
|
|||
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)
|
||||
try:
|
||||
req = json.loads(requests.get(f"https://api.hypixel.net/guild?key={HYPIXEL_API_KEY}&{TYPE}={data}").text)
|
||||
except Exception as ename:
|
||||
raise HypixelApiDown("Couldn't contact the server. (%s)"%ename)
|
||||
if req['success'] is False: raise UnknownError(req)
|
||||
return req
|
||||
def _sqrt(num): return num ** 0.5
|
||||
|
@ -113,4 +131,4 @@ def RestOfTheFunctions():
|
|||
"""
|
||||
The rest of the functions are still a work in progress.
|
||||
"""
|
||||
raise BaseException
|
||||
raise BaseException("You dare run me?! I'll crash your program!")
|
||||
|
|
|
@ -2,3 +2,5 @@ class InvalidPlayer(Exception):
|
|||
pass
|
||||
class UnknownError(Exception):
|
||||
pass
|
||||
class HypixelApiDown(Exception):
|
||||
pass
|
||||
|
|
Loading…
Reference in New Issue