[WarcraftLogs] WCL 2.0

This commit is contained in:
aikaterna
2021-01-20 15:01:43 -08:00
parent d8c29b09b4
commit 2cd7f03f1b
12 changed files with 2712 additions and 357 deletions

View File

@@ -1,4 +1,5 @@
from .warcraftlogs import WarcraftLogs
from redbot.core.bot import Red
from .core import WarcraftLogs
__red_end_user_data_statement__ = (
"This cog stores data provided by users "
@@ -12,5 +13,7 @@ __red_end_user_data_statement__ = (
)
def setup(bot):
bot.add_cog(WarcraftLogs(bot))
async def setup(bot: Red) -> None:
cog = WarcraftLogs(bot)
await cog._create_client()
bot.add_cog(cog)

74
warcraftlogs/calls.py Normal file
View File

@@ -0,0 +1,74 @@
# Most of the source of this file can be found at: https://github.com/Kowlin/GraphQL-WoWLogs/blob/master/wowlogs/calls.py
class Queries:
get_last_encounter = """
query ($char_realm: String!, $char_name: String!, $char_server: String!) {
rateLimitData {
limitPerHour
pointsSpentThisHour
pointsResetIn
}
characterData {
character(name: $char_name, serverSlug: $char_realm, serverRegion: $char_server) {
name
id
classID
recentReports(limit: 1) {
data {
fights(killType: Kills) {
encounterID
name
endTime
}
}
}
}
}
}
"""
get_overview = """
query ($char_realm: String!, $char_name: String!, $char_server: String!, $zone_id: Int!) {
rateLimitData {
limitPerHour
pointsSpentThisHour
pointsResetIn
}
characterData {
character(name: $char_name, serverSlug: $char_realm, serverRegion: $char_server) {
name
id
zoneRankings(zoneID: $zone_id)
}
}
}
"""
get_gear = """
query($char_realm: String!, $char_name: String!, $char_server: String!, $encounter: Int!) {
rateLimitData {
limitPerHour
pointsSpentThisHour
pointsResetIn
}
characterData {
character(name: $char_name, serverSlug: $char_realm, serverRegion: $char_server) {
name
id
classID
encounterRankings(includeCombatantInfo: true, byBracket: true, encounterID: $encounter)
}
}
}
"""
check_bearer = """
query {
rateLimitData {
limitPerHour
pointsSpentThisHour
pointsResetIn
}
}
"""

610
warcraftlogs/core.py Normal file
View File

@@ -0,0 +1,610 @@
# Most of the source of this file for the actual API mechanics can be found at:
# https://github.com/Kowlin/GraphQL-WoWLogs/blob/master/wowlogs/core.py
import discord
import io
import logging
import math
from redbot.core import checks, commands, Config
from redbot.core.bot import Red
from redbot.core.data_manager import bundled_data_path
from redbot.core.utils.chat_formatting import box
from beautifultable import ALIGN_LEFT, BeautifulTable
from datetime import datetime
from PIL import ImageFont, ImageDraw, Image
from typing import Literal, Mapping, Optional
from .enchantid import ENCHANT_ID
from .encounterid import ZONES_BY_ID, ZONES_BY_SHORT_NAME
from .http import WoWLogsClient, generate_bearer
log = logging.getLogger("red.aikaterna.warcraftlogs")
WCL_URL = "https://classic.warcraftlogs.com/reports/{}"
class WarcraftLogs(commands.Cog):
"""Retrieve World of Warcraft Classic character information from WarcraftLogs."""
def __init__(self, bot):
self.bot: Red = bot
self.config = Config.get_conf(self, identifier=2713931002, force_registration=True)
self.http: WoWLogsClient = None
self.path = bundled_data_path(self)
self.config.register_global(bearer_timestamp=0)
default_user = {
"charname": None,
"realm": None,
"region": None,
}
self.config.register_user(**default_user)
async def _create_client(self) -> None:
self.http = WoWLogsClient(bearer=await self._get_bearer())
bearer_status = await self.http.check_bearer()
if bearer_status is False:
await generate_bearer(self.bot, self.config)
await self.http.recreate_session(await self._get_bearer())
async def _get_bearer(self) -> str:
api_tokens = await self.bot.get_shared_api_tokens("warcraftlogs")
bearer = api_tokens.get("bearer", "")
bearer_timestamp = await self.config.bearer_timestamp()
timestamp_now = int(datetime.utcnow().timestamp())
if timestamp_now > bearer_timestamp:
log.info("Bearer token has expired. Generating one")
bearer = await generate_bearer(self.bot, self.config)
elif not bearer:
log.info("Bearer token doesn't exist. Generating one")
bearer = await generate_bearer(self.bot, self.config)
if bearer is None:
return
return bearer
def cog_unload(self) -> None:
self.bot.loop.create_task(self.http.session.close())
async def red_get_data_for_user(self, **kwargs):
return {}
async def red_delete_data_for_user(
self, *, requester: Literal["discord", "owner", "user", "user_strict"], user_id: int
):
await self.config.user_from_id(user_id).clear()
@commands.bot_has_permissions(embed_links=True)
@commands.command()
async def getgear(self, ctx, name: str = None, realm: str = None, *, region: str = None):
"""
Fetch a character's gear.
Examples:
[p]getgear Username Atiesh US
[p]getgear Username Nethergarde Keep EU
This is provided from the last log entry for a user that includes gear data.
Not every log has gear data.
Enchants can be shown - if the log provides them.
"""
userdata = await self.config.user(ctx.author).all()
if not name:
name = userdata["charname"]
if not name:
return await ctx.send("Please specify a character name with this command.")
if not realm:
realm = userdata["realm"]
if not realm:
return await ctx.send("Please specify a realm name with this command.")
if not region:
region = userdata["region"]
if not region:
return await ctx.send("Please specify a region name with this command.")
if len(region.split(" ")) > 1:
presplit = region.split(" ")
realm = f"{realm}-{presplit[0]}"
region = presplit[1]
name = name.title()
realm = realm.title()
region = region.upper()
# Get the user's last raid encounters
encounters = await self.http.get_last_encounter(name, realm, region)
if encounters is False:
# the user wasn't found on the API.
return await ctx.send(f"{name} wasn't found on the API.")
error = encounters.get("error", None)
if error:
return await ctx.send(f"WCL API Error: {error}")
if encounters is None:
return await ctx.send("The bearer token was invalidated for some reason.")
char_data = await self.http.get_gear(name, realm, region, encounters["latest"])
if not char_data:
return await ctx.send("Check your API token and make sure you have added it to the bot correctly.")
gear = None
if char_data is None:
# Assuming bearer has been invalidated.
await self._create_client()
if len(char_data["encounterRankings"]["ranks"]) != 0:
# Ensure this is the encounter that has gear listed. IF its not, we're moving on with the other encounters.
gear = char_data["encounterRankings"]["ranks"][0]["gear"]
else:
encounters["ids"].remove(encounters["latest"])
for encounter in encounters["ids"]:
char_data = await self.http.get_gear(name, realm, region, encounter)
if len(char_data["encounterRankings"]["ranks"]) != 0:
gear = char_data["encounterRankings"]["ranks"][0]["gear"]
break
if gear is None:
return await ctx.send(f"No gear for {name} found in the last report.")
item_list = []
item_ilevel = 0
item_count = 0
for item in gear:
if item["id"] == 0:
continue
# item can be {'name': 'Unknown Item', 'quality': 'common', 'id': None, 'icon': 'inv_axe_02.jpg'} here
rarity = self._get_rarity(item)
item_ilevel_entry = item.get("itemLevel", None)
if item_ilevel_entry:
if int(item["itemLevel"]) > 5:
item_ilevel += int(item["itemLevel"])
item_count += 1
item_list.append(f"{rarity} [{item['name']}](https://classic.wowhead.com/item={item['id']})")
perm_enchant_id = item.get("permanentEnchant", None)
temp_enchant_id = item.get("temporaryEnchant", None)
perm_enchant_text = ENCHANT_ID.get(perm_enchant_id, None)
temp_enchant_text = ENCHANT_ID.get(temp_enchant_id, None)
if perm_enchant_id:
if temp_enchant_id:
symbol = ""
else:
symbol = ""
if perm_enchant_text:
item_list.append(f"`{symbol}──` {perm_enchant_text}")
if temp_enchant_id:
if temp_enchant_text:
item_list.append(f"`└──` {temp_enchant_text}")
if item_ilevel > 0:
avg_ilevel = "{:g}".format(item_ilevel / item_count)
else:
avg_ilevel = "Unknown (not present in log data from the API)"
# embed
embed = discord.Embed()
title = f"{name.title()} - {realm.title()} ({region.upper()})"
guild_name = char_data["encounterRankings"]["ranks"][0]["guild"].get("name", None)
if guild_name:
title += f"\n{guild_name}"
embed.title = title
embed.description = "\n".join(item_list)
# embed footer
ilvl = f"Average Item Level: {avg_ilevel}\n"
encounter_spec = char_data["encounterRankings"]["ranks"][0].get("spec", None)
spec = f"Encounter spec: {encounter_spec}\n"
gear = f'Gear data pulled from {WCL_URL.format(char_data["encounterRankings"]["ranks"][0]["report"]["code"])}\n'
log = f'Log Date/Time: {self._time_convert(char_data["encounterRankings"]["ranks"][0]["startTime"])} UTC'
embed.set_footer(text=f"{spec}{ilvl}{gear}{log}")
await ctx.send(embed=embed)
@commands.bot_has_permissions(embed_links=True)
@commands.command()
async def getrank(self, ctx, name: str = None, realm: str = None, region: str = None, zone: str = None):
"""
Character rank overview.
If the realm name is two words, use a hyphen to connect the words.
Examples:
[p]getrank Username Atiesh US
[p]getrank Username Nethergarde-Keep EU
Specific Zones:
[p]getrank Username Atiesh US BWL
[p]getrank Username Nethergarde-Keep EU AQ20
Zone name must be formatted like:
Naxx, AQ40, AQ20, ZG, BWL, Ony, MC
- Only Phase 6 World Buff metrics will be displayed
"""
# someone has their data saved so they are just trying
# to look up a zone for themselves
if name:
if name.upper() in ZONES_BY_SHORT_NAME:
zone = name
name = None
realm = None
region = None
# look up any saved info
userdata = await self.config.user(ctx.author).all()
if not name:
name = userdata["charname"]
if not name:
return await ctx.send("Please specify a character name with this command.")
if not realm:
realm = userdata["realm"]
if not realm:
return await ctx.send("Please specify a realm name with this command.")
if not region:
region = userdata["region"]
if not region:
return await ctx.send("Please specify a region name with this command.")
region = region.upper()
if region not in ["US", "EU"]:
msg = "Realm names that have a space (like 'Nethergarde Keep') must be written with a hyphen, "
msg += "upper or lower case: `nethergarde-keep` or `Nethergarde-Keep`."
return await ctx.send(msg)
name = name.title()
realm = realm.title()
# fetch zone name and zone id from user input
zone_id = None
if zone:
if zone.upper() in ZONES_BY_SHORT_NAME:
zone_id = ZONES_BY_SHORT_NAME[zone.upper()][1]
zone_id_to_name = ZONES_BY_SHORT_NAME[zone.upper()][0]
if zone_id == None:
# return first raid that actually has parse info in phase 6
# as no specific zone was requested
zone_ids = list(ZONES_BY_ID.keys())
zone_ids.reverse()
for zone_number in zone_ids:
data = await self.http.get_overview(name, realm, region, zone_number)
error = data.get("error", None)
if error:
return await ctx.send(f"WCL API Error: {error}")
if (data is False) or (not data["data"]["characterData"]["character"]):
return await ctx.send(f"{name} wasn't found on the API.")
char_data = data["data"]["characterData"]["character"]["zoneRankings"]
data_test = char_data.get("bestPerformanceAverage", None)
if data_test != None:
break
else:
# try getting a specific zone's worth of info for this character
data = await self.http.get_overview(name, realm, region, zone_id)
error = data.get("error", None)
if error:
return await ctx.send(f"WCL API Error: {error}")
if (data is False) or (not data["data"]["characterData"]["character"]):
return await ctx.send(f"{name} wasn't found on the API.")
# embed and data setup
zws = "\N{ZERO WIDTH SPACE}"
space = "\N{SPACE}"
try:
char_data = data["data"]["characterData"]["character"]["zoneRankings"]
except (KeyError, TypeError):
msg = "Something went terribly wrong while trying to access the zone rankings for this character."
return await ctx.send(msg)
zone_name = await self._zone_name_from_id(char_data["zone"])
zone_name = f"{zone_name}".center(40, " ")
embed = discord.Embed()
embed.title = f"{name.title()} - {realm.title()} ({region.upper()})"
# perf averages
embed.add_field(name=zws, value=box(zone_name, lang="fix"), inline=False) ###
perf_avg = char_data.get("bestPerformanceAverage", None)
if perf_avg:
pf_avg = "{:.1f}".format(char_data["bestPerformanceAverage"])
pf_avg = self._get_color(float(pf_avg))
embed.add_field(name="Best Perf. Avg", value=pf_avg, inline=True)
else:
if zone_id:
return await ctx.send(f"Nothing found for {zone_id_to_name.title()} for this player for phase 6.")
else:
return await ctx.send("Nothing at all found for this player for phase 6.")
md_avg = "{:.1f}".format(char_data["medianPerformanceAverage"])
md_avg = self._get_color(float(md_avg))
embed.add_field(name="Median Perf. Avg", value=md_avg, inline=True)
# perf avg filler space
embed.add_field(name=zws, value=zws, inline=True)
# table setup
table = BeautifulTable(default_alignment=ALIGN_LEFT, maxwidth=500)
table.set_style(BeautifulTable.STYLE_COMPACT)
table.columns.header = [
"Name",
"Best %",
"Spec",
"DPS",
"Kills",
"Fastest",
"Med %",
"AS Pts",
"AS Rank",
]
# add rankings per encounter to table
rankings = sorted(char_data["rankings"], key=lambda k: k["encounter"]["id"])
for encounter in rankings:
all_stars = encounter["allStars"]
enc_details = encounter["encounter"]
best_amt = "{:.1f}".format(encounter["bestAmount"]) if encounter["bestAmount"] != 0 else "-"
median_pct = "{:.1f}".format(encounter["medianPercent"]) if encounter["medianPercent"] else "-"
rank_pct = "{:.1f}".format(encounter["rankPercent"]) if encounter["medianPercent"] else "-"
fastest_kill_tup = self._dynamic_time(encounter["fastestKill"] / 1000)
if fastest_kill_tup == (0, 0):
fastest_kill = "-"
else:
if len(str(fastest_kill_tup[1])) == 1:
seconds = f"0{fastest_kill_tup[1]}"
else:
seconds = fastest_kill_tup[1]
fastest_kill = f"{fastest_kill_tup[0]}:{seconds}"
table.rows.append(
(
enc_details.get("name", None),
rank_pct,
encounter["spec"],
best_amt,
encounter["totalKills"],
fastest_kill,
median_pct,
all_stars.get("points", None) if all_stars else "-",
all_stars.get("rank", None) if all_stars else "-",
)
)
# all stars
all_stars = char_data["allStars"]
section_name = f"⫷ Expansion All Stars ⫸".center(40, " ")
embed.add_field(name=zws, value=box(section_name, lang="Prolog"), inline=False)
for item in all_stars:
msg = f"**{item['spec']}**\n"
rank_percent = "{:.1f}".format(item["rankPercent"])
msg += f"Points:\n`{item['points']}`\n"
msg += f"Rank:\n`{item['rank']}`\n"
msg += f"{self._get_color(float(rank_percent), '%')}\n"
embed.add_field(name=zws, value=msg, inline=True)
# all stars filler space
if not len(all_stars) % 3 == 0:
nearest_multiple = 3 * math.ceil(len(all_stars) / 3)
else:
nearest_multiple = len(all_stars)
bonus_empty_fields = nearest_multiple - len(all_stars)
if bonus_empty_fields > 0:
for _ in range(bonus_empty_fields):
embed.add_field(name=zws, value=zws, inline=True)
# table time
table_image = await self._make_table_image(str(table))
image_file = discord.File(fp=table_image, filename="table_image.png")
embed.set_image(url=f"attachment://{image_file.filename}")
await ctx.send(file=image_file, embed=embed)
@commands.command()
async def wclcharname(self, ctx, charname: str):
"""Set your character's name."""
await self.config.user(ctx.author).charname.set(charname)
await ctx.send(f"Your character name was set to {charname.title()}.")
@commands.command()
async def wclrealm(self, ctx, *, realm: str):
"""Set your realm."""
realmname = realm.replace(" ", "-")
await self.config.user(ctx.author).realm.set(realmname)
await ctx.send(f"Your realm was set to {realm.title()}.")
@commands.command()
async def wclregion(self, ctx, region: str):
"""Set your region."""
valid_regions = ["EU", "US"]
if region.upper() not in valid_regions:
return await ctx.send("Valid regions are: {humanize_list(valid_regions)}")
await self.config.user(ctx.author).region.set(region)
await ctx.send(f"Your realm's region was set to {region.upper()}.")
@commands.command()
async def wclsettings(self, ctx, user: discord.User = None):
"""Show your current settings."""
if not user:
user = ctx.author
userinfo = await self.config.user(user).all()
msg = f"[Settings for {user.display_name}]\n"
charname = userinfo["charname"].title() if userinfo["charname"] else "None"
realmname = userinfo["realm"].title().replace("-", " ") if userinfo["realm"] else "None"
regionname = userinfo["region"].upper() if userinfo["region"] else "None"
msg += f"Character: {charname}\nRealm: {realmname}\nRegion: {regionname}\n\n"
msg += f"[Bot Permissions Needed]\n"
if ctx.message.guild.me.guild_permissions.embed_links:
msg += "[X] Embed Links permissions\n"
else:
msg += "[ ] I need Embed Links permissions\n"
await ctx.send(box(msg, lang="ini"))
@commands.command()
@checks.is_owner()
async def wclapikey(self, ctx):
"""Instructions for setting the api key."""
msg = "Set your API key by adding it to Red's API key storage.\n"
msg += "Get a key from <https://classic.warcraftlogs.com> by signing up for an account, then visit your settings.\n"
msg += "At the bottom is a section called Web API. Click on the blue link that says `manage your V2 clients here`.\n"
msg += "Do NOT sign up for a v1 API key, it will not work with this cog.\n"
msg += "Click on Create Client. Be ready to write down your information somewhere, you cannot retrive the secret after this.\n"
msg += "Enter a name (whatever you want), `https://localhost` for the redirect URL, and leave the Public Client box unchecked.\n"
msg += f"Use `{ctx.prefix}set api warcraftlogs client_id,client-id-goes-here client_secret,client-secret-goes-here` to set your key.\n"
await ctx.send(msg)
@commands.command(hidden=True)
@checks.is_owner()
async def wclrank(self, ctx):
"""[Depreciated] Fetch ranking info about a player."""
msg = "This cog has changed significantly from the last update.\n"
msg += f"Use `{ctx.prefix}help WarcraftLogs` to see all commands.\n"
msg += f"Use `{ctx.prefix}wclapikey` to see instructions on how to get the new API key.\n"
await ctx.send(msg)
@commands.command(hidden=True)
@commands.guild_only()
async def wclgear(self, ctx):
"""[Depreciated] Fetch gear info about a player."""
msg = "This cog has changed significantly from the last update.\n"
msg += f"Use `{ctx.prefix}help WarcraftLogs` to see all commands.\n"
msg += f"Use `{ctx.prefix}wclapikey` to see instructions on how to get the new API key.\n"
await ctx.send(msg)
async def _make_table_image(self, table):
image_path = str(self.path / "blank.png")
image = Image.open(image_path)
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(str(self.path / "Cousine-Regular.ttf"), 20)
x = 20
y = 0
text_lines = table.split("\n")
for text_line in text_lines:
y += 25
draw.text((x, y), text_line, font=font, fill=(255, 255, 255, 255))
image_object = io.BytesIO()
image.save(image_object, format="PNG")
image_object.seek(0)
return image_object
@staticmethod
def _dynamic_time(time_elapsed):
m, s = divmod(int(time_elapsed), 60)
return m, s
@staticmethod
def _get_rarity(item):
rarity = item["quality"]
if rarity == "common":
return ""
elif rarity == "uncommon":
return "🟩"
elif rarity == "rare":
return "🟦"
elif rarity == "epic":
return "🟪"
else:
return "🔳"
@staticmethod
def _time_convert(time):
time = str(time)[0:10]
value = datetime.fromtimestamp(int(time)).strftime("%Y-%m-%d %H:%M:%S")
return value
@staticmethod
async def _zone_name_from_id(zoneID: int):
for zone_id, zone_name in ZONES_BY_ID.items():
if zoneID == zone_id:
return zone_name
def _get_color(self, number: float, bonus=""):
if number >= 95:
# legendary
out = self._orange(number, bonus)
elif 94 >= number > 75:
# epic
out = self._red(number, bonus)
elif 75 >= number > 50:
# rare
out = self._blue(number, bonus)
elif 50 >= number > 25:
# common
out = self._green(number, bonus)
elif 25 >= number >= 0:
# trash
out = self._grey(number, bonus)
else:
# someone fucked up somewhere
out = box(number)
return out
@staticmethod
def _red(number, bonus):
output_center = f"{str(number)}{bonus}".center(8, " ")
text = f" [ {output_center} ]"
new_number = f"{box(text, lang='css')}"
return new_number
@staticmethod
def _orange(number, bonus):
output_center = f"{str(number)}{bonus}".center(8, " ")
text = f" [ {output_center} ]"
new_number = f"{box(text, lang='fix')}"
return new_number
@staticmethod
def _green(number, bonus):
output_center = f"{str(number)}{bonus}".center(8, " ")
text = f" [ {output_center} ]"
new_number = f"{box(text, lang='py')}"
return new_number
@staticmethod
def _blue(number, bonus):
output_center = f"{str(number)}{bonus}".center(8, " ")
text = f" [ {output_center} ]"
new_number = f"{box(text, lang='ini')}"
return new_number
@staticmethod
def _grey(number, bonus):
output_center = f"{str(number)}{bonus}".center(8, " ")
text = f" [ {output_center} ]"
new_number = f"{box(text, lang='bf')}"
return new_number
@commands.Cog.listener()
async def on_red_api_tokens_update(self, service_name: str, api_tokens: Mapping[str, str]):
"""Lifted shamelessly from GHC. Thanks Kowlin for this and everything else you did on this cog."""
if service_name != "warcraftlogs":
return
await self.http.recreate_session(await self._get_token(api_tokens))
async def _get_token(self, api_tokens: Optional[Mapping[str, str]] = None) -> str:
"""Get WCL bearer token."""
if api_tokens is None:
api_tokens = await self.bot.get_shared_api_tokens("warcraftlogs")
bearer = api_tokens.get("bearer", None)
if not bearer:
log.info("No valid token found, trying to create one.")
await generate_bearer(self.bot, self.config)
return await self._get_bearer()
else:
return bearer

Binary file not shown.

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2010-2012 Google Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,7 @@
Cousine-Regular.ttf
Cousine was designed by Steve Matteson as an innovative, refreshing sans serif design that is metrically compatible with Courier New™.
Cousine offers improved on-screen readability characteristics and the pan-European WGL character set and solves the needs of developers looking for width-compatible
fonts to address document portability across platforms.
Digitized data copyright (c) 2010-2012 Google Corporation.

BIN
warcraftlogs/data/blank.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

1542
warcraftlogs/enchantid.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,91 @@
ENCOUNTER_ID = {
610: "Razorgore the Untamed",
611: "Vaelastrasz the Corrupt",
612: "Broodlord Lashlayer",
613: "Firemaw",
614: "Ebonroc",
615: "Flamegor",
616: "Chromaggus",
617: "Nefarian",
663: "Lucifron",
664: "Magmadar",
665: "Gehennas",
666: "Garr",
667: "Shazzrah",
668: "Baron Geddon",
669: "Sulfuron Harbinger",
670: "Golemagg the Incinerator",
671: "Majordomo Executus",
672: "Ragnaros",
709: "The Prophet Skeram",
710: "Silithid Royalty",
711: "Battleguard Sartura",
712: "Fankriss the Unyielding",
713: "Viscidus",
714: "Princess Huhuran",
715: "Twin Emperors",
716: "Ouro",
717: "C'thun",
718: "Kurinnaxx",
719: "General Rajaxx",
720: "Moam",
721: "Buru the Gorger",
722: "Ayamiss the Hunter",
723: "Ossirian the Unscarred",
784: "High Priest Venoxis",
785: "High Priestess Jeklik",
786: "High Priestess Mar'li",
787: "Bloodlord Mandokir",
788: "Edge of Madness",
789: "High Priest Thekal",
790: "Gahz'ranka",
791: "High Priestess Arlokk",
792: "Jin'do the Hexxer",
793: "Hakkar",
1084: "Onyxia",
1107: "Anub'Rekhan",
1108: "Gluth",
1109: "Gothik the Harvester",
1110: "Grand Widow Faerlina",
1111: "Grobbulus",
1112: "Heigan the Unclean",
1113: "Instructor Razuvious",
1114: "Kel'Thuzad",
1115: "Loatheb",
1116: "Maexxna",
1117: "Noth the Plaguebringer",
1118: "Patchwerk",
1119: "Sapphiron",
1120: "Thaddius",
1121: "The Four Horsemen",
}
ENCOUNTER_ZONES = {
"Molten Core": [663, 664, 665, 666, 667, 668, 669, 670, 671, 672],
"Onyxia": [1084],
"Blackwing Lair": [610, 611, 612, 613, 614, 615, 616, 617],
"Zul'Gurub": [784, 785, 786, 787, 788, 789, 790, 791, 792, 793],
"Ahn'Qiraj Ruins": [718, 719, 720, 721, 722, 723],
"Ahn'Qiraj Temple": [709, 710, 711, 712, 713, 714, 715, 716, 717],
"Naxxramas": [1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121],
}
ZONES_BY_ID = {
1000: "Molten Core",
1001: "Onyxia",
1002: "Blackwing Lair",
1003: "Zul'Gurub",
1004: "Ahn'Qiraj Ruins",
1005: "Ahn'Qiraj Temple",
1006: "Naxxramas",
}
ZONES_BY_SHORT_NAME = {
"MC": ["Molten Core", 1000],
"ONY": ["Onyxia", 1001],
"BWL": ["Blackwing Lair", 1002],
"ZG": ["Zul'Gurub", 1003],
"AQ20": ["Ahn'Qiraj Ruins", 1004],
"AQ40": ["Ahn'Qiraj Temple", 1005],
"NAXX": ["Naxxramas", 1006],
}

176
warcraftlogs/http.py Normal file
View File

@@ -0,0 +1,176 @@
# Most of this code is copied from https://github.com/Kowlin/Sentinel/blob/master/githubcards/http.py
# Most of the source of this file can be found at: https://github.com/Kowlin/GraphQL-WoWLogs/blob/master/wowlogs/http.py
from enum import unique
import aiohttp
import logging
from redbot.core.bot import Red
from redbot.core.config import Config
from datetime import datetime
from .calls import Queries
log = logging.getLogger("red.aikaterna.warcraftlogs.http")
baseurl = "https://classic.warcraftlogs.com"
graphql_url = baseurl + "/api/v2/client"
async def generate_bearer(bot: Red, config: Config) -> str:
"""Generate the Bearer token used in GraphQL queries
Bot and Config are imported here from the main class,
due the need to save data to both of them."""
tokens = await bot.get_shared_api_tokens("warcraftlogs")
client_id = tokens.get("client_id", "")
client_secret = tokens.get("client_secret", "")
if not client_id:
log.error("Generate bearer: No valid client ID set")
return None
elif not client_secret:
log.error("Generate bearer: No valid client secret set")
return None
else:
headers = {"User-Agent": "Red-DiscordBot/WarcraftLogsCog"}
async with aiohttp.ClientSession(
headers=headers, auth=aiohttp.BasicAuth(login=client_id, password=client_secret)
) as session:
form = aiohttp.FormData()
form.add_field("grant_type", "client_credentials")
request = await session.post(f"{baseurl}/oauth/token", data=form)
json = await request.json()
if json.get("error", ""):
log.error("There is an error generating the bearer key, probably a misconfigured client id and secret.")
log.error(f"{json['error']}: {json['error_description']}")
return None
timestamp_now = int(datetime.utcnow().timestamp()) # Round the timestamp down to a full number
bearer_timestamp = (
timestamp_now + json["expires_in"] - 120
) # Reduce the timestamp by 2 min to be on the safe side of possible errors
await config.bearer_timestamp.set(bearer_timestamp)
log.info("Bearer token created")
await bot.set_shared_api_tokens("warcraftlogs", bearer=json["access_token"])
return json["access_token"]
class WoWLogsClient:
"""This is where the magic happens."""
def __init__(self, bearer: str) -> None:
self.session: aiohttp.ClientSession
self._bearer: str
self._create_session(bearer)
def _create_session(self, bearer: str) -> None:
headers = {
"Authorization": f"Bearer {bearer}",
"Content-Type": "application/json",
# Not strictly required to set an user agent, yet still respectful.
"User-Agent": "Red-DiscordBot/WarcraftLogsCog",
}
self._bearer = bearer
self.session = aiohttp.ClientSession(headers=headers)
async def recreate_session(self, bearer: str) -> None:
await self.session.close()
self._create_session(bearer)
async def check_bearer(self):
async with self.session.post(graphql_url, json={"query": Queries.check_bearer}) as call:
try:
await call.json()
except aiohttp.ContentTypeError:
log.error("Bearer token has been invalidated")
return False
return True
async def get_overview(self, char_name: str, char_realm: str, char_server: str, zone_id: int):
async with self.session.post(
graphql_url,
json={
"query": Queries.get_overview,
"variables": {
"char_name": char_name,
"char_realm": char_realm,
"char_server": char_server,
"zone_id": zone_id,
},
},
) as call:
try:
json = await call.json()
except aiohttp.ContentTypeError:
log.error("Bearer token has been invalidated")
return None
error = json.get("error", None)
if error:
log.error(f"Error: {error}")
return json
async def get_last_encounter(self, char_name: str, char_realm: str, char_server: str):
async with self.session.post(
graphql_url,
json={
"query": Queries.get_last_encounter,
"variables": {"char_name": char_name, "char_realm": char_realm, "char_server": char_server},
},
) as call:
try:
json = await call.json()
except aiohttp.ContentTypeError:
log.error("Bearer token has been invalidated")
return None
error = json.get("error", None)
if error:
log.error(f"Error: {error}")
return json
if json["data"]["characterData"]["character"] is None:
return False
data = json["data"]["characterData"]["character"]["recentReports"]["data"]
unique_encouters = {"ids": [], "latest": 0, "latest_time": 0}
for fight in data[0]["fights"]:
if fight["encounterID"] not in unique_encouters["ids"]:
unique_encouters["ids"].append(int(fight["encounterID"]))
if fight["endTime"] > unique_encouters["latest_time"]:
unique_encouters["latest"] = fight["encounterID"]
unique_encouters["latest_time"] = fight["endTime"]
return unique_encouters
async def get_gear(self, char_name: str, char_realm: str, char_server: str, encounter_id: int):
async with self.session.post(
graphql_url,
json={
"query": Queries.get_gear,
"variables": {
"char_name": char_name,
"char_realm": char_realm,
"char_server": char_server,
"encounter": encounter_id,
},
},
) as call:
try:
json = await call.json()
except aiohttp.ContentTypeError:
log.error("Bearer token has been invalidated")
return None
error = json.get("error", None)
if error:
log.error(f"Error: {error}")
return json
if json["data"]["characterData"]["character"] is None:
return False
data = json["data"]["characterData"]["character"]
return data

View File

@@ -1,10 +1,11 @@
{
"author": ["aikaterna"],
"author": ["aikaterna", "Kowlin"],
"description": "Check WarcraftLogs for data on players of World of Warcraft Classic.",
"install_msg": "Check out [p]help WarcraftLogs and set your WCL API key, available by signing into a WarcraftLogs account on their site and visiting the bottom of your settings page. ",
"install_msg": "Check out [p]help WarcraftLogs and set your WCL API key, available by signing into a WarcraftLogs account on their site and visiting the bottom of your settings page.\nThe bot needs Embed Links permissions before the relevant commands will be available for use in this cog.\nThis cog also comes with a font that is included in the bundled data, under the Apache 2.0 License, which can also be found in that bundled data directory.",
"short": "WarcraftLogs data for World of Warcraft Classic players.",
"tags": ["warcraft"],
"permissions": ["embed_links"],
"requirements": ["pillow"],
"type": "COG",
"end_user_data_statement": "This cog stores data provided by users for the express purpose of redisplaying. It does not store user data which was not provided through a command. Users may remove their own content without making a data removal request. This cog does not support data requests, but will respect deletion requests."
}
}

View File

@@ -1,350 +0,0 @@
from typing import Literal
import aiohttp
import datetime
import discord
import itertools
import json
from operator import itemgetter
from redbot.core import Config, commands, checks
from redbot.core.utils.chat_formatting import box
from redbot.core.utils.menus import menu, DEFAULT_CONTROLS
class WarcraftLogs(commands.Cog):
"""Access Warcraftlogs stats."""
async def red_delete_data_for_user(
self, *, requester: Literal["discord", "owner", "user", "user_strict"], user_id: int,
):
await self.config.user_from_id(user_id).clear()
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 2713931001, force_registration=True)
self.session = aiohttp.ClientSession()
self.zones = [1005, 1004, 1003, 1002] # Ony and MC removed as we are now in ph 5
self.partitions = [3, 2] # No partition 1 needed here now - ZG, AQ, BWL were not present in ph 1 & 2
default_user = {
"charname": None,
"realm": None,
"region": None,
}
default_global = {
"apikey": None,
}
self.config.register_user(**default_user)
self.config.register_global(**default_global)
def cog_unload(self):
self.bot.loop.create_task(self.session.close())
@commands.command()
async def wclregion(self, ctx, region: str):
"""Set your region."""
valid_regions = ["EU", "US"]
if region.upper() not in valid_regions:
return await ctx.send("Valid regions are: {humanize_list(valid_regions)}")
await self.config.user(ctx.author).region.set(region)
await ctx.send(f"Your server's region was set to {region.upper()}.")
@commands.command()
async def wclcharname(self, ctx, charname: str):
"""Set your character's name."""
await self.config.user(ctx.author).charname.set(charname)
await ctx.send(f"Your character name was set to {charname.title()}.")
@commands.command()
async def wclrealm(self, ctx, *, realm: str):
"""Set your realm."""
realmname = realm.replace(" ", "-")
await self.config.user(ctx.author).realm.set(realmname)
await ctx.send(f"Your realm was set to {realm.title()}.")
@commands.command()
async def wclsettings(self, ctx, user: discord.User = None):
"""Show your current settings."""
if not user:
user = ctx.author
userinfo = await self.config.user(user).all()
msg = f"[Settings for {user.display_name}]\n"
charname = userinfo["charname"].title() if userinfo["charname"] else "None"
realmname = userinfo["realm"].title().replace("-", " ") if userinfo["realm"] else "None"
regionname = userinfo["region"].upper() if userinfo["region"] else "None"
msg += f"Character: {charname}\nRealm: {realmname}\nRegion: {regionname}\n"
await ctx.send(box(msg, lang="ini"))
@commands.command()
@checks.is_owner()
async def wclapikey(self, ctx, apikey: str):
"""Set the api key."""
await self.config.apikey.set(apikey)
try:
await ctx.message.delete()
except discord.errors.Forbidden:
pass
await ctx.send(f"The WarcraftLogs API key has been set.")
@commands.command()
@commands.guild_only()
async def wclrank(self, ctx, username=None, realmname=None, region=None):
"""Fetch ranking info about a player."""
userdata = await self.config.user(ctx.author).all()
apikey = await self.config.apikey()
if not apikey:
return await ctx.send("The bot owner needs to set a WarcraftLogs API key before this can be used.")
if not username:
username = userdata["charname"]
if not username:
return await ctx.send("Please specify a character name with this command.")
if not realmname:
realmname = userdata["realm"]
if not realmname:
return await ctx.send("Please specify a realm name with this command.")
if not region:
region = userdata["region"]
if not region:
return await ctx.send("Please specify a region name with this command.")
final_embed_list = []
kill_data = []
log_data = []
async with ctx.channel.typing():
for zone in self.zones:
for phase in self.partitions:
url = f"https://classic.warcraftlogs.com/v1/parses/character/{username}/{realmname}/{region}?zone={zone}&partition={phase}&api_key={apikey}"
try:
async with self.session.request("GET", url) as page:
data = await page.text()
data = json.loads(data)
except Exception as e:
return await ctx.send(
f"Oops, there was a problem fetching something (Zone {zone}/Phase {phase}): {e}"
)
if "error" in data:
return await ctx.send(
f"{username.title()} - {realmname.title()} ({region.upper()}) doesn't have any valid logs that I can see.\nError {data['status']}: {data['error']}"
)
# Logged Kills
zone_name = self.get_zone(zone)
zone_and_phase = f"{zone_name}_{phase}"
area_data = self.get_kills(data, zone_and_phase)
kill_data.append(area_data)
# Log IDs for parses
log_info = self.get_log_id(data, zone_and_phase)
log_data.append(log_info)
# Logged Kill sorting
embed1 = discord.Embed(title=f"{username.title()} - {realmname.title()} ({region.upper()})\nLogged Kills")
for item in kill_data:
zone_kills = ""
for boss_info in list(item.values()):
zone_name, phase_num = self.clean_name(list(item))
for boss_name, boss_kills in boss_info.items():
zone_kills += f"{boss_name}: {boss_kills}\n"
if zone_kills:
embed1.add_field(name=f"{zone_name}\n{phase_num}", value=zone_kills)
embed1.set_footer(text="Molten Core and Onyxia are not currently displayed as we are now in Phase 5.")
final_embed_list.append(embed1)
# Log ID sorting
wcl_url = "https://classic.warcraftlogs.com/reports/{}#fight={}"
log_embed_list = []
for item in log_data:
log_page = ""
for id_data in list(item.values()):
sorted_item = {k: v for k, v in sorted(id_data.items(), key=lambda item: item[1], reverse=True)}
short_list = dict(itertools.islice(sorted_item.items(), 5))
zone_name, phase_num = self.clean_name(list(item))
for log_id, info_list in short_list.items():
# info_list: [timestamp:int, percentile:int, spec:str, fightid:int, rank:int, outOf:int]
# log_id: encounterid-encountername
log_url = log_id.split("-")[0]
log_name = log_id.split("-")[1]
log_page += f"{wcl_url.format(log_url, info_list[3])}\n{self.time_convert(info_list[0])} UTC\nEncounter: {log_name}\nDPS Percentile: {info_list[1]} [{info_list[4]} of {info_list[5]}] ({info_list[2]})\n\n"
if id_data:
embed = discord.Embed(
title=f"{username.title()} - {realmname.title()} ({region.upper()})\nWarcraft Log IDs"
)
embed.add_field(name=f"{zone_name}\n{phase_num}", value=log_page, inline=False)
embed.set_footer(text="Up to the last 5 logs shown per encounter/phase.")
log_embed_list.append(embed)
for log_embed in log_embed_list:
final_embed_list.append(log_embed)
await menu(ctx, final_embed_list, DEFAULT_CONTROLS)
# @commands.command()
# @commands.guild_only()
# async def wclgear(self, ctx, username=None, realmname=None, region=None):
# """Fetch gear info about a player."""
# userdata = await self.config.user(ctx.author).all()
# apikey = await self.config.apikey()
# if not apikey:
# return await ctx.send("The bot owner needs to set a WarcraftLogs API key before this can be used.")
# if not username:
# username = userdata["charname"]
# if not username:
# return await ctx.send("Please specify a character name with this command.")
# if not realmname:
# realmname = userdata["realm"]
# if not realmname:
# return await ctx.send("Please specify a realm name with this command.")
# if not region:
# region = userdata["region"]
# if not region:
# return await ctx.send("Please specify a region name with this command.")
# all_encounters = []
# for zone, phase in [(x, y) for x in self.zones for y in self.partitions]:
# url = f"https://classic.warcraftlogs.com/v1/parses/character/{username}/{realmname}/{region}?zone={zone}&partition={phase}&api_key={apikey}"
# async with self.session.request("GET", url) as page:
# data = await page.text()
# data = json.loads(data)
# if "error" in data:
# return await ctx.send(
# f"{username.title()} - {realmname.title()} ({region.upper()}) doesn't have any valid logs that I can see.\nError {data['status']}: {data['error']}"
# )
# if data:
# encounter = self.get_recent_gear(data)
# if encounter:
# all_encounters.append(encounter)
# final = self.get_recent_gear(all_encounters)
# wowhead_url = "https://classic.wowhead.com/item={}"
# wcl_url = "https://classic.warcraftlogs.com/reports/{}"
# itempage = ""
# for item in final["gear"]:
# if item["id"] == 0:
# continue
# rarity = self.get_rarity(item)
# itempage += f"{rarity} [{item['name']}]({wowhead_url.format(item['id'])})\n"
# itempage += f"\nAverage ilvl: {final['ilvlKeyOrPatch']}"
# embed = discord.Embed(
# title=f"{final['characterName']} - {final['server']} ({region.upper()})\n{final['class']} ({final['spec']})",
# description=itempage,
# )
# embed.set_footer(
# text=f"Gear data pulled from {wcl_url.format(final['reportID'])}\nEncounter: {final['encounterName']}\nLog Date/Time: {self.time_convert(final['startTime'])} UTC"
# )
# await ctx.send(embed=embed)
@staticmethod
def get_rarity(item):
rarity = item["quality"]
if rarity == "common":
return ""
elif rarity == "uncommon":
return "🟩"
elif rarity == "rare":
return "🟦"
elif rarity == "epic":
return "🟪"
else:
return "🔳"
@staticmethod
def time_convert(time):
time = str(time)[0:10]
value = datetime.datetime.fromtimestamp(int(time)).strftime("%Y-%m-%d %H:%M:%S")
return value
@staticmethod
def get_kills(data, zone_and_phase):
# data is json data
# zone_and_phase: Name_Phasenum
boss_kills = {}
for encounter in data:
if encounter["encounterName"] not in boss_kills.keys():
boss_kills[encounter["encounterName"]] = 0
boss_kills[encounter["encounterName"]] += 1
complete_info = {}
complete_info[zone_and_phase] = boss_kills
return complete_info
@staticmethod
def get_zone(zone):
# Zone ID and name is available from the API, but why make another
# call to a url when it's simple for now... maybe revisit in phase 5+
if zone == 1000:
zone_name = "MoltenCore"
elif zone == 1001:
zone_name = "Onyxia"
elif zone == 1002:
zone_name = "BWL"
elif zone == 1003:
zone_name = "ZG"
elif zone == 1004:
zone_name = "AQ20"
elif zone == 1005:
zone_name = "AQ40"
else:
zone_name = None
return zone_name
@staticmethod
def clean_name(zone_and_phase):
zone_and_phase = zone_and_phase[0]
zone_name = zone_and_phase.split("_")[0]
phase_num = zone_and_phase[-1]
if zone_name == "MoltenCore":
zone_name = "Molten Core"
elif zone_name == "BWL":
zone_name = "Blackwing Lair"
elif zone_name == "ZG":
zone_name = "Zul'Gurub"
elif zone_name == "AQ20":
zone_name = "Ahn'Qiraj Ruins"
elif zone_name == "AQ40":
zone_name = "Ahn'Qiraj Temple"
else:
zone_name = zone_name
if phase_num == "1":
phase_num = "Phase 1 & 2"
elif phase_num == "2":
phase_num = "Phase 3 & 4"
else:
phase_num = "Phase 5"
return zone_name, phase_num
@staticmethod
def get_log_id(data, zone_and_phase):
report_ids = {}
for encounter in data:
keyname = f"{encounter['reportID']}-{encounter['encounterName']}"
report_ids[keyname] = [
encounter["startTime"],
encounter["percentile"],
encounter["spec"],
encounter["fightID"],
encounter["rank"],
encounter["outOf"],
]
complete_info = {}
complete_info[zone_and_phase] = report_ids
return complete_info
@staticmethod
def get_recent_gear(data):
date_sorted_data = sorted(data, key=itemgetter("startTime"), reverse=True)
for encounter in date_sorted_data:
try:
item_name = encounter["gear"][0]["name"]
if item_name == "Unknown Item":
continue
else:
return encounter
except KeyError:
return None