Use ruff and conert stock to fstrings
All checks were successful
Build and push / changes (push) Successful in 13s
Build and push / Lint-Python (push) Successful in 2s
Build and push / Build-and-Push-Docker (push) Successful in 1m13s
Build and push / sync-argocd-app (push) Successful in 3s
Build and push / post-failure-to-discord (push) Has been skipped
Build and push / post-success-to-discord (push) Successful in 1s

This commit is contained in:
Luke Robles 2025-05-07 15:23:32 -07:00
parent 0df0cb444a
commit 99776dbae6
8 changed files with 128 additions and 30 deletions

90
app/apex.py Executable file
View File

@ -0,0 +1,90 @@
import discord
import os
import requests
def get_player(player):
url = "https://public-api.tracker.gg/v2/apex/standard/profile/origin/" + player
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64)",
"accept": "application/json",
"TRN-Api-Key": os.getenv("tracker_network_token"),
}
response = requests.get(url, headers=headers).json()["data"]
print(response)
# Build the embed
embed = discord.Embed(description="-------", color=discord.Color.red(), type="rich")
embed.set_thumbnail(url=response["platformInfo"]["avatarUrl"])
embed.set_author(
name="Apex stats for %s" % response["platformInfo"]["platformUserId"],
icon_url=response["segments"][0]["stats"]["lifetimePeakRankScore"]["metadata"][
"iconUrl"
],
)
embed.add_field(
name="**Current Rank**",
value=response["segments"][0]["stats"]["lifetimePeakRankScore"]["displayName"],
inline=True,
)
embed.add_field(name="Account Wide stats", value="-----", inline=False)
stats_we_care_about = ["wins", "level", "kills", "damage", "headshots", "revives"]
for stat in stats_we_care_about:
embed.add_field(
name="**%s**" % response["segments"][0]["stats"][stat]["displayName"],
value=response["segments"][0]["stats"][stat]["displayValue"],
inline=True,
)
all_legends = response["segments"][1:]
# Calculate their most effective legends
embed.add_field(name="Bests", value="-----", inline=False)
embed.add_field(
name="**Legend with most kills**",
value="%s: %s"
% (
find_best(all_legends, key="kills")["metadata"]["name"],
find_best(all_legends, key="kills")["stats"]["kills"]["displayValue"],
),
)
embed.add_field(
name="**Legend with most wins**",
value="%s: %s"
% (
find_best(all_legends, key="wins")["metadata"]["name"],
find_best(all_legends, key="wins")["stats"]["wins"]["displayValue"],
),
)
embed.add_field(
name="**Legend with most damage**",
value="%s: %s"
% (
find_best(all_legends, key="damage")["metadata"]["name"],
find_best(all_legends, key="damage")["stats"]["damage"]["displayValue"],
),
)
embed.add_field(
name="**Legend with most revives**",
value="%s: %s"
% (
find_best(all_legends, key="revives")["metadata"]["name"],
find_best(all_legends, key="revives")["stats"]["revives"]["displayValue"],
),
)
return embed
def find_best(blob, key):
"""
find_best(blob, key)
blob should be the list within the request you want to find the best of,
must be one of [weapopns, vehicles, classes, gamemodes, maps, gadgets], eg. response["weapons"],
and the key to use to make that distinction, for example, for weapons, you could use kills
"""
return max(blob, key=lambda x: x["stats"][key]["value"] if key in x else None)

View File

@ -2,7 +2,6 @@
from discord.ext import commands from discord.ext import commands
import core_utils import core_utils
import discord import discord
import httpx
import os import os
import random import random
import requests import requests

View File

@ -1,5 +1,4 @@
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from discord import option
from discord.ext import commands from discord.ext import commands
import discord import discord
import requests import requests
@ -23,6 +22,30 @@ class Games(commands.Cog):
return worlds return worlds
@commands.slash_command(
guild_ids=None,
name="apex",
description="Query the game's API for data about a player",
contexts={
discord.InteractionContextType.guild,
discord.InteractionContextType.bot_dm,
discord.InteractionContextType.private_channel,
},
integration_types={
discord.IntegrationType.guild_install,
discord.IntegrationType.user_install,
},
)
async def apex(self, ctx: discord.ApplicationContext, player):
import apex
try:
await ctx.defer()
embed = apex.get_player(player)
await ctx.send_followup(embed=embed)
except Exception as e:
await ctx.send(e)
# @commands.slash_command( # @commands.slash_command(
# guild_ids=None, # guild_ids=None,
# name="ffxiv", # name="ffxiv",

View File

@ -1,10 +1,7 @@
from discord import option from discord.ext import commands
from discord.ext import commands, tasks
import discord import discord
import requests import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import re
import os
class PalWorld(commands.Cog): class PalWorld(commands.Cog):

View File

@ -1,7 +1,6 @@
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from datetime import datetime from datetime import datetime
from discord.ext import commands, tasks from discord.ext import commands, tasks
import core_utils
import discord import discord
import os import os
import json import json

View File

@ -86,7 +86,7 @@ class TrackDays(commands.Cog):
} }
current_month = datetime.datetime.now().month current_month = datetime.datetime.now().month
current_year = datetime.datetime.now().year datetime.datetime.now().year
for month in months: for month in months:
month_name = month.text month_name = month.text

View File

@ -35,33 +35,29 @@ def _add_verbose_fields(embed, request):
""" """
embed.add_field( embed.add_field(
name="Previous Close", name="Previous Close",
value="$%s" % request["regularMarketPreviousClose"], value=f"${request['regularMarketPreviousClose']}",
inline=False, inline=False,
) )
embed.add_field( embed.add_field(
name="Change since prev. close (as %)", name="Change since prev. close (as %)",
value="$%.2f (%s%%)" value=f"${request['regularMarketChange']:.2f} ({request['regularMarketChangePercent']}%)",
% (
request["regularMarketChange"],
request["regularMarketChangePercent"],
),
inline=False, inline=False,
) )
if "bid" in request and "ask" in request: if "bid" in request and "ask" in request:
embed.add_field( embed.add_field(
name="Current bid price", name="Current bid price",
value="$%s" % request["bid"], value=f"${request['bid']}",
inline=False, inline=False,
) )
embed.add_field( embed.add_field(
name="Current ask price", name="Current ask price",
value="$%s" % request["ask"], value=f"${request['ask']}",
inline=False, inline=False,
) )
embed.add_field( embed.add_field(
name="Current bid-ask spread", name="Current bid-ask spread",
value="$%.2f" % (request["bid"] - request["ask"]), value=f"${(request['bid'] - request['ask']):.2f}",
inline=False, inline=False,
) )
@ -71,13 +67,13 @@ def _add_verbose_fields(embed, request):
if "marketCap" in request: if "marketCap" in request:
embed.add_field( embed.add_field(
name="Market Cap", value="{:,}".format(request["marketCap"]), inline=False name="Market Cap", value=f"{request['marketCap']:,}", inline=False
) )
if "sharesOutstanding" in request: if "sharesOutstanding" in request:
embed.add_field( embed.add_field(
name="Shares Outstanding", name="Shares Outstanding",
value="{:,}".format(request["sharesOutstanding"]), value=f"{request['sharesOutstanding']:,}",
inline=False, inline=False,
) )
@ -102,8 +98,8 @@ def get_stock(share_name, verbose=False, fast=False):
current_price = request.get("currentPrice", request["ask"]) current_price = request.get("currentPrice", request["ask"])
current_change = current_price - request["open"] current_change = current_price - request["open"]
except Exception as e: except Exception:
raise ValueError("Invalid symbol %s: empty response from Yahoo" % share_name) raise ValueError(f"Invalid symbol {share_name}: empty response from Yahoo")
# If stock price has gone down since open, use red and a sad stonk meme # If stock price has gone down since open, use red and a sad stonk meme
# change_symbol = "+" # change_symbol = "+"
@ -120,22 +116,18 @@ def get_stock(share_name, verbose=False, fast=False):
embed.add_field( embed.add_field(
name="Current price", name="Current price",
value="$" + format(current_price, ",.2f"), value=f"${current_price:,.2f}",
inline=False, inline=False,
) )
embed.add_field( embed.add_field(
name="Opening price", name="Opening price",
value="$" + format(request["open"], ",.2f"), value=f"${request['open']:,.2f}",
inline=False, inline=False,
) )
embed.add_field( embed.add_field(
name="Change since day open (as %)", name="Change since day open (as %)",
value="$%.2f (%.7f%%)" value=f"${current_change:.2f} ({current_change * 100 / request['open']:.7f}%)",
% (
current_change,
current_change * 100 / request["open"],
),
inline=False, inline=False,
) )

View File

@ -1,8 +1,6 @@
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import datetime
import pprint import pprint
import requests import requests
from collections import OrderedDict
pp = pprint.PrettyPrinter(indent=2) pp = pprint.PrettyPrinter(indent=2)