Skip to content

Commit

Permalink
Merge pull request #137 from DMcP89/enhancement/113-placeholder-for-t…
Browse files Browse the repository at this point in the history
…eam-names

Enhancement/113 placeholder for team names
  • Loading branch information
DMcP89 authored Feb 2, 2024
2 parents 7ad43d2 + ad5ed73 commit 0b6f6cb
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 36 deletions.
7 changes: 3 additions & 4 deletions harambot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@
if "LOGLEVEL" in settings:
logger.setLevel(settings.loglevel)
else:
logger.setLevel("INFO")
logger.setLevel("DEBUG")


intents = discord.Intents.default()
# intents.members = True
# intents.messages = True
# intents.message_content = True


bot = commands.Bot(command_prefix="$", description="", intents=intents)
bot.remove_command("help")
Expand Down
80 changes: 58 additions & 22 deletions harambot/cogs/yahoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from discord import app_commands
from yahoo_oauth import OAuth2
from playhouse.shortcuts import model_to_dict
from typing import List

from harambot.yahoo_api import Yahoo
from harambot.database.models import Guild
Expand All @@ -29,34 +30,29 @@ def __init__(self, bot, KEY, SECRET):
self.SECRET = SECRET
self.yahoo_api = None

async def cog_before_invoke(self, ctx):
guild = Guild.get(Guild.guild_id == str(ctx.guild.id))
self.yahoo_api = Yahoo(
OAuth2(
self.KEY, self.SECRET, store_file=False, **model_to_dict(guild)
),
guild.league_id,
guild.league_type,
)
return

def set_yahoo(f):
@functools.wraps(f)
async def wrapper(
self, interaction: discord.Interaction, *args, **kwargs
):
guild = Guild.get(Guild.guild_id == str(interaction.guild_id))
self.yahoo_api = Yahoo(
OAuth2(
self.KEY,
self.SECRET,
store_file=False,
**model_to_dict(guild),
),
guild.league_id,
guild.league_type,
)
await f(self, interaction, *args, **kwargs)

if (
not self.yahoo_api
or self.yahoo_api.league_id != guild.league_id
):
self.yahoo_api = Yahoo(
OAuth2(
self.KEY,
self.SECRET,
store_file=False,
**model_to_dict(guild),
),
guild.league_id,
guild.league_type,
)

return await f(self, interaction, *args, **kwargs)

return wrapper

Expand All @@ -83,9 +79,27 @@ async def standings(self, interaction: discord.Interaction):
else:
await interaction.response.send_message(self.error_message)

@set_yahoo
async def roster_autocomplete(
self,
interaction: discord.Interaction,
current: str,
) -> List[app_commands.Choice[str]]:
teams = self.yahoo_api.get_teams()
options = list(
map(
lambda x: app_commands.Choice(
name=teams[x]["name"], value=teams[x]["name"]
),
teams,
)
)
return options

@app_commands.command(
name="roster", description="Returns the roster of the given team"
)
@app_commands.autocomplete(team_name=roster_autocomplete)
@set_yahoo
async def roster(self, interaction: discord.Interaction, team_name: str):
logger.info("roster called")
Expand Down Expand Up @@ -196,9 +210,31 @@ async def trade(self, interaction: discord.Interaction):
await response_message.add_reaction(yes_emoji)
await response_message.add_reaction(no_emoji)

@set_yahoo
async def stats_autocomplete(
self,
interaction: discord.Interaction,
current: str,
) -> List[app_commands.Choice[str]]:
players = self.yahoo_api.league().player_details(current)
if players:
options = list(
map(
lambda x: app_commands.Choice(
name=x["name"]["full"],
value=x["name"]["full"],
),
players,
)
)
else:
options = []
return options

@app_commands.command(
name="stats", description="Returns the details of the given player"
)
@app_commands.autocomplete(player_name=stats_autocomplete)
@set_yahoo
async def stats(self, interaction: discord.Interaction, player_name: str):
logger.info("player_details called")
Expand Down
20 changes: 10 additions & 10 deletions harambot/yahoo_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@


dir_path = os.path.dirname(os.path.realpath(__file__))
cache = TTLCache(maxsize=1024, ttl=600)


class Yahoo:
Expand All @@ -26,7 +27,6 @@ def __init__(self, oauth, league_id, league_type):
self.league_id = league_id
self.league_type = league_type

@cached(cache=TTLCache(maxsize=1024, ttl=600))
def league(self):
if not self.oauth.token_is_valid():
self.oauth.refresh_access_token()
Expand All @@ -35,7 +35,9 @@ def league(self):
self.scoring_type = league.settings()["scoring_type"]
return league

@cached(cache=TTLCache(maxsize=1024, ttl=600))
def get_teams(self):
return self.league().teams()

def get_standings(self):
try:
standings = []
Expand All @@ -59,15 +61,15 @@ def get_standings(self):
)
return None

@cached(cache=TTLCache(maxsize=1024, ttl=600))
@cached(cache)
def get_roster(self, team_name):
team_details = self.league().get_team(team_name)
if team_details:
return team_details[team_name].roster(self.league().current_week())
else:
return None

@cached(cache=TTLCache(maxsize=1024, ttl=600))
@cached(cache)
def get_player_details(self, player_name):
try:
player = self.league().player_details(player_name)[0]
Expand All @@ -82,7 +84,7 @@ def get_player_details(self, player_name):
)
return None

@cached(cache=TTLCache(maxsize=1024, ttl=600))
@cached(cache)
def get_player_owner(self, player_id):
try:
player_ownership = self.league().ownership([player_id])[
Expand All @@ -107,7 +109,6 @@ def get_player_owner(self, player_id):
)
return None

@cached(cache=TTLCache(maxsize=1024, ttl=600))
def get_matchups(self):
try:
matchups = objectpath.Tree(self.league().matchups()).execute(
Expand All @@ -130,11 +131,12 @@ def get_matchups(self):
}
)
return str(self.league().current_week()), details
except Exception:
except Exception as e:
logger.exception(
"Error while fetching matchups for league: {}".format(
self.league_id
)
),
e,
)

def get_matchup_details(self, team):
Expand Down Expand Up @@ -175,7 +177,6 @@ def get_matchup_details(self, team):
)
return {"name": team_name, "text": team_details}

@cached(cache=TTLCache(maxsize=1024, ttl=600))
def get_latest_trade(self):
try:
for key, values in self.league().teams().items():
Expand All @@ -193,7 +194,6 @@ def get_latest_trade(self):
except Exception:
logger.exception("Error while fetching latest trade")

@cached(cache=TTLCache(maxsize=1024, ttl=600))
def get_latest_waiver_transactions(self):
ts = datetime.now() - timedelta(days=1)
transactions = self.league().transactions("add,drop", "")
Expand Down

0 comments on commit 0b6f6cb

Please sign in to comment.