From 99776dbae624d3b41e8bb0de8365fab70b64c507 Mon Sep 17 00:00:00 2001 From: Luke Robles Date: Wed, 7 May 2025 15:23:32 -0700 Subject: [PATCH] Use ruff and conert stock to fstrings --- app/apex.py | 90 +++++++++++++++++++++++++++++++++++++ app/bot.py | 1 - app/cogs/game_apis.py | 25 ++++++++++- app/cogs/palworld.py | 5 +-- app/cogs/tarkov.py | 1 - app/cogs/trackdays.py | 2 +- app/stock.py | 32 +++++-------- scratchpad/get_trackdays.py | 2 - 8 files changed, 128 insertions(+), 30 deletions(-) create mode 100755 app/apex.py diff --git a/app/apex.py b/app/apex.py new file mode 100755 index 00000000..25592137 --- /dev/null +++ b/app/apex.py @@ -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) diff --git a/app/bot.py b/app/bot.py index a151485a..58904b58 100755 --- a/app/bot.py +++ b/app/bot.py @@ -2,7 +2,6 @@ from discord.ext import commands import core_utils import discord -import httpx import os import random import requests diff --git a/app/cogs/game_apis.py b/app/cogs/game_apis.py index 5952f9d2..bdfcf54e 100755 --- a/app/cogs/game_apis.py +++ b/app/cogs/game_apis.py @@ -1,5 +1,4 @@ from bs4 import BeautifulSoup -from discord import option from discord.ext import commands import discord import requests @@ -23,6 +22,30 @@ class Games(commands.Cog): 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( # guild_ids=None, # name="ffxiv", diff --git a/app/cogs/palworld.py b/app/cogs/palworld.py index 70bb0583..e7a2ea94 100755 --- a/app/cogs/palworld.py +++ b/app/cogs/palworld.py @@ -1,10 +1,7 @@ -from discord import option -from discord.ext import commands, tasks +from discord.ext import commands import discord import requests from bs4 import BeautifulSoup -import re -import os class PalWorld(commands.Cog): diff --git a/app/cogs/tarkov.py b/app/cogs/tarkov.py index e9646084..1cfd3f8b 100755 --- a/app/cogs/tarkov.py +++ b/app/cogs/tarkov.py @@ -1,7 +1,6 @@ from bs4 import BeautifulSoup from datetime import datetime from discord.ext import commands, tasks -import core_utils import discord import os import json diff --git a/app/cogs/trackdays.py b/app/cogs/trackdays.py index cfff67ce..a40965e0 100755 --- a/app/cogs/trackdays.py +++ b/app/cogs/trackdays.py @@ -86,7 +86,7 @@ class TrackDays(commands.Cog): } current_month = datetime.datetime.now().month - current_year = datetime.datetime.now().year + datetime.datetime.now().year for month in months: month_name = month.text diff --git a/app/stock.py b/app/stock.py index c839a95c..fc574570 100755 --- a/app/stock.py +++ b/app/stock.py @@ -35,33 +35,29 @@ def _add_verbose_fields(embed, request): """ embed.add_field( name="Previous Close", - value="$%s" % request["regularMarketPreviousClose"], + value=f"${request['regularMarketPreviousClose']}", inline=False, ) embed.add_field( name="Change since prev. close (as %)", - value="$%.2f (%s%%)" - % ( - request["regularMarketChange"], - request["regularMarketChangePercent"], - ), + value=f"${request['regularMarketChange']:.2f} ({request['regularMarketChangePercent']}%)", inline=False, ) if "bid" in request and "ask" in request: embed.add_field( name="Current bid price", - value="$%s" % request["bid"], + value=f"${request['bid']}", inline=False, ) embed.add_field( name="Current ask price", - value="$%s" % request["ask"], + value=f"${request['ask']}", inline=False, ) embed.add_field( name="Current bid-ask spread", - value="$%.2f" % (request["bid"] - request["ask"]), + value=f"${(request['bid'] - request['ask']):.2f}", inline=False, ) @@ -71,13 +67,13 @@ def _add_verbose_fields(embed, request): if "marketCap" in request: 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: embed.add_field( name="Shares Outstanding", - value="{:,}".format(request["sharesOutstanding"]), + value=f"{request['sharesOutstanding']:,}", inline=False, ) @@ -102,8 +98,8 @@ def get_stock(share_name, verbose=False, fast=False): current_price = request.get("currentPrice", request["ask"]) current_change = current_price - request["open"] - except Exception as e: - raise ValueError("Invalid symbol %s: empty response from Yahoo" % share_name) + except Exception: + 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 # change_symbol = "+" @@ -120,22 +116,18 @@ def get_stock(share_name, verbose=False, fast=False): embed.add_field( name="Current price", - value="$" + format(current_price, ",.2f"), + value=f"${current_price:,.2f}", inline=False, ) embed.add_field( name="Opening price", - value="$" + format(request["open"], ",.2f"), + value=f"${request['open']:,.2f}", inline=False, ) embed.add_field( name="Change since day open (as %)", - value="$%.2f (%.7f%%)" - % ( - current_change, - current_change * 100 / request["open"], - ), + value=f"${current_change:.2f} ({current_change * 100 / request['open']:.7f}%)", inline=False, ) diff --git a/scratchpad/get_trackdays.py b/scratchpad/get_trackdays.py index ae47bf06..a73f11e1 100755 --- a/scratchpad/get_trackdays.py +++ b/scratchpad/get_trackdays.py @@ -1,8 +1,6 @@ from bs4 import BeautifulSoup -import datetime import pprint import requests -from collections import OrderedDict pp = pprint.PrettyPrinter(indent=2)