diff --git a/cogs/economy.py b/cogs/economy.py index b7f2fe2..23df3e8 100644 --- a/cogs/economy.py +++ b/cogs/economy.py @@ -50,71 +50,83 @@ class Economy(commands.Cog): # self.pd_ticker.cancel() async def cog_command_error(self, ctx, error): - await ctx.send(f'{error}\n\nRun .help to see the command requirements') + await ctx.send( + f"{error}\n\nRun .help to see the command requirements" + ) - async def on_app_command_error(self, interaction: discord.Interaction, error: discord.app_commands.AppCommandError): - await interaction.channel.send(f'{error}') + async def on_app_command_error( + self, + interaction: discord.Interaction, + error: discord.app_commands.AppCommandError, + ): + await interaction.channel.send(f"{error}") - async def buy_card(self, interaction: discord.Interaction, this_player: dict, owner_team: dict): - c_query = await db_get('cards', - params=[('player_id', this_player['player_id']), ('team_id', owner_team["id"])]) - num_copies = c_query['count'] if c_query else 0 + async def buy_card( + self, interaction: discord.Interaction, this_player: dict, owner_team: dict + ): + c_query = await db_get( + "cards", + params=[ + ("player_id", this_player["player_id"]), + ("team_id", owner_team["id"]), + ], + ) + num_copies = c_query["count"] if c_query else 0 - if not this_player['cardset']['for_purchase']: + if not this_player["cardset"]["for_purchase"]: await interaction.response.send_message( - content=f'Ope - looks like singles from the {this_player["cardset"]["name"]} cardset are not available ' - f'for purchase.' + content=f"Ope - looks like singles from the {this_player['cardset']['name']} cardset are not available " + f"for purchase." ) return - if this_player['cost'] > owner_team['wallet']: + if this_player["cost"] > owner_team["wallet"]: await interaction.response.send_message( content=None, - embeds=await get_card_embeds(get_blank_team_card(this_player)) + embeds=await get_card_embeds(get_blank_team_card(this_player)), ) await interaction.channel.send( - content=f'You currently have {num_copies} cop{"ies" if num_copies != 1 else "y"} of this card.\n\n' - f'Your Wallet: {owner_team["wallet"]}₼\n' - f'Card Price: {this_player["cost"]}₼\n' - f'After Purchase: {await get_emoji(interaction.guild, "dead", False)}\n\n' - f'You will have to save up a little more.' + content=f"You currently have {num_copies} cop{'ies' if num_copies != 1 else 'y'} of this card.\n\n" + f"Your Wallet: {owner_team['wallet']}₼\n" + f"Card Price: {this_player['cost']}₼\n" + f"After Purchase: {await get_emoji(interaction.guild, 'dead', False)}\n\n" + f"You will have to save up a little more." ) return view = Confirm(responders=[interaction.user]) await interaction.response.send_message( - content=None, - embeds=await get_card_embeds(get_blank_team_card(this_player)) + content=None, embeds=await get_card_embeds(get_blank_team_card(this_player)) ) question = await interaction.channel.send( - content=f'You currently have {num_copies} cop{"ies" if num_copies != 1 else "y"} of this card.\n\n' - f'Your Wallet: {owner_team["wallet"]}₼\n' - f'Card Price: {this_player["cost"]}₼\n' - f'After Purchase: {owner_team["wallet"] - this_player["cost"]}₼\n\n' - f'Would you like to make this purchase?', - view=view + content=f"You currently have {num_copies} cop{'ies' if num_copies != 1 else 'y'} of this card.\n\n" + f"Your Wallet: {owner_team['wallet']}₼\n" + f"Card Price: {this_player['cost']}₼\n" + f"After Purchase: {owner_team['wallet'] - this_player['cost']}₼\n\n" + f"Would you like to make this purchase?", + view=view, ) await view.wait() if not view.value: - await question.edit( - content='Saving that money. Smart.', - view=None - ) + await question.edit(content="Saving that money. Smart.", view=None) return purchase = await db_get( - f'teams/{owner_team["id"]}/buy/players', - params=[('ts', team_hash(owner_team)), ('ids', f'{this_player["player_id"]}')], - timeout=10 + f"teams/{owner_team['id']}/buy/players", + params=[ + ("ts", team_hash(owner_team)), + ("ids", f"{this_player['player_id']}"), + ], + timeout=10, ) if not purchase: await question.edit( - content=f'That didn\'t go through for some reason. If this happens again, go ping the shit out of Cal.', - view=None + content=f"That didn't go through for some reason. If this happens again, go ping the shit out of Cal.", + view=None, ) return - await question.edit(content=f'It\'s all yours!', view=None) + await question.edit(content=f"It's all yours!", view=None) # async def slash_error(self, ctx, error): # await ctx.send(f'{error}') @@ -181,343 +193,325 @@ class Economy(commands.Cog): @tasks.loop(minutes=10) async def notif_check(self): # Check for notifications - all_notifs = await db_get('notifs', params=[('ack', False)]) + all_notifs = await db_get("notifs", params=[("ack", False)]) if not all_notifs: - logger.debug(f'No notifications') + logger.debug(f"No notifications") return topics = { - 'Price Change': { - 'channel_name': 'pd-market-watch', - 'desc': 'Modified by buying and selling', - 'notifs': [] + "Price Change": { + "channel_name": "pd-market-watch", + "desc": "Modified by buying and selling", + "notifs": [], + }, + "Rare Pull": { + "channel_name": "pd-network-news", + "desc": "MVP and All-Star cards pulled from packs", + "notifs": [], }, - 'Rare Pull': { - 'channel_name': 'pd-network-news', - 'desc': 'MVP and All-Star cards pulled from packs', - 'notifs': [] - } } - for line in all_notifs['notifs']: - if line['title'] in topics: - topics[line['title']]['notifs'].append(line) + for line in all_notifs["notifs"]: + if line["title"] in topics: + topics[line["title"]]["notifs"].append(line) - logger.info(f'topics:\n{topics}') + logger.info(f"topics:\n{topics}") for topic in topics: - embed = get_team_embed(title=f'{topic}{"s" if len(topics[topic]["notifs"]) > 1 else ""}') - embed.description = topics[topic]['desc'] + embed = get_team_embed( + title=f"{topic}{'s' if len(topics[topic]['notifs']) > 1 else ''}" + ) + embed.description = topics[topic]["desc"] p_list = {} - if topics[topic]['notifs']: - for x in topics[topic]['notifs']: - if x['field_name'] not in p_list: - p_list[x['field_name']] = { - 'field_name': x['field_name'], - 'message': f'{x["message"]}', - 'count': 1 + if topics[topic]["notifs"]: + for x in topics[topic]["notifs"]: + if x["field_name"] not in p_list: + p_list[x["field_name"]] = { + "field_name": x["field_name"], + "message": f"{x['message']}", + "count": 1, } else: - p_list[x['field_name']]['message'] = f'{x["message"]}' - p_list[x['field_name']]['count'] += 1 - await db_patch('notifs', object_id=x['id'], params=[('ack', True)]) - logger.debug(f'p_list: {p_list}') + p_list[x["field_name"]]["message"] = f"{x['message']}" + p_list[x["field_name"]]["count"] += 1 + await db_patch("notifs", object_id=x["id"], params=[("ack", True)]) + logger.debug(f"p_list: {p_list}") this_embed = copy.deepcopy(embed) counter = 1 for player in p_list: if counter % 25 == 0: counter = 1 - await send_to_channel(self.bot, topics[topic]['channel_name'], embed=this_embed) + await send_to_channel( + self.bot, topics[topic]["channel_name"], embed=this_embed + ) this_embed = copy.deepcopy(embed) this_embed.add_field( - name=p_list[player]['field_name'], value=p_list[player]['message'], inline=False) + name=p_list[player]["field_name"], + value=p_list[player]["message"], + inline=False, + ) if len(p_list) > 0: - await send_to_channel(self.bot, topics[topic]['channel_name'], embed=this_embed) + await send_to_channel( + self.bot, topics[topic]["channel_name"], embed=this_embed + ) @notif_check.before_loop async def before_notif_check(self): await self.bot.wait_until_ready() - @commands.hybrid_group(name='help-pd', help='FAQ for Paper Dynasty and the bot', aliases=['helppd']) + @commands.hybrid_group( + name="help-pd", help="FAQ for Paper Dynasty and the bot", aliases=["helppd"] + ) @commands.check(legal_channel) async def pd_help_command(self, ctx: commands.Context): if ctx.invoked_subcommand is None: - embed = get_team_embed(f'Paper Dynasty Help') - embed.description = 'Frequently Asked Questions' + embed = get_team_embed(f"Paper Dynasty Help") + embed.description = "Frequently Asked Questions" embed.add_field( - name='What the Heck is Paper Dynasty', - value=f'Well, whipper snapper, have a seat and I\'ll tell you. We\'re running a diamond dynasty / ' - f'perfect team style game with electronic card and dice baseball!\n\nGet a starter pack, play ' - f'games at your leisure either solo or against another player, and collect cards from the ' - f'custom 2021 player set.', - inline=False + name="What the Heck is Paper Dynasty", + value=f"Well, whipper snapper, have a seat and I'll tell you. We're running a diamond dynasty / " + f"perfect team style game with electronic card and dice baseball!\n\nGet a starter pack, play " + f"games at your leisure either solo or against another player, and collect cards from the " + f"custom 2021 player set.", + inline=False, ) embed.add_field( - name='How Do I Get Started', - value=f'Run the `.in` command - that\'s a period followed by the word "in". That\'ll get you the ' - f'Paper Dynasty Players role so you can run all of the other PD commands!\n\nOnce you get your ' - f'role, run `/newteam` and follow the prompts to get your starter team.', - inline=False + name="How Do I Get Started", + value=f"Run the `.in` command - that's a period followed by the word \"in\". That'll get you the " + f"Paper Dynasty Players role so you can run all of the other PD commands!\n\nOnce you get your " + f"role, run `/newteam` and follow the prompts to get your starter team.", + inline=False, ) embed.add_field( - name='How Do I Play', - value='A step-by-step of how to play was written by Riles [starting here](https://discord.com/channels' - '/613880856032968834/633456305830625303/985968300272001054). ' - 'In addition, you can find the Rules Reference [right here](https://docs.google.com/document/d/' - '1yGZcHy9zN2MUi4hnce12dAzlFpIApbn7zR24vCkPl1o).\n\nThere are three key differences from league ' - 'play:\n1) Injuries: there are no injuries in Paper Dynasty!\n2) sWAR: there is no sWAR "salary ' - 'cap" for your team like in league play. Some events will have roster construction rules to ' - 'follow, though!\n3) The Universal DH is in effect; teams may forfeit the DH at their ' - 'discretion.', - inline=False - ) - await ctx.send( - content=None, - embed=embed + name="How Do I Play", + value="A step-by-step of how to play was written by Riles [starting here](https://discord.com/channels" + "/613880856032968834/633456305830625303/985968300272001054). " + "In addition, you can find the Rules Reference [right here](https://docs.google.com/document/d/" + "1yGZcHy9zN2MUi4hnce12dAzlFpIApbn7zR24vCkPl1o).\n\nThere are three key differences from league " + 'play:\n1) Injuries: there are no injuries in Paper Dynasty!\n2) sWAR: there is no sWAR "salary ' + 'cap" for your team like in league play. Some events will have roster construction rules to ' + "follow, though!\n3) The Universal DH is in effect; teams may forfeit the DH at their " + "discretion.", + inline=False, ) + await ctx.send(content=None, embed=embed) - @pd_help_command.command(name='start', help='FAQ for Paper Dynasty and the bot', aliases=['faq']) + @pd_help_command.command( + name="start", help="FAQ for Paper Dynasty and the bot", aliases=["faq"] + ) @commands.check(legal_channel) async def help_faq(self, ctx: commands.Context): - embed = get_team_embed(f'Paper Dynasty Help') - embed.description = 'Frequently Asked Questions' + embed = get_team_embed(f"Paper Dynasty Help") + embed.description = "Frequently Asked Questions" embed.add_field( - name='What the Heck is Paper Dynasty', - value=HELP_START_WHAT, - inline=False + name="What the Heck is Paper Dynasty", value=HELP_START_WHAT, inline=False ) + embed.add_field(name="How Do I Get Started", value=HELP_START_HOW, inline=False) + embed.add_field(name="How Do I Play", value=HELP_START_PLAY, inline=False) embed.add_field( - name='How Do I Get Started', - value=HELP_START_HOW, - inline=False - ) - embed.add_field( - name='How Do I Play', - value=HELP_START_PLAY, - inline=False - ) - embed.add_field( - name='Other Questions?', - value=f'Feel free to ask any questions down in {get_channel(ctx, "paper-dynasty-chat")} or check out ' - f'the other `/help-pd` commands for the FAQs!' - ) - await ctx.send( - content=None, - embed=embed + name="Other Questions?", + value=f"Feel free to ask any questions down in {get_channel(ctx, 'paper-dynasty-chat')} or check out " + f"the other `/help-pd` commands for the FAQs!", ) + await ctx.send(content=None, embed=embed) - @pd_help_command.command(name='links', help='Helpful links for Paper Dynasty') + @pd_help_command.command(name="links", help="Helpful links for Paper Dynasty") @commands.check(legal_channel) async def help_links(self, ctx: commands.Context): - current = await db_get('current') - embed = get_team_embed(f'Paper Dynasty Help') - embed.description = 'Resources & Links' + current = await db_get("current") + embed = get_team_embed(f"Paper Dynasty Help") + embed.description = "Resources & Links" embed.add_field( - name='Team Sheet Template', - value=f'{get_roster_sheet({"gsheet": current["gsheet_template"]})}' + name="Team Sheet Template", + value=f"{get_roster_sheet({'gsheet': current['gsheet_template']})}", ) embed.add_field( - name='Paper Dynasty Guidelines', - value='https://docs.google.com/document/d/1ngsjbz8wYv7heSiPMJ21oKPa6JLStTsw6wNdLDnt-k4/edit?usp=sharing', - inline=False - ) - embed.add_field( - name='Rules Reference', - value='https://docs.google.com/document/d/1wu63XSgfQE2wadiegWaaDda11QvqkN0liRurKm0vcTs/edit?usp=sharing', - inline=False - ) - await ctx.send(content=None, embed=embed) - - @pd_help_command.command(name='rewards', help='How to Earn Rewards in Paper Dynasty') - @commands.check(legal_channel) - async def help_rewards(self, ctx: commands.Context): - embed = get_team_embed(f'Paper Dynasty Help') - embed.description = 'How to Earn Rewards' - embed.add_field( - name='Premium Pack', - value=HELP_REWARDS_PREMIUM, - inline=False - ) - embed.add_field( - name='Standard Pack', - value=HELP_REWARDS_STANDARD, - inline=False - ) - embed.add_field( - name='MantiBucks ₼', - value=HELP_REWARDS_MONEY, - inline=False - ) - embed.add_field( - name='Ko-fi Shop', - value=HELP_REWARDS_SHOP, - inline=False - ) - await ctx.send(content=None, embed=embed) - - @pd_help_command.command(name='team-sheet', help='How to Use Your Team Sheet') - @commands.check(legal_channel) - async def help_team_sheet(self, ctx: commands.Context): - embed = get_team_embed(f'Paper Dynasty Help') - embed.description = 'How to Use Your Team Sheet' - embed.add_field( - name='Your Dashboard', - value=HELP_TS_DASH, - inline=False - ) - embed.add_field( - name='Roster Management', - value=HELP_TS_ROSTER, - inline=False - ) - embed.add_field( - name='Marketplace', - value=HELP_TS_MARKET, - inline=False - ) - embed.add_field( - name='Paper Dynasty Menu', - value=HELP_TS_MENU, - inline=False - ) - embed.set_footer( - text='More details to come', - icon_url=IMAGES['logo'] - ) - await ctx.send(content=None, embed=embed) - - @pd_help_command.command(name='gameplay', help='How to Play Paper Dynasty') - @commands.check(legal_channel) - async def help_gameplay(self, ctx: commands.Context): - embed = get_team_embed(f'Paper Dynasty Help') - embed.description = 'How to Play Paper Dynasty' - embed.add_field( - name='Game Modes', - value=HELP_GAMEMODES, - inline=False - ) - embed.add_field( - name='Start a New Game', - value=HELP_NEWGAME, + name="Paper Dynasty Guidelines", + value="https://docs.google.com/document/d/1ngsjbz8wYv7heSiPMJ21oKPa6JLStTsw6wNdLDnt-k4/edit?usp=sharing", inline=False, ) embed.add_field( - name='Playing the Game', - value=HELP_PLAYGAME, - inline=False - ) - embed.add_field( - name='Ending the Game', - value=f'{HELP_ENDGAME}\n' - f'- Go post highlights in {get_channel(ctx, "pd-news-ticker").mention}', - inline=False + name="Rules Reference", + value="https://docs.google.com/document/d/1wu63XSgfQE2wadiegWaaDda11QvqkN0liRurKm0vcTs/edit?usp=sharing", + inline=False, ) await ctx.send(content=None, embed=embed) - @pd_help_command.command(name='cardsets', help='Show Cardset Requirements') + @pd_help_command.command( + name="rewards", help="How to Earn Rewards in Paper Dynasty" + ) + @commands.check(legal_channel) + async def help_rewards(self, ctx: commands.Context): + embed = get_team_embed(f"Paper Dynasty Help") + embed.description = "How to Earn Rewards" + embed.add_field(name="Premium Pack", value=HELP_REWARDS_PREMIUM, inline=False) + embed.add_field(name="Standard Pack", value=HELP_REWARDS_STANDARD, inline=False) + embed.add_field(name="MantiBucks ₼", value=HELP_REWARDS_MONEY, inline=False) + embed.add_field(name="Ko-fi Shop", value=HELP_REWARDS_SHOP, inline=False) + await ctx.send(content=None, embed=embed) + + @pd_help_command.command(name="team-sheet", help="How to Use Your Team Sheet") + @commands.check(legal_channel) + async def help_team_sheet(self, ctx: commands.Context): + embed = get_team_embed(f"Paper Dynasty Help") + embed.description = "How to Use Your Team Sheet" + embed.add_field(name="Your Dashboard", value=HELP_TS_DASH, inline=False) + embed.add_field(name="Roster Management", value=HELP_TS_ROSTER, inline=False) + embed.add_field(name="Marketplace", value=HELP_TS_MARKET, inline=False) + embed.add_field(name="Paper Dynasty Menu", value=HELP_TS_MENU, inline=False) + embed.set_footer(text="More details to come", icon_url=IMAGES["logo"]) + await ctx.send(content=None, embed=embed) + + @pd_help_command.command(name="gameplay", help="How to Play Paper Dynasty") + @commands.check(legal_channel) + async def help_gameplay(self, ctx: commands.Context): + embed = get_team_embed(f"Paper Dynasty Help") + embed.description = "How to Play Paper Dynasty" + embed.add_field(name="Game Modes", value=HELP_GAMEMODES, inline=False) + embed.add_field( + name="Start a New Game", + value=HELP_NEWGAME, + inline=False, + ) + embed.add_field(name="Playing the Game", value=HELP_PLAYGAME, inline=False) + embed.add_field( + name="Ending the Game", + value=f"{HELP_ENDGAME}\n" + f"- Go post highlights in {get_channel(ctx, 'pd-news-ticker').mention}", + inline=False, + ) + await ctx.send(content=None, embed=embed) + + @pd_help_command.command(name="cardsets", help="Show Cardset Requirements") @commands.check(legal_channel) async def help_cardsets(self, ctx: commands.Context): - embed = get_team_embed(f'Paper Dynasty Help') - embed.description = 'Cardset Requirements' + embed = get_team_embed(f"Paper Dynasty Help") + embed.description = "Cardset Requirements" embed.add_field( - name='Ranked Legal', - value='2005, 2025 Seasons + Promos', - inline=False + name="Ranked Legal", value="2005, 2025 Seasons + Promos", inline=False ) embed.add_field( - name='Minor League', - value='Humans: Unlimited\nAI: 2005 Season / 2025 Season as backup', - inline=False + name="Minor League", + value="Humans: Unlimited\nAI: 2005 Season / 2025 Season as backup", + inline=False, ) embed.add_field( - name='Major League', - value='Humans: Ranked Legal\nAI: 2005, 2025, 2018, 2012 Seasons + Promos', - inline=False + name="Major League", + value="Humans: Ranked Legal\nAI: 2005, 2025, 2018, 2012 Seasons + Promos", + inline=False, ) embed.add_field( - name='Flashback', - value='2018, 2019, 2021, 2022 Seasons', - inline=False + name="Flashback", value="2018, 2019, 2021, 2022 Seasons", inline=False ) embed.add_field( - name='Hall of Fame', - value='Humans: Ranked Legal\nAI: Unlimited', - inline=False + name="Hall of Fame", + value="Humans: Ranked Legal\nAI: Unlimited", + inline=False, ) await ctx.send(content=None, embed=embed) - @commands.hybrid_group(name='donation', help='Mod: Give packs for PD donations') + @commands.hybrid_group(name="donation", help="Mod: Give packs for PD donations") @commands.has_any_role(PD_PLAYERS_ROLE_NAME) async def donation(self, ctx: commands.Context): if ctx.invoked_subcommand is None: - await ctx.send('To buy packs, visit https://ko-fi.com/manticorum/shop and include your discord username!') + await ctx.send( + "To buy packs, visit https://ko-fi.com/manticorum/shop and include your discord username!" + ) - @donation.command(name='premium', help='Mod: Give premium packs', aliases=['p', 'prem']) + @donation.command( + name="premium", help="Mod: Give premium packs", aliases=["p", "prem"] + ) async def donation_premium(self, ctx: commands.Context, num_packs: int, gm: Member): if ctx.author.id != self.bot.owner_id: - await ctx.send('Wait a second. You\'re not in charge here!') + await ctx.send("Wait a second. You're not in charge here!") return team = await get_team_by_owner(gm.id) - p_query = await db_get('packtypes', params=[('name', 'Premium')]) - if p_query['count'] == 0: - await ctx.send('Oof. I couldn\'t find a Premium Pack') + p_query = await db_get("packtypes", params=[("name", "Premium")]) + if p_query["count"] == 0: + await ctx.send("Oof. I couldn't find a Premium Pack") return - total_packs = await give_packs(team, num_packs, pack_type=p_query['packtypes'][0]) - await ctx.send(f'The {team["lname"]} now have {total_packs["count"]} total packs!') + total_packs = await give_packs( + team, num_packs, pack_type=p_query["packtypes"][0] + ) + await ctx.send( + f"The {team['lname']} now have {total_packs['count']} total packs!" + ) - @donation.command(name='standard', help='Mod: Give standard packs', aliases=['s', 'sta']) - async def donation_standard(self, ctx: commands.Context, num_packs: int, gm: Member): + @donation.command( + name="standard", help="Mod: Give standard packs", aliases=["s", "sta"] + ) + async def donation_standard( + self, ctx: commands.Context, num_packs: int, gm: Member + ): if ctx.author.id != self.bot.owner_id: - await ctx.send('Wait a second. You\'re not in charge here!') + await ctx.send("Wait a second. You're not in charge here!") return team = await get_team_by_owner(gm.id) - p_query = await db_get('packtypes', params=[('name', 'Standard')]) - if p_query['count'] == 0: - await ctx.send('Oof. I couldn\'t find a Standard Pack') + p_query = await db_get("packtypes", params=[("name", "Standard")]) + if p_query["count"] == 0: + await ctx.send("Oof. I couldn't find a Standard Pack") return - total_packs = await give_packs(team, num_packs, pack_type=p_query['packtypes'][0]) - await ctx.send(f'The {team["lname"]} now have {total_packs["count"]} total packs!') + total_packs = await give_packs( + team, num_packs, pack_type=p_query["packtypes"][0] + ) + await ctx.send( + f"The {team['lname']} now have {total_packs['count']} total packs!" + ) - @commands.hybrid_command(name='lastpack', help='Replay your last pack') + @commands.hybrid_command(name="lastpack", help="Replay your last pack") @commands.check(legal_channel) @commands.has_any_role(PD_PLAYERS_ROLE_NAME) async def last_pack_command(self, ctx: commands.Context): team = await get_team_by_owner(ctx.author.id) if not team: - await ctx.send(f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!') + await ctx.send( + f"I don't see a team for you, yet. You can sign up with the `/newteam` command!" + ) return p_query = await db_get( - 'packs', - params=[('opened', True), ('team_id', team['id']), ('new_to_old', True), ('limit', 1)] + "packs", + params=[ + ("opened", True), + ("team_id", team["id"]), + ("new_to_old", True), + ("limit", 1), + ], ) - if not p_query['count']: - await ctx.send(f'I do not see any packs for you, bub.') + if not p_query["count"]: + await ctx.send(f"I do not see any packs for you, bub.") return - pack_name = p_query['packs'][0]['pack_type']['name'] - if pack_name == 'Standard': - pack_cover = IMAGES['pack-sta'] - elif pack_name == 'Premium': - pack_cover = IMAGES['pack-pre'] + pack_name = p_query["packs"][0]["pack_type"]["name"] + if pack_name == "Standard": + pack_cover = IMAGES["pack-sta"] + elif pack_name == "Premium": + pack_cover = IMAGES["pack-pre"] else: pack_cover = None - c_query = await db_get( - 'cards', - params=[('pack_id', p_query['packs'][0]['id'])] - ) - if not c_query['count']: - await ctx.send(f'Hmm...I didn\'t see any cards in that pack.') + c_query = await db_get("cards", params=[("pack_id", p_query["packs"][0]["id"])]) + if not c_query["count"]: + await ctx.send(f"Hmm...I didn't see any cards in that pack.") return - await display_cards(c_query['cards'], team, ctx.channel, ctx.author, self.bot, pack_cover=pack_cover) + await display_cards( + c_query["cards"], + team, + ctx.channel, + ctx.author, + self.bot, + pack_cover=pack_cover, + ) - @app_commands.command(name='comeonmanineedthis', description='Daily check-in for cards, currency, and packs') + @app_commands.command( + name="comeonmanineedthis", + description="Daily check-in for cards, currency, and packs", + ) @app_commands.checks.has_any_role(PD_PLAYERS) @app_legal_channel() async def daily_checkin(self, interaction: discord.Interaction): @@ -525,35 +519,53 @@ class Economy(commands.Cog): team = await get_team_by_owner(interaction.user.id) if not team: await interaction.edit_original_response( - content=f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!' + content=f"I don't see a team for you, yet. You can sign up with the `/newteam` command!" ) return - current = await db_get('current') + current = await db_get("current") now = datetime.datetime.now() - midnight = int_timestamp(datetime.datetime(now.year, now.month, now.day, 0, 0, 0)) - daily = await db_get('rewards', params=[ - ('name', 'Daily Check-in'), ('team_id', team['id']), ('created_after', midnight) - ]) - logger.debug(f'midnight: {midnight} / now: {int_timestamp(now)}') - logger.debug(f'daily_return: {daily}') + midnight = int_timestamp( + datetime.datetime(now.year, now.month, now.day, 0, 0, 0) + ) + daily = await db_get( + "rewards", + params=[ + ("name", "Daily Check-in"), + ("team_id", team["id"]), + ("created_after", midnight), + ], + ) + logger.debug(f"midnight: {midnight} / now: {int_timestamp(now)}") + logger.debug(f"daily_return: {daily}") if daily: await interaction.edit_original_response( - content=f'Looks like you already checked in today - come back at midnight Central!' + content=f"Looks like you already checked in today - come back at midnight Central!" ) return - await db_post('rewards', payload={ - 'name': 'Daily Check-in', 'team_id': team['id'], 'season': current['season'], 'week': current['week'], - 'created': int_timestamp(now) - }) - current = await db_get('current') - check_ins = await db_get('rewards', params=[ - ('name', 'Daily Check-in'), ('team_id', team['id']), ('season', current['season']) - ]) + await db_post( + "rewards", + payload={ + "name": "Daily Check-in", + "team_id": team["id"], + "season": current["season"], + "week": current["week"], + "created": int_timestamp(now), + }, + ) + current = await db_get("current") + check_ins = await db_get( + "rewards", + params=[ + ("name", "Daily Check-in"), + ("team_id", team["id"]), + ("season", current["season"]), + ], + ) - check_count = check_ins['count'] % 5 + check_count = check_ins["count"] % 5 # TODO: complete the migration to an interaction # 2nd, 4th, and 5th check-ins @@ -561,62 +573,74 @@ class Economy(commands.Cog): # Every fifth check-in if check_count == 0: greeting = await interaction.edit_original_response( - content=f'Hey, you just earned a Standard pack of cards!' + content=f"Hey, you just earned a Standard pack of cards!" ) - pack_channel = get_channel(interaction, 'pack-openings') + pack_channel = get_channel(interaction, "pack-openings") - p_query = await db_get('packtypes', params=[('name', 'Standard')]) + p_query = await db_get("packtypes", params=[("name", "Standard")]) if not p_query: await interaction.edit_original_response( - content=f'I was not able to pull this pack for you. ' - f'Maybe ping {get_cal_user(interaction).mention}?' + content=f"I was not able to pull this pack for you. " + f"Maybe ping {get_cal_user(interaction).mention}?" ) return # Every second and fourth check-in else: greeting = await interaction.edit_original_response( - content=f'Hey, you just earned a player card!' + content=f"Hey, you just earned a player card!" ) pack_channel = interaction.channel - p_query = await db_get('packtypes', params=[('name', 'Check-In Player')]) + p_query = await db_get( + "packtypes", params=[("name", "Check-In Player")] + ) if not p_query: await interaction.edit_original_response( - content=f'I was not able to pull this card for you. ' - f'Maybe ping {get_cal_user(interaction).mention}?' + content=f"I was not able to pull this card for you. " + f"Maybe ping {get_cal_user(interaction).mention}?" ) return - await give_packs(team, 1, p_query['packtypes'][0]) + await give_packs(team, 1, p_query["packtypes"][0]) p_query = await db_get( - 'packs', - params=[('opened', False), ('team_id', team['id']), ('new_to_old', True), ('limit', 1)] + "packs", + params=[ + ("opened", False), + ("team_id", team["id"]), + ("new_to_old", True), + ("limit", 1), + ], ) - if not p_query['count']: + if not p_query["count"]: await interaction.edit_original_response( - content=f'I do not see any packs in here. {await get_emoji(interaction, "ConfusedPsyduck")}') + content=f"I do not see any packs in here. {await get_emoji(interaction, 'ConfusedPsyduck')}" + ) return - pack_ids = await roll_for_cards(p_query['packs'], extra_val=check_ins['count']) + pack_ids = await roll_for_cards( + p_query["packs"], extra_val=check_ins["count"] + ) if not pack_ids: await greeting.edit( - content=f'I was not able to create these cards {await get_emoji(interaction, "slight_frown")}' + content=f"I was not able to create these cards {await get_emoji(interaction, 'slight_frown')}" ) return all_cards = [] for p_id in pack_ids: - new_cards = await db_get('cards', params=[('pack_id', p_id)]) - all_cards.extend(new_cards['cards']) + new_cards = await db_get("cards", params=[("pack_id", p_id)]) + all_cards.extend(new_cards["cards"]) if not all_cards: await interaction.edit_original_response( - content=f'I was not able to pull these cards {await get_emoji(interaction, "slight_frown")}' + content=f"I was not able to pull these cards {await get_emoji(interaction, 'slight_frown')}" ) return - await display_cards(all_cards, team, pack_channel, interaction.user, self.bot) + await display_cards( + all_cards, team, pack_channel, interaction.user, self.bot + ) await refresh_sheet(team, self.bot) return @@ -634,87 +658,94 @@ class Economy(commands.Cog): else: m_reward = 25 - team = await db_post(f'teams/{team["id"]}/money/{m_reward}') + team = await db_post(f"teams/{team['id']}/money/{m_reward}") await interaction.edit_original_response( - content=f'You just earned {m_reward}₼! That brings your wallet to {team["wallet"]}₼!') + content=f"You just earned {m_reward}₼! That brings your wallet to {team['wallet']}₼!" + ) - @app_commands.command(name='open-packs', description='Open packs from your inventory') + @app_commands.command( + name="open-packs", description="Open packs from your inventory" + ) @app_commands.checks.has_any_role(PD_PLAYERS) async def open_packs_slash(self, interaction: discord.Interaction): - if interaction.channel.name in ['paper-dynasty-chat', 'pd-news-ticker', 'pd-network-news']: + if interaction.channel.name in [ + "paper-dynasty-chat", + "pd-news-ticker", + "pd-network-news", + ]: await interaction.response.send_message( - f'Please head to down to {get_channel(interaction, "pd-bot-hole")} to run this command.', - ephemeral=True + f"Please head to down to {get_channel(interaction, 'pd-bot-hole')} to run this command.", + ephemeral=True, ) return owner_team = await get_team_by_owner(interaction.user.id) if not owner_team: await interaction.response.send_message( - f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!' + f"I don't see a team for you, yet. You can sign up with the `/newteam` command!" ) return - p_query = await db_get('packs', params=[ - ('team_id', owner_team['id']), ('opened', False) - ]) - if p_query['count'] == 0: + p_query = await db_get( + "packs", params=[("team_id", owner_team["id"]), ("opened", False)] + ) + if p_query["count"] == 0: await interaction.response.send_message( - f'Looks like you are clean out of packs, friendo. You can earn them by playing PD games or by ' - f'donating to the league.' + f"Looks like you are clean out of packs, friendo. You can earn them by playing PD games or by " + f"donating to the league." ) return # Group packs by type and customization (e.g. Standard, Standard-Orioles, Standard-2012, Premium) p_count = 0 p_data = { - 'Standard': [], - 'Premium': [], - 'Daily': [], - 'MVP': [], - 'All Star': [], - 'Mario': [], - 'Team Choice': [] + "Standard": [], + "Premium": [], + "Daily": [], + "MVP": [], + "All Star": [], + "Mario": [], + "Team Choice": [], } - logger.debug(f'Parsing packs...') - for pack in p_query['packs']: + logger.debug(f"Parsing packs...") + for pack in p_query["packs"]: p_group = None - logger.debug(f'pack: {pack}') - logger.debug(f'pack cardset: {pack["pack_cardset"]}') - if pack['pack_team'] is None and pack['pack_cardset'] is None: - p_group = pack['pack_type']['name'] + logger.debug(f"pack: {pack}") + logger.debug(f"pack cardset: {pack['pack_cardset']}") + if pack["pack_team"] is None and pack["pack_cardset"] is None: + p_group = pack["pack_type"]["name"] # Add to p_data if this is a new pack type if p_group not in p_data: p_data[p_group] = [] - elif pack['pack_team'] is not None: - if pack['pack_type']['name'] == 'Standard': - p_group = f'Standard-Team-{pack["pack_team"]["id"]}-{pack["pack_team"]["sname"]}' - elif pack['pack_type']['name'] == 'Premium': - p_group = f'Premium-Team-{pack["pack_team"]["id"]}-{pack["pack_team"]["sname"]}' - elif pack['pack_type']['name'] == 'Team Choice': - p_group = f'Team Choice-Team-{pack["pack_team"]["id"]}-{pack["pack_team"]["sname"]}' - elif pack['pack_type']['name'] == 'MVP': - p_group = f'MVP-Team-{pack["pack_team"]["id"]}-{pack["pack_team"]["sname"]}' + elif pack["pack_team"] is not None: + if pack["pack_type"]["name"] == "Standard": + p_group = f"Standard-Team-{pack['pack_team']['id']}-{pack['pack_team']['sname']}" + elif pack["pack_type"]["name"] == "Premium": + p_group = f"Premium-Team-{pack['pack_team']['id']}-{pack['pack_team']['sname']}" + elif pack["pack_type"]["name"] == "Team Choice": + p_group = f"Team Choice-Team-{pack['pack_team']['id']}-{pack['pack_team']['sname']}" + elif pack["pack_type"]["name"] == "MVP": + p_group = f"MVP-Team-{pack['pack_team']['id']}-{pack['pack_team']['sname']}" - if pack['pack_cardset'] is not None: - p_group += f'-Cardset-{pack["pack_cardset"]["id"]}' + if pack["pack_cardset"] is not None: + p_group += f"-Cardset-{pack['pack_cardset']['id']}" - elif pack['pack_cardset'] is not None: - if pack['pack_type']['name'] == 'Standard': - p_group = f'Standard-Cardset-{pack["pack_cardset"]["id"]}-{pack["pack_cardset"]["name"]}' - elif pack['pack_type']['name'] == 'Premium': - p_group = f'Premium-Cardset-{pack["pack_cardset"]["id"]}-{pack["pack_cardset"]["name"]}' - elif pack['pack_type']['name'] == 'Team Choice': - p_group = f'Team Choice-Cardset-{pack["pack_cardset"]["id"]}-{pack["pack_cardset"]["name"]}' - elif pack['pack_type']['name'] == 'All Star': - p_group = f'All Star-Cardset-{pack["pack_cardset"]["id"]}-{pack["pack_cardset"]["name"]}' - elif pack['pack_type']['name'] == 'MVP': - p_group = f'MVP-Cardset-{pack["pack_cardset"]["id"]}-{pack["pack_cardset"]["name"]}' - elif pack['pack_type']['name'] == 'Promo Choice': - p_group = f'Promo Choice-Cardset-{pack["pack_cardset"]["id"]}-{pack["pack_cardset"]["name"]}' + elif pack["pack_cardset"] is not None: + if pack["pack_type"]["name"] == "Standard": + p_group = f"Standard-Cardset-{pack['pack_cardset']['id']}-{pack['pack_cardset']['name']}" + elif pack["pack_type"]["name"] == "Premium": + p_group = f"Premium-Cardset-{pack['pack_cardset']['id']}-{pack['pack_cardset']['name']}" + elif pack["pack_type"]["name"] == "Team Choice": + p_group = f"Team Choice-Cardset-{pack['pack_cardset']['id']}-{pack['pack_cardset']['name']}" + elif pack["pack_type"]["name"] == "All Star": + p_group = f"All Star-Cardset-{pack['pack_cardset']['id']}-{pack['pack_cardset']['name']}" + elif pack["pack_type"]["name"] == "MVP": + p_group = f"MVP-Cardset-{pack['pack_cardset']['id']}-{pack['pack_cardset']['name']}" + elif pack["pack_type"]["name"] == "Promo Choice": + p_group = f"Promo Choice-Cardset-{pack['pack_cardset']['id']}-{pack['pack_cardset']['name']}" - logger.info(f'p_group: {p_group}') + logger.info(f"p_group: {p_group}") if p_group is not None: p_count += 1 if p_group not in p_data: @@ -724,327 +755,390 @@ class Economy(commands.Cog): if p_count == 0: await interaction.response.send_message( - f'Looks like you are clean out of packs, friendo. You can earn them by playing PD games or by ' - f'donating to the league.' + f"Looks like you are clean out of packs, friendo. You can earn them by playing PD games or by " + f"donating to the league." ) return # Display options and ask which group to open - embed = get_team_embed(f'Unopened Packs', team=owner_team) - embed.description = owner_team['lname'] + embed = get_team_embed(f"Unopened Packs", team=owner_team) + embed.description = owner_team["lname"] select_options = [] for key in p_data: if len(p_data[key]) > 0: pretty_name = None # Not a specific pack - if '-' not in key: + if "-" not in key: pretty_name = key - elif 'Team' in key: - pretty_name = f'{key.split("-")[0]} - {key.split("-")[3]}' - elif 'Cardset' in key: - pretty_name = f'{key.split("-")[0]} - {key.split("-")[3]}' + elif "Team" in key: + pretty_name = f"{key.split('-')[0]} - {key.split('-')[3]}" + elif "Cardset" in key: + pretty_name = f"{key.split('-')[0]} - {key.split('-')[3]}" if pretty_name is not None: - embed.add_field(name=pretty_name, value=f'Qty: {len(p_data[key])}') - select_options.append(discord.SelectOption(label=pretty_name, value=key)) + embed.add_field(name=pretty_name, value=f"Qty: {len(p_data[key])}") + select_options.append( + discord.SelectOption(label=pretty_name, value=key) + ) - view = SelectView(select_objects=[SelectOpenPack(select_options, owner_team)], timeout=15) + view = SelectView( + select_objects=[SelectOpenPack(select_options, owner_team)], timeout=15 + ) await interaction.response.send_message(embed=embed, view=view) - group_buy = app_commands.Group(name='buy', description='Make a purchase from the marketplace') + group_buy = app_commands.Group( + name="buy", description="Make a purchase from the marketplace" + ) - @group_buy.command(name='card-by-id', description='Buy a player card from the marketplace') + @group_buy.command( + name="card-by-id", description="Buy a player card from the marketplace" + ) @app_commands.checks.has_any_role(PD_PLAYERS) async def buy_card_id_slash(self, interaction: discord.Interaction, player_id: int): - if interaction.channel.name in ['paper-dynasty-chat', 'pd-news-ticker', 'pd-network-news']: + if interaction.channel.name in [ + "paper-dynasty-chat", + "pd-news-ticker", + "pd-network-news", + ]: await interaction.response.send_message( - f'Please head to down to {get_channel(interaction, "pd-bot-hole")} to run this command.', - ephemeral=True + f"Please head to down to {get_channel(interaction, 'pd-bot-hole')} to run this command.", + ephemeral=True, ) return owner_team = await get_team_by_owner(interaction.user.id) if not owner_team: await interaction.response.send_message( - f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!' + f"I don't see a team for you, yet. You can sign up with the `/newteam` command!" ) - p_query = await db_get('players', object_id=player_id, none_okay=False) - logger.debug(f'this_player: {p_query}') + p_query = await db_get("players", object_id=player_id, none_okay=False) + logger.debug(f"this_player: {p_query}") await self.buy_card(interaction, p_query, owner_team) - @group_buy.command(name='card-by-name', description='Buy a player card from the marketplace') + @group_buy.command( + name="card-by-name", description="Buy a player card from the marketplace" + ) @app_commands.checks.has_any_role(PD_PLAYERS) @app_commands.describe( - player_name='Name of the player you want to purchase', - player_cardset='Optional: Name of the cardset the player is from' + player_name="Name of the player you want to purchase", + player_cardset="Optional: Name of the cardset the player is from", ) async def buy_card_slash( - self, interaction: discord.Interaction, player_name: str, player_cardset: Optional[str] = None): - if interaction.channel.name in ['paper-dynasty-chat', 'pd-news-ticker', 'pd-network-news']: + self, + interaction: discord.Interaction, + player_name: str, + player_cardset: Optional[str] = None, + ): + if interaction.channel.name in [ + "paper-dynasty-chat", + "pd-news-ticker", + "pd-network-news", + ]: await interaction.response.send_message( - f'Please head to down to {get_channel(interaction, "pd-bot-hole")} to run this command.', - ephemeral=True + f"Please head to down to {get_channel(interaction, 'pd-bot-hole')} to run this command.", + ephemeral=True, ) return owner_team = await get_team_by_owner(interaction.user.id) if not owner_team: await interaction.response.send_message( - f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!' + f"I don't see a team for you, yet. You can sign up with the `/newteam` command!" ) - player_cog = self.bot.get_cog('Players') + player_cog = self.bot.get_cog("Players") proper_name = fuzzy_search(player_name, player_cog.player_list) if not proper_name: - await interaction.response.send_message(f'No clue who that is.') + await interaction.response.send_message(f"No clue who that is.") return - all_params = [('name', proper_name)] + all_params = [("name", proper_name)] if player_cardset: this_cardset = await cardset_search(player_cardset, player_cog.cardset_list) - all_params.append(('cardset_id', this_cardset['id'])) + all_params.append(("cardset_id", this_cardset["id"])) - p_query = await db_get('players', params=all_params) + p_query = await db_get("players", params=all_params) - if p_query['count'] == 0: + if p_query["count"] == 0: await interaction.response.send_message( - f'I didn\'t find any cards for {proper_name}' + f"I didn't find any cards for {proper_name}" ) return - if p_query['count'] > 1: + if p_query["count"] > 1: await interaction.response.send_message( - f'I found {p_query["count"]} different cards for {proper_name}. Would you please run this again ' - f'with the cardset specified?' + f"I found {p_query['count']} different cards for {proper_name}. Would you please run this again " + f"with the cardset specified?" ) return - this_player = p_query['players'][0] - logger.debug(f'this_player: {this_player}') + this_player = p_query["players"][0] + logger.debug(f"this_player: {this_player}") await self.buy_card(interaction, this_player, owner_team) - @group_buy.command(name='pack', description='Buy a pack or 7 from the marketplace') + @group_buy.command(name="pack", description="Buy a pack or 7 from the marketplace") @app_commands.checks.has_any_role(PD_PLAYERS) @app_commands.describe() async def buy_pack_slash(self, interaction: discord.Interaction): - if interaction.channel.name in ['paper-dynasty-chat', 'pd-news-ticker', 'pd-network-news']: + if interaction.channel.name in [ + "paper-dynasty-chat", + "pd-news-ticker", + "pd-network-news", + ]: await interaction.response.send_message( - f'Please head to down to {get_channel(interaction, "pd-bot-hole")} to run this command.', - ephemeral=True + f"Please head to down to {get_channel(interaction, 'pd-bot-hole')} to run this command.", + ephemeral=True, ) return owner_team = await get_team_by_owner(interaction.user.id) if not owner_team: await interaction.response.send_message( - f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!' + f"I don't see a team for you, yet. You can sign up with the `/newteam` command!" ) - p_query = await db_get('packtypes', params=[('available', True)]) - if 'count' not in p_query: + p_query = await db_get("packtypes", params=[("available", True)]) + if "count" not in p_query: await interaction.response.send_message( - f'Welp, I couldn\'t find any packs in my database. Should probably go ping ' - f'{get_cal_user(interaction).mention} about that.' + f"Welp, I couldn't find any packs in my database. Should probably go ping " + f"{get_cal_user(interaction).mention} about that." ) return - embed = get_team_embed('Packs for Purchase') + embed = get_team_embed("Packs for Purchase") # embed.description = 'Run `/buy pack `' - for x in p_query['packtypes']: - embed.add_field(name=f'{x["name"]} - {x["cost"]}₼', value=f'{x["description"]}') + for x in p_query["packtypes"]: + embed.add_field( + name=f"{x['name']} - {x['cost']}₼", value=f"{x['description']}" + ) - pack_options = [x['name'] for x in p_query['packtypes'][:5] if x['available'] and x['cost']] + pack_options = [ + x["name"] for x in p_query["packtypes"][:5] if x["available"] and x["cost"] + ] if len(pack_options) < 5: - pack_options.extend(['na' for x in range(5 - len(pack_options))]) + pack_options.extend(["na" for x in range(5 - len(pack_options))]) view = ButtonOptions( - responders=[interaction.user], timeout=60, - labels=pack_options + responders=[interaction.user], timeout=60, labels=pack_options ) - await interaction.response.send_message( - content=None, - embed=embed - ) + await interaction.response.send_message(content=None, embed=embed) question = await interaction.channel.send( - f'Which pack would you like to purchase?', view=view + f"Which pack would you like to purchase?", view=view ) await view.wait() if view.value: pack_name = view.value await question.delete() - this_q = Question(self.bot, interaction.channel, 'How many would you like?', 'int', 60) + this_q = Question( + self.bot, interaction.channel, "How many would you like?", "int", 60 + ) num_packs = await this_q.ask([interaction.user]) else: await question.delete() - await interaction.channel.send('Hm. Another window shopper. I\'ll be here when you\'re serious.') + await interaction.channel.send( + "Hm. Another window shopper. I'll be here when you're serious." + ) return p_query = await db_get( - 'packtypes', params=[('name', pack_name.lower().replace('pack', '')), ('available', True)] + "packtypes", + params=[ + ("name", pack_name.lower().replace("pack", "")), + ("available", True), + ], ) - if 'count' not in p_query: + if "count" not in p_query: await interaction.channel.send( - f'Hmm...I don\'t recognize {pack_name.title()} as a pack type. Check on that and get back to me.', - ephemeral=True + f"Hmm...I don't recognize {pack_name.title()} as a pack type. Check on that and get back to me.", + ephemeral=True, ) return - pack_type = p_query['packtypes'][0] + pack_type = p_query["packtypes"][0] - pack_cover = IMAGES['logo'] - if pack_type['name'] == 'Standard': - pack_cover = IMAGES['pack-sta'] - elif pack_type['name'] == 'Premium': - pack_cover = IMAGES['pack-pre'] - elif pack_type['name'] == 'Promo Choice': - pack_cover = IMAGES['mvp-hype'] + pack_cover = IMAGES["logo"] + if pack_type["name"] == "Standard": + pack_cover = IMAGES["pack-sta"] + elif pack_type["name"] == "Premium": + pack_cover = IMAGES["pack-pre"] + elif pack_type["name"] == "Promo Choice": + pack_cover = IMAGES["mvp-hype"] - total_cost = pack_type['cost'] * num_packs + total_cost = pack_type["cost"] * num_packs pack_embed = image_embed( pack_cover, - title=f'{owner_team["lname"]}', - desc=f'{num_packs if num_packs > 1 else ""}{"x " if num_packs > 1 else ""}' - f'{pack_type["name"]} Pack{"s" if num_packs != 1 else ""}', + title=f"{owner_team['lname']}", + desc=f"{num_packs if num_packs > 1 else ''}{'x ' if num_packs > 1 else ''}" + f"{pack_type['name']} Pack{'s' if num_packs != 1 else ''}", ) - if total_cost > owner_team['wallet']: + if total_cost > owner_team["wallet"]: + await interaction.channel.send(content=None, embed=pack_embed) await interaction.channel.send( - content=None, - embed=pack_embed - ) - await interaction.channel.send( - content=f'Your Wallet: {owner_team["wallet"]}₼\n' - f'Pack{"s" if num_packs > 1 else ""} Price: {total_cost}₼\n' - f'After Purchase: {await get_emoji(interaction.guild, "dead", False)}\n\n' - f'You will have to save up a little more.' + content=f"Your Wallet: {owner_team['wallet']}₼\n" + f"Pack{'s' if num_packs > 1 else ''} Price: {total_cost}₼\n" + f"After Purchase: {await get_emoji(interaction.guild, 'dead', False)}\n\n" + f"You will have to save up a little more." ) return # Get Customization and make purchase - if pack_name in ['Standard', 'Premium']: + if pack_name in ["Standard", "Premium"]: view = ButtonOptions( [interaction.user], timeout=15, - labels=['No Customization', 'Cardset', 'Franchise', None, None] + labels=["No Customization", "Cardset", "Franchise", None, None], ) view.option1.style = discord.ButtonStyle.danger await interaction.channel.send( - content='Would you like to apply a pack customization?', + content="Would you like to apply a pack customization?", embed=pack_embed, - view=view + view=view, ) await view.wait() if not view.value: - await interaction.channel.send(f'You think on it and get back to me.') + await interaction.channel.send(f"You think on it and get back to me.") return - elif view.value == 'Cardset': - # await interaction.delete_original_response() - view = SelectView([SelectBuyPacksCardset(owner_team, num_packs, pack_type['id'], pack_embed, total_cost)]) - await interaction.channel.send( - content=None, - view=view - ) - return - elif view.value == 'Franchise': + elif view.value == "Cardset": # await interaction.delete_original_response() view = SelectView( [ - SelectBuyPacksTeam('AL', owner_team, num_packs, pack_type['id'], pack_embed, total_cost), - SelectBuyPacksTeam('NL', owner_team, num_packs, pack_type['id'], pack_embed, total_cost) + SelectBuyPacksCardset( + owner_team, + num_packs, + pack_type["id"], + pack_embed, + total_cost, + ) + ] + ) + await interaction.channel.send(content=None, view=view) + return + elif view.value == "Franchise": + # await interaction.delete_original_response() + view = SelectView( + [ + SelectBuyPacksTeam( + "AL", + owner_team, + num_packs, + pack_type["id"], + pack_embed, + total_cost, + ), + SelectBuyPacksTeam( + "NL", + owner_team, + num_packs, + pack_type["id"], + pack_embed, + total_cost, + ), ], - timeout=30 - ) - await interaction.channel.send( - content=None, - view=view + timeout=30, ) + await interaction.channel.send(content=None, view=view) return - question = await confirm_pack_purchase(interaction, owner_team, num_packs, total_cost, pack_embed) + question = await confirm_pack_purchase( + interaction, owner_team, num_packs, total_cost, pack_embed + ) if question is None: return purchase = await db_get( - f'teams/{owner_team["id"]}/buy/pack/{pack_type["id"]}', - params=[('ts', team_hash(owner_team)), ('quantity', num_packs)] + f"teams/{owner_team['id']}/buy/pack/{pack_type['id']}", + params=[("ts", team_hash(owner_team)), ("quantity", num_packs)], ) if not purchase: await question.edit( - f'That didn\'t go through for some reason. If this happens again, go ping the shit out of Cal.', - view=None + f"That didn't go through for some reason. If this happens again, go ping the shit out of Cal.", + view=None, ) return await question.edit( - content=f'{"They are" if num_packs > 1 else "It is"} all yours! Go rip \'em with `/open-packs`', - view=None + content=f"{'They are' if num_packs > 1 else 'It is'} all yours! Go rip 'em with `/open-packs`", + view=None, ) return - @app_commands.command(name='selldupes', description='Sell all of your duplicate cards') + @app_commands.command( + name="selldupes", description="Sell all of your duplicate cards" + ) @app_commands.checks.has_any_role(PD_PLAYERS) @app_legal_channel() @app_commands.describe( - immediately='Skip all prompts and sell dupes immediately; default False', - skip_live='Skip all live series cards; default True' + immediately="Skip all prompts and sell dupes immediately; default False", + skip_live="Skip all live series cards; default True", ) async def sell_dupes_command( - self, interaction: discord.Interaction, skip_live: bool = True, immediately: bool = False): + self, + interaction: discord.Interaction, + skip_live: bool = True, + immediately: bool = False, + ): team = await get_team_by_owner(interaction.user.id) if not team: await interaction.response.send_message( - f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!', - ephemeral=True + f"I don't see a team for you, yet. You can sign up with the `/newteam` command!", + ephemeral=True, ) return await interaction.response.send_message( - f'Let me flip through your cards. This could take a while if you have a ton of cards...' + f"Let me flip through your cards. This could take a while if you have a ton of cards..." ) try: - c_query = await db_get('cards', params=[('team_id', team['id']), ('dupes', True)], timeout=15) + c_query = await db_get( + "cards", params=[("team_id", team["id"]), ("dupes", True)], timeout=15 + ) except Exception as e: await interaction.edit_original_response( - content=f'{e}\n\nSounds like a {get_cal_user(interaction).mention} problem tbh' + content=f"{e}\n\nSounds like a {get_cal_user(interaction).mention} problem tbh" ) return player_ids = [] - dupe_ids = '' + dupe_ids = "" dupe_cards = [] - dupe_strings = ['' for x in range(20)] + dupe_strings = ["" for x in range(20)] str_count = 0 - for card in c_query['cards']: + for card in c_query["cards"]: if len(dupe_strings[str_count]) > 1500: str_count += 1 - logger.debug(f'card: {card}') - if skip_live and (card['player']['cardset']['id'] == LIVE_CARDSET_ID): - logger.debug(f'live series card - skipping') - elif card['player']['player_id'] not in player_ids: - logger.debug(f'not a dupe') - player_ids.append(card['player']['player_id']) + logger.debug(f"card: {card}") + if skip_live and (card["player"]["cardset"]["id"] == LIVE_CARDSET_ID): + logger.debug(f"live series card - skipping") + elif card["player"]["player_id"] not in player_ids: + logger.debug(f"not a dupe") + player_ids.append(card["player"]["player_id"]) else: - logger.info(f'{team["abbrev"]} duplicate card: {card["id"]}') + logger.info(f"{team['abbrev']} duplicate card: {card['id']}") dupe_cards.append(card) - dupe_ids += f'{card["id"]},' - dupe_strings[str_count] += f'{card["player"]["rarity"]["name"]} {card["player"]["p_name"]} - ' \ - f'{card["player"]["cardset"]["name"]}\n' + dupe_ids += f"{card['id']}," + dupe_strings[str_count] += ( + f"{card['player']['rarity']['name']} {card['player']['p_name']} - " + f"{card['player']['cardset']['name']}\n" + ) if len(dupe_cards) == 0: - await interaction.edit_original_response(content=f'You currently have 0 duplicate cards!') + await interaction.edit_original_response( + content=f"You currently have 0 duplicate cards!" + ) return - logger.info(f'sending first message / length {len(dupe_strings[0])}') + logger.info(f"sending first message / length {len(dupe_strings[0])}") await interaction.edit_original_response( - content=f'You currently have {len(dupe_cards)} duplicate cards:\n\n{dupe_strings[0]}' + content=f"You currently have {len(dupe_cards)} duplicate cards:\n\n{dupe_strings[0]}" ) for x in dupe_strings[1:]: - logger.info(f'checking string: {len(x)}') + logger.info(f"checking string: {len(x)}") if len(x) > 0: await interaction.channel.send(x) else: @@ -1052,139 +1146,152 @@ class Economy(commands.Cog): if not immediately: view = Confirm(responders=[interaction.user]) - question = await interaction.channel.send('Would you like to sell all of them?', view=view) + question = await interaction.channel.send( + "Would you like to sell all of them?", view=view + ) await view.wait() if not view.value: - await question.edit( - content='We can leave them be for now.', - view=None - ) + await question.edit(content="We can leave them be for now.", view=None) return - await question.edit(content=f'The sale is going through...', view=None) + await question.edit(content=f"The sale is going through...", view=None) # for card in dupe_cards: sale = await db_get( - f'teams/{team["id"]}/sell/cards', - params=[('ts', team_hash(team)), ('ids', dupe_ids)], - timeout=10 + f"teams/{team['id']}/sell/cards", + params=[("ts", team_hash(team)), ("ids", dupe_ids)], + timeout=10, ) if not sale: await interaction.channel.send( - f'That didn\'t go through for some reason. Go ping the shit out of {get_cal_user(interaction).mention}.' + f"That didn't go through for some reason. Go ping the shit out of {get_cal_user(interaction).mention}." ) return - team = await db_get('teams', object_id=team['id']) - await interaction.channel.send(f'Your Wallet: {team["wallet"]}₼') + team = await db_get("teams", object_id=team["id"]) + await interaction.channel.send(f"Your Wallet: {team['wallet']}₼") - @app_commands.command(name='newteam', description='Get your fresh team for a new season') + @app_commands.command( + name="newteam", description="Get your fresh team for a new season" + ) @app_commands.checks.has_any_role(PD_PLAYERS) @app_commands.describe( - gm_name='The fictional name of your team\'s GM', - team_abbrev='2, 3, or 4 character abbreviation (e.g. WV, ATL, MAD)', - team_full_name='City/location and name (e.g. Baltimore Orioles)', - team_short_name='Name of team (e.g. Yankees)', - mlb_anchor_team='2 or 3 character abbreviation of your anchor MLB team (e.g. NYM, MKE)', - team_logo_url='[Optional] URL ending in .png or .jpg for your team logo', - color='[Optional] Hex color code to highlight your team' + gm_name="The fictional name of your team's GM", + team_abbrev="2, 3, or 4 character abbreviation (e.g. WV, ATL, MAD)", + team_full_name="City/location and name (e.g. Baltimore Orioles)", + team_short_name="Name of team (e.g. Yankees)", + mlb_anchor_team="2 or 3 character abbreviation of your anchor MLB team (e.g. NYM, MKE)", + team_logo_url="[Optional] URL ending in .png or .jpg for your team logo", + color="[Optional] Hex color code to highlight your team", ) async def new_team_slash( - self, interaction: discord.Interaction, gm_name: str, team_abbrev: str, team_full_name: str, - team_short_name: str, mlb_anchor_team: str, team_logo_url: str = None, color: str = None): + self, + interaction: discord.Interaction, + gm_name: str, + team_abbrev: str, + team_full_name: str, + team_short_name: str, + mlb_anchor_team: str, + team_logo_url: str = None, + color: str = None, + ): owner_team = await get_team_by_owner(interaction.user.id) - current = await db_get('current') + current = await db_get("current") # Check for existing team - if owner_team and not os.environ.get('TESTING'): + if owner_team and not os.environ.get("TESTING"): await interaction.response.send_message( - f'Whoa there, bucko. I already have you down as GM of the {owner_team["sname"]}.' + f"Whoa there, bucko. I already have you down as GM of the {owner_team['sname']}." ) return # Check for duplicate team data - dupes = await db_get('teams', params=[('abbrev', team_abbrev)]) - if dupes['count']: + dupes = await db_get("teams", params=[("abbrev", team_abbrev)]) + if dupes["count"]: await interaction.response.send_message( - f'Yikes! {team_abbrev.upper()} is a popular abbreviation - it\'s already in use by the ' - f'{dupes["teams"][0]["sname"]}. No worries, though, you can run the `/newteam` command again to get ' - f'started!' + f"Yikes! {team_abbrev.upper()} is a popular abbreviation - it's already in use by the " + f"{dupes['teams'][0]['sname']}. No worries, though, you can run the `/newteam` command again to get " + f"started!" ) return # Check for duplicate team data - dupes = await db_get('teams', params=[('lname', team_full_name)]) - if dupes['count']: + dupes = await db_get("teams", params=[("lname", team_full_name)]) + if dupes["count"]: await interaction.response.send_message( - f'Yikes! {team_full_name.title()} is a popular name - it\'s already in use by ' - f'{dupes["teams"][0]["abbrev"]}. No worries, though, you can run the `/newteam` command again to get ' - f'started!' + f"Yikes! {team_full_name.title()} is a popular name - it's already in use by " + f"{dupes['teams'][0]['abbrev']}. No worries, though, you can run the `/newteam` command again to get " + f"started!" ) return # Get personal bot channel hello_channel = discord.utils.get( interaction.guild.text_channels, - name=f'hello-{interaction.user.name.lower()}' + name=f"hello-{interaction.user.name.lower()}", ) if hello_channel: op_ch = hello_channel else: op_ch = await helpers.create_channel( interaction, - channel_name=f'hello-{interaction.user.name}', - category_name='Paper Dynasty Team', + channel_name=f"hello-{interaction.user.name}", + category_name="Paper Dynasty Team", everyone_read=False, - read_send_members=[interaction.user] + read_send_members=[interaction.user], ) await share_channel(op_ch, interaction.guild.me) await share_channel(op_ch, interaction.user) try: - poke_role = get_role(interaction, 'Pokétwo') + poke_role = get_role(interaction, "Pokétwo") await share_channel(op_ch, poke_role, read_only=True) except Exception as e: - logger.error(f'unable to share sheet with Poketwo') + logger.error(f"unable to share sheet with Poketwo") await interaction.response.send_message( - f'Let\'s head down to your private channel: {op_ch.mention}', - ephemeral=True + f"Let's head down to your private channel: {op_ch.mention}", ephemeral=True + ) + await op_ch.send( + f"Hey there, {interaction.user.mention}! I am Paper Domo - welcome to season " + f"{current['season']} of Paper Dynasty! We've got a lot of special updates in store for this " + f"season including live cards, throwback cards, and special events." ) - await op_ch.send(f'Hey there, {interaction.user.mention}! I am Paper Domo - welcome to season ' - f'{current["season"]} of Paper Dynasty! We\'ve got a lot of special updates in store for this ' - f'season including live cards, throwback cards, and special events.') # Confirm user is happy with branding embed = get_team_embed( - f'Branding Check', + f"Branding Check", { - 'logo': team_logo_url if team_logo_url else None, - 'color': color if color else 'a6ce39', - 'season': 4 - } + "logo": team_logo_url if team_logo_url else None, + "color": color if color else "a6ce39", + "season": 4, + }, ) - embed.add_field(name='GM Name', value=gm_name, inline=False) - embed.add_field(name='Full Team Name', value=team_full_name) - embed.add_field(name='Short Team Name', value=team_short_name) - embed.add_field(name='Team Abbrev', value=team_abbrev.upper()) + embed.add_field(name="GM Name", value=gm_name, inline=False) + embed.add_field(name="Full Team Name", value=team_full_name) + embed.add_field(name="Short Team Name", value=team_short_name) + embed.add_field(name="Team Abbrev", value=team_abbrev.upper()) view = Confirm(responders=[interaction.user]) - question = await op_ch.send('Are you happy with this branding? Don\'t worry - you can update it later!', - embed=embed, view=view) + question = await op_ch.send( + "Are you happy with this branding? Don't worry - you can update it later!", + embed=embed, + view=view, + ) await view.wait() if not view.value: await question.edit( - content='~~Are you happy with this branding?~~\n\nI gotta go, but when you\'re ready to start again ' - 'run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the ' - 'command from last time and make edits.', - view=None + content="~~Are you happy with this branding?~~\n\nI gotta go, but when you're ready to start again " + "run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the " + "command from last time and make edits.", + view=None, ) return await question.edit( - content='Looking good, champ in the making! Let\'s get you your starter team!', - view=None + content="Looking good, champ in the making! Let's get you your starter team!", + view=None, ) team_choice = None @@ -1192,26 +1299,31 @@ class Economy(commands.Cog): team_choice = mlb_anchor_team.title() else: for x in ALL_MLB_TEAMS: - if mlb_anchor_team.upper() in ALL_MLB_TEAMS[x] or mlb_anchor_team.title() in ALL_MLB_TEAMS[x]: + if ( + mlb_anchor_team.upper() in ALL_MLB_TEAMS[x] + or mlb_anchor_team.title() in ALL_MLB_TEAMS[x] + ): team_choice = x break team_string = mlb_anchor_team - logger.debug(f'team_string: {team_string} / team_choice: {team_choice}') + logger.debug(f"team_string: {team_string} / team_choice: {team_choice}") if not team_choice: # Get MLB anchor team while True: - prompt = f'I don\'t recognize **{team_string}**. I try to recognize abbreviations (BAL), ' \ - f'short names (Orioles), and long names ("Baltimore Orioles").\n\nWhat MLB club would you ' \ - f'like to use as your anchor team?' - this_q = Question(self.bot, op_ch, prompt, 'text', 120) + prompt = ( + f"I don't recognize **{team_string}**. I try to recognize abbreviations (BAL), " + f'short names (Orioles), and long names ("Baltimore Orioles").\n\nWhat MLB club would you ' + f"like to use as your anchor team?" + ) + this_q = Question(self.bot, op_ch, prompt, "text", 120) team_string = await this_q.ask([interaction.user]) if not team_string: await op_ch.send( - f'Tell you hwat. You think on it and come back I gotta go, but when you\'re ready to start again ' - 'run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the ' - 'command from last time and make edits.' + f"Tell you hwat. You think on it and come back I gotta go, but when you're ready to start again " + "run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the " + "command from last time and make edits." ) return @@ -1221,166 +1333,257 @@ class Economy(commands.Cog): else: match = False for x in ALL_MLB_TEAMS: - if team_string.upper() in ALL_MLB_TEAMS[x] or team_string.title() in ALL_MLB_TEAMS[x]: + if ( + team_string.upper() in ALL_MLB_TEAMS[x] + or team_string.title() in ALL_MLB_TEAMS[x] + ): team_choice = x match = True break if not match: - await op_ch.send(f'Got it!') + await op_ch.send(f"Got it!") - team = await db_post('teams', payload={ - 'abbrev': team_abbrev.upper(), - 'sname': team_short_name, - 'lname': team_full_name, - 'gmid': interaction.user.id, - 'gmname': gm_name, - 'gsheet': 'None', - 'season': current['season'], - 'wallet': 100, - 'color': color if color else 'a6ce39', - 'logo': team_logo_url if team_logo_url else None - }) + team = await db_post( + "teams", + payload={ + "abbrev": team_abbrev.upper(), + "sname": team_short_name, + "lname": team_full_name, + "gmid": interaction.user.id, + "gmname": gm_name, + "gsheet": "None", + "season": current["season"], + "wallet": 100, + "color": color if color else "a6ce39", + "logo": team_logo_url if team_logo_url else None, + }, + ) if not team: - await op_ch.send(f'Frick. {get_cal_user(interaction).mention}, can you help? I can\'t find this team.') + await op_ch.send( + f"Frick. {get_cal_user(interaction).mention}, can you help? I can't find this team." + ) return - t_role = await get_or_create_role(interaction, f'{team_abbrev} - {team_full_name}') + t_role = await get_or_create_role( + interaction, f"{team_abbrev} - {team_full_name}" + ) await interaction.user.add_roles(t_role) anchor_players = [] anchor_all_stars = await db_get( - 'players/random', + "players/random", params=[ - ('min_rarity', 3), ('max_rarity', 3), ('franchise', normalize_franchise(team_choice)), ('pos_exclude', 'RP'), ('limit', 1), - ('in_packs', True) - ] + ("min_rarity", 3), + ("max_rarity", 3), + ("franchise", normalize_franchise(team_choice)), + ("pos_exclude", "RP"), + ("limit", 1), + ("in_packs", True), + ], ) anchor_starters = await db_get( - 'players/random', + "players/random", params=[ - ('min_rarity', 2), ('max_rarity', 2), ('franchise', normalize_franchise(team_choice)), ('pos_exclude', 'RP'), ('limit', 2), - ('in_packs', True) - ] + ("min_rarity", 2), + ("max_rarity", 2), + ("franchise", normalize_franchise(team_choice)), + ("pos_exclude", "RP"), + ("limit", 2), + ("in_packs", True), + ], ) if not anchor_all_stars: - await op_ch.send(f'I am so sorry, but the {team_choice} do not have an All-Star to ' - f'provide as your anchor player. Let\'s start this process over - will you please ' - f'run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the ' - 'command from last time and make edits.') - await db_delete('teams', object_id=team['id']) + await op_ch.send( + f"I am so sorry, but the {team_choice} do not have an All-Star to " + f"provide as your anchor player. Let's start this process over - will you please " + f"run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the " + "command from last time and make edits." + ) + await db_delete("teams", object_id=team["id"]) return - if not anchor_starters or anchor_starters['count'] <= 1: - await op_ch.send(f'I am so sorry, but the {team_choice} do not have two Starters to ' - f'provide as your anchor players. Let\'s start this process over - will you please ' - f'run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the ' - 'command from last time and make edits.') - await db_delete('teams', object_id=team['id']) + if not anchor_starters or anchor_starters["count"] <= 1: + await op_ch.send( + f"I am so sorry, but the {team_choice} do not have two Starters to " + f"provide as your anchor players. Let's start this process over - will you please " + f"run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the " + "command from last time and make edits." + ) + await db_delete("teams", object_id=team["id"]) return - anchor_players.append(anchor_all_stars['players'][0]) - anchor_players.append(anchor_starters['players'][0]) - anchor_players.append(anchor_starters['players'][1]) + anchor_players.append(anchor_all_stars["players"][0]) + anchor_players.append(anchor_starters["players"][0]) + anchor_players.append(anchor_starters["players"][1]) - this_pack = await db_post('packs/one', - payload={'team_id': team['id'], 'pack_type_id': 2, - 'open_time': datetime.datetime.timestamp(datetime.datetime.now())*1000}) + this_pack = await db_post( + "packs/one", + payload={ + "team_id": team["id"], + "pack_type_id": 2, + "open_time": datetime.datetime.timestamp(datetime.datetime.now()) + * 1000, + }, + ) roster_counts = { - 'SP': 0, - 'RP': 0, - 'CP': 0, - 'C': 0, - '1B': 0, - '2B': 0, - '3B': 0, - 'SS': 0, - 'LF': 0, - 'CF': 0, - 'RF': 0, - 'DH': 0, - 'All-Star': 0, - 'Starter': 0, - 'Reserve': 0, - 'Replacement': 0, + "SP": 0, + "RP": 0, + "CP": 0, + "C": 0, + "1B": 0, + "2B": 0, + "3B": 0, + "SS": 0, + "LF": 0, + "CF": 0, + "RF": 0, + "DH": 0, + "All-Star": 0, + "Starter": 0, + "Reserve": 0, + "Replacement": 0, } def update_roster_counts(players: list): for pl in players: - roster_counts[pl['rarity']['name']] += 1 + roster_counts[pl["rarity"]["name"]] += 1 for x in get_all_pos(pl): roster_counts[x] += 1 - logger.warning(f'Roster counts for {team["sname"]}: {roster_counts}') + logger.warning(f"Roster counts for {team['sname']}: {roster_counts}") # Add anchor position coverage update_roster_counts(anchor_players) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in anchor_players] - }, timeout=10) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in anchor_players + ] + }, + timeout=10, + ) # Get 10 pitchers to seed team - five_sps = await db_get('players/random', params=[('pos_include', 'SP'), ('max_rarity', 1), ('limit', 5)]) - five_rps = await db_get('players/random', params=[('pos_include', 'RP'), ('max_rarity', 1), ('limit', 5)]) - team_sp = [x for x in five_sps['players']] - team_rp = [x for x in five_rps['players']] + five_sps = await db_get( + "players/random", + params=[("pos_include", "SP"), ("max_rarity", 1), ("limit", 5)], + ) + five_rps = await db_get( + "players/random", + params=[("pos_include", "RP"), ("max_rarity", 1), ("limit", 5)], + ) + team_sp = [x for x in five_sps["players"]] + team_rp = [x for x in five_rps["players"]] update_roster_counts([*team_sp, *team_rp]) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in [*team_sp, *team_rp]] - }, timeout=10) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in [*team_sp, *team_rp] + ] + }, + timeout=10, + ) - # TODO: track reserve vs replacement and if rep < res, get rep, else get res # Collect infielders team_infielders = [] - for pos in ['C', '1B', '2B', '3B', 'SS']: - max_rar = 1 - if roster_counts['Replacement'] < roster_counts['Reserve']: - max_rar = 0 + for pos in ["C", "1B", "2B", "3B", "SS"]: + if roster_counts["Replacement"] < roster_counts["Reserve"]: + rarity_param = ("rarity", 0) + else: + rarity_param = ("rarity", 1) r_draw = await db_get( - 'players/random', params=[('pos_include', pos), ('max_rarity', max_rar), ('limit', 2)], none_okay=False + "players/random", + params=[("pos_include", pos), rarity_param, ("limit", 2)], + none_okay=False, ) - team_infielders.extend(r_draw['players']) + team_infielders.extend(r_draw["players"]) update_roster_counts(team_infielders) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in team_infielders] - }, timeout=10) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in team_infielders + ] + }, + timeout=10, + ) # Collect outfielders team_outfielders = [] - for pos in ['LF', 'CF', 'RF']: - max_rar = 1 - if roster_counts['Replacement'] < roster_counts['Reserve']: - max_rar = 0 + for pos in ["LF", "CF", "RF"]: + if roster_counts["Replacement"] < roster_counts["Reserve"]: + rarity_param = ("rarity", 0) + else: + rarity_param = ("rarity", 1) r_draw = await db_get( - 'players/random', params=[('pos_include', pos), ('max_rarity', max_rar), ('limit', 2)], none_okay=False + "players/random", + params=[("pos_include", pos), rarity_param, ("limit", 2)], + none_okay=False, ) - team_outfielders.extend(r_draw['players']) + team_outfielders.extend(r_draw["players"]) update_roster_counts(team_outfielders) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in team_outfielders] - }, timeout=10) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in team_outfielders + ] + }, + timeout=10, + ) async with op_ch.typing(): done_anc = await display_cards( - [{'player': x, 'team': team} for x in anchor_players], team, op_ch, interaction.user, self.bot, - cust_message=f'Let\'s take a look at your three {team_choice} anchor players.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in anchor_players], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"Let's take a look at your three {team_choice} anchor players.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) - error_text = f'Yikes - I can\'t display the rest of your team. {get_cal_user(interaction).mention} plz halp' + error_text = f"Yikes - I can't display the rest of your team. {get_cal_user(interaction).mention} plz halp" if not done_anc: await op_ch.send(error_text) async with op_ch.typing(): done_sp = await display_cards( - [{'player': x, 'team': team} for x in team_sp], team, op_ch, interaction.user, self.bot, - cust_message=f'Here are your starting pitchers.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in team_sp], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"Here are your starting pitchers.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) if not done_sp: @@ -1388,10 +1591,14 @@ class Economy(commands.Cog): async with op_ch.typing(): done_rp = await display_cards( - [{'player': x, 'team': team} for x in team_rp], team, op_ch, interaction.user, self.bot, - cust_message=f'And now for your bullpen.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in team_rp], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"And now for your bullpen.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) if not done_rp: @@ -1399,10 +1606,14 @@ class Economy(commands.Cog): async with op_ch.typing(): done_inf = await display_cards( - [{'player': x, 'team': team} for x in team_infielders], team, op_ch, interaction.user, self.bot, - cust_message=f'Next let\'s take a look at your infielders.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in team_infielders], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"Next let's take a look at your infielders.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) if not done_inf: @@ -1410,10 +1621,14 @@ class Economy(commands.Cog): async with op_ch.typing(): done_out = await display_cards( - [{'player': x, 'team': team} for x in team_outfielders], team, op_ch, interaction.user, self.bot, - cust_message=f'Now let\'s take a look at your outfielders.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in team_outfielders], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"Now let's take a look at your outfielders.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) if not done_out: @@ -1421,223 +1636,296 @@ class Economy(commands.Cog): await give_packs(team, 1) await op_ch.send( - f'To get you started, I\'ve spotted you 100₼ and a pack of cards. You can rip that with the ' - f'`/open` command once your google sheet is set up!' + f"To get you started, I've spotted you 100₼ and a pack of cards. You can rip that with the " + f"`/open` command once your google sheet is set up!" ) await op_ch.send( - f'{t_role.mention}\n\n' - f'There\'s your roster! We have one more step and you will be ready to play.\n\n{SHEET_SHARE_STEPS}\n\n' - f'{get_roster_sheet({"gsheet": current["gsheet_template"]})}' + f"{t_role.mention}\n\n" + f"There's your roster! We have one more step and you will be ready to play.\n\n{SHEET_SHARE_STEPS}\n\n" + f"{get_roster_sheet({'gsheet': current['gsheet_template']})}" ) - new_team_embed = await team_summary_embed(team, interaction, include_roster=False) + new_team_embed = await team_summary_embed( + team, interaction, include_roster=False + ) await send_to_channel( - self.bot, "pd-network-news", content='A new challenger approaches...', embed=new_team_embed + self.bot, + "pd-network-news", + content="A new challenger approaches...", + embed=new_team_embed, ) - @commands.command(name='mlbteam', help='Mod: Load MLB team data') + @commands.command(name="mlbteam", help="Mod: Load MLB team data") @commands.is_owner() async def mlb_team_command( - self, ctx: commands.Context, abbrev: str, sname: str, lname: str, gmid: int, gmname: str, gsheet: str, - logo: str, color: str, ranking: int): + self, + ctx: commands.Context, + abbrev: str, + sname: str, + lname: str, + gmid: int, + gmname: str, + gsheet: str, + logo: str, + color: str, + ranking: int, + ): # Check for duplicate team data - dupes = await db_get('teams', params=[('abbrev', abbrev)]) - if dupes['count']: + dupes = await db_get("teams", params=[("abbrev", abbrev)]) + if dupes["count"]: await ctx.send( - f'Yikes! {abbrev.upper()} is a popular abbreviation - it\'s already in use by the ' - f'{dupes["teams"][0]["sname"]}. No worries, though, you can run the `/newteam` command again to get ' - f'started!' + f"Yikes! {abbrev.upper()} is a popular abbreviation - it's already in use by the " + f"{dupes['teams'][0]['sname']}. No worries, though, you can run the `/newteam` command again to get " + f"started!" ) return # Check for duplicate team data - dupes = await db_get('teams', params=[('lname', lname)]) - if dupes['count']: + dupes = await db_get("teams", params=[("lname", lname)]) + if dupes["count"]: await ctx.send( - f'Yikes! {lname.title()} is a popular name - it\'s already in use by ' - f'{dupes["teams"][0]["abbrev"]}. No worries, though, you can run the `/newteam` command again to get ' - f'started!' + f"Yikes! {lname.title()} is a popular name - it's already in use by " + f"{dupes['teams'][0]['abbrev']}. No worries, though, you can run the `/newteam` command again to get " + f"started!" ) return - current = await db_get('current') + current = await db_get("current") - team = await db_post('teams', payload={ - 'abbrev': abbrev.upper(), - 'sname': sname, - 'lname': lname, - 'gmid': gmid, - 'gmname': gmname, - 'gsheet': gsheet, - 'season': current['season'], - 'wallet': 100, - 'ranking': ranking, - 'color': color if color else 'a6ce39', - 'logo': logo if logo else None, - 'is_ai': True - }) - - p_query = await db_get('players', params=[('franchise', sname)]) - - this_pack = await db_post( - 'packs/one', - payload={'team_id': team['id'], 'pack_type_id': 2, - 'open_time': datetime.datetime.timestamp(datetime.datetime.now())*1000} + team = await db_post( + "teams", + payload={ + "abbrev": abbrev.upper(), + "sname": sname, + "lname": lname, + "gmid": gmid, + "gmname": gmname, + "gsheet": gsheet, + "season": current["season"], + "wallet": 100, + "ranking": ranking, + "color": color if color else "a6ce39", + "logo": logo if logo else None, + "is_ai": True, + }, ) - team_players = p_query['players'] + p_query['players'] - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in team_players] - }, timeout=10) + p_query = await db_get("players", params=[("franchise", sname)]) - embed = get_team_embed(f'{team["lname"]}', team) + this_pack = await db_post( + "packs/one", + payload={ + "team_id": team["id"], + "pack_type_id": 2, + "open_time": datetime.datetime.timestamp(datetime.datetime.now()) + * 1000, + }, + ) + + team_players = p_query["players"] + p_query["players"] + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in team_players + ] + }, + timeout=10, + ) + + embed = get_team_embed(f"{team['lname']}", team) await ctx.send(content=None, embed=embed) - @commands.hybrid_command(name='mlb-update', help='Distribute MLB cards to AI teams') + @commands.hybrid_command(name="mlb-update", help="Distribute MLB cards to AI teams") @commands.is_owner() async def mlb_update_command(self, ctx: commands.Context): - ai_teams = await db_get('teams', params=[('is_ai', True)]) - if ai_teams['count'] == 0: - await ctx.send(f'I could not find any AI teams.') + ai_teams = await db_get("teams", params=[("is_ai", True)]) + if ai_teams["count"] == 0: + await ctx.send(f"I could not find any AI teams.") return total_cards = 0 total_teams = 0 - for team in ai_teams['teams']: - all_players = await db_get('players', params=[('franchise', team['sname'])]) + for team in ai_teams["teams"]: + all_players = await db_get("players", params=[("franchise", team["sname"])]) new_players = [] if all_players: - for player in all_players['players']: - owned_by_team_ids = [entry['team'] for entry in player['paperdex']['paperdex']] + for player in all_players["players"]: + owned_by_team_ids = [ + entry["team"] for entry in player["paperdex"]["paperdex"] + ] - if team['id'] not in owned_by_team_ids: + if team["id"] not in owned_by_team_ids: new_players.append(player) if new_players: - await ctx.send(f'Posting {len(new_players)} new cards for {team["gmname"]}\'s {team["sname"]}...') + await ctx.send( + f"Posting {len(new_players)} new cards for {team['gmname']}'s {team['sname']}..." + ) total_cards += len(new_players) total_teams += 1 this_pack = await db_post( - 'packs/one', - payload={'team_id': team['id'], 'pack_type_id': 2, - 'open_time': datetime.datetime.timestamp(datetime.datetime.now()) * 1000} + "packs/one", + payload={ + "team_id": team["id"], + "pack_type_id": 2, + "open_time": datetime.datetime.timestamp( + datetime.datetime.now() + ) + * 1000, + }, + ) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in new_players + ] + }, + timeout=10, ) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in - new_players - ]}, timeout=10) await refresh_sheet(team, self.bot) - await ctx.send(f'All done! I added {total_cards} across {total_teams} teams.') + await ctx.send(f"All done! I added {total_cards} across {total_teams} teams.") - @commands.hybrid_command(name='newsheet', help='Link a new team sheet with your team') + @commands.hybrid_command( + name="newsheet", help="Link a new team sheet with your team" + ) @commands.has_any_role(PD_PLAYERS) async def share_sheet_command( - self, ctx, google_sheet_url: str, team_abbrev: Optional[str], copy_rosters: Optional[bool] = True): + self, + ctx, + google_sheet_url: str, + team_abbrev: Optional[str], + copy_rosters: Optional[bool] = True, + ): owner_team = await get_team_by_owner(ctx.author.id) if not owner_team: - await ctx.send(f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!') + await ctx.send( + f"I don't see a team for you, yet. You can sign up with the `/newteam` command!" + ) return team = owner_team - if team_abbrev and team_abbrev != owner_team['abbrev']: + if team_abbrev and team_abbrev != owner_team["abbrev"]: if ctx.author.id != 258104532423147520: - await ctx.send(f'You can only update the team sheet for your own team, you goober.') + await ctx.send( + f"You can only update the team sheet for your own team, you goober." + ) return else: team = await get_team_by_abbrev(team_abbrev) - current = await db_get('current') - if current['gsheet_template'] in google_sheet_url: - await ctx.send(f'Ope, looks like that is the template sheet. Would you please make a copy and then share?') + current = await db_get("current") + if current["gsheet_template"] in google_sheet_url: + await ctx.send( + f"Ope, looks like that is the template sheet. Would you please make a copy and then share?" + ) return - gauntlet_team = await get_team_by_abbrev(f'Gauntlet-{owner_team["abbrev"]}') + gauntlet_team = await get_team_by_abbrev(f"Gauntlet-{owner_team['abbrev']}") if gauntlet_team: - view = ButtonOptions([ctx.author], timeout=30, labels=['Main Team', 'Gauntlet Team', None, None, None]) - question = await ctx.send(f'Is this sheet for your main PD team or your active Gauntlet team?', view=view) + view = ButtonOptions( + [ctx.author], + timeout=30, + labels=["Main Team", "Gauntlet Team", None, None, None], + ) + question = await ctx.send( + f"Is this sheet for your main PD team or your active Gauntlet team?", + view=view, + ) await view.wait() if not view.value: await question.edit( - content=f'Okay you keep thinking on it and get back to me when you\'re ready.', view=None + content=f"Okay you keep thinking on it and get back to me when you're ready.", + view=None, ) return - elif view.value == 'Gauntlet Team': + elif view.value == "Gauntlet Team": await question.delete() team = gauntlet_team sheets = get_sheets(self.bot) - response = await ctx.send(f'I\'ll go grab that sheet...') + response = await ctx.send(f"I'll go grab that sheet...") try: new_sheet = sheets.open_by_url(google_sheet_url) except Exception as e: - logger.error(f'Error accessing {team["abbrev"]} sheet: {e}') - current = await db_get('current') - await ctx.send(f'I wasn\'t able to access that sheet. Did you remember to share it with my PD email?' - f'\n\nHere\'s a quick refresher:\n{SHEET_SHARE_STEPS}\n\n' - f'{get_roster_sheet({"gsheet": current["gsheet_template"]})}') + logger.error(f"Error accessing {team['abbrev']} sheet: {e}") + current = await db_get("current") + await ctx.send( + f"I wasn't able to access that sheet. Did you remember to share it with my PD email?" + f"\n\nHere's a quick refresher:\n{SHEET_SHARE_STEPS}\n\n" + f"{get_roster_sheet({'gsheet': current['gsheet_template']})}" + ) return - team_data = new_sheet.worksheet_by_title('Team Data') + team_data = new_sheet.worksheet_by_title("Team Data") if not gauntlet_team or owner_team != gauntlet_team: team_data.update_values( - crange='B1:B2', - values=[[f'{team["id"]}'], [f'\'{team_hash(team)}']] + crange="B1:B2", values=[[f"{team['id']}"], [f"'{team_hash(team)}"]] ) - if copy_rosters and team['gsheet'].lower() != 'none': - old_sheet = sheets.open_by_key(team['gsheet']) - r_sheet = old_sheet.worksheet_by_title(f'My Rosters') - roster_ids = r_sheet.range('B3:B80') - lineups_data = r_sheet.range('H4:M26') + if copy_rosters and team["gsheet"].lower() != "none": + old_sheet = sheets.open_by_key(team["gsheet"]) + r_sheet = old_sheet.worksheet_by_title(f"My Rosters") + roster_ids = r_sheet.range("B3:B80") + lineups_data = r_sheet.range("H4:M26") new_r_data, new_l_data = [], [] for row in roster_ids: - if row[0].value != '': + if row[0].value != "": new_r_data.append([int(row[0].value)]) else: new_r_data.append([None]) - logger.debug(f'new_r_data: {new_r_data}') + logger.debug(f"new_r_data: {new_r_data}") for row in lineups_data: - logger.debug(f'row: {row}') - new_l_data.append([ - row[0].value if row[0].value != '' else None, - int(row[1].value) if row[1].value != '' else None, - row[2].value if row[2].value != '' else None, - int(row[3].value) if row[3].value != '' else None, - row[4].value if row[4].value != '' else None, - int(row[5].value) if row[5].value != '' else None - ]) - logger.debug(f'new_l_data: {new_l_data}') + logger.debug(f"row: {row}") + new_l_data.append( + [ + row[0].value if row[0].value != "" else None, + int(row[1].value) if row[1].value != "" else None, + row[2].value if row[2].value != "" else None, + int(row[3].value) if row[3].value != "" else None, + row[4].value if row[4].value != "" else None, + int(row[5].value) if row[5].value != "" else None, + ] + ) + logger.debug(f"new_l_data: {new_l_data}") - new_r_sheet = new_sheet.worksheet_by_title(f'My Rosters') - new_r_sheet.update_values( - crange='B3:B80', - values=new_r_data - ) - new_r_sheet.update_values( - crange='H4:M26', - values=new_l_data - ) + new_r_sheet = new_sheet.worksheet_by_title(f"My Rosters") + new_r_sheet.update_values(crange="B3:B80", values=new_r_data) + new_r_sheet.update_values(crange="H4:M26", values=new_l_data) - if team['has_guide']: + if team["has_guide"]: post_ratings_guide(team, self.bot, this_sheet=new_sheet) - team = await db_patch('teams', object_id=team['id'], params=[('gsheet', new_sheet.id)]) + team = await db_patch( + "teams", object_id=team["id"], params=[("gsheet", new_sheet.id)] + ) await refresh_sheet(team, self.bot, sheets) - conf_message = f'Alright, your sheet is linked to your team - good luck' + conf_message = f"Alright, your sheet is linked to your team - good luck" if owner_team == team: - conf_message += ' this season!' + conf_message += " this season!" else: - conf_message += ' on your run!' - conf_message += f'\n\n{HELP_SHEET_SCRIPTS}' - await response.edit(content=f'{conf_message}') + conf_message += " on your run!" + conf_message += f"\n\n{HELP_SHEET_SCRIPTS}" + await response.edit(content=f"{conf_message}") # @commands.hybrid_command(name='refresh', help='Refresh team data in Sheets') # @commands.has_any_role(PD_PLAYERS) @@ -1692,89 +1980,103 @@ class Economy(commands.Cog): # # # # db.close() - @commands.hybrid_command(name='give-card', help='Mod: Give free card to team') + @commands.hybrid_command(name="give-card", help="Mod: Give free card to team") # @commands.is_owner() @commands.has_any_role("PD Gift Players") async def give_card_command(self, ctx, player_ids: str, team_abbrev: str): - if ctx.channel.name in ['paper-dynasty-chat', 'pd-news-ticker', 'pd-network-news']: - await ctx.send(f'Please head to down to {get_channel(ctx, "pd-bot-hole")} to run this command.') + if ctx.channel.name in [ + "paper-dynasty-chat", + "pd-news-ticker", + "pd-network-news", + ]: + await ctx.send( + f"Please head to down to {get_channel(ctx, 'pd-bot-hole')} to run this command." + ) return - question = await ctx.send(f'I\'ll go put that card on their roster...') + question = await ctx.send(f"I'll go put that card on their roster...") all_player_ids = player_ids.split(" ") - t_query = await db_get('teams', params=[('abbrev', team_abbrev)]) - if not t_query['count']: - await ctx.send(f'I could not find {team_abbrev}') + t_query = await db_get("teams", params=[("abbrev", team_abbrev)]) + if not t_query["count"]: + await ctx.send(f"I could not find {team_abbrev}") return - team = t_query['teams'][0] + team = t_query["teams"][0] this_pack = await db_post( - 'packs/one', + "packs/one", payload={ - 'team_id': team['id'], - 'pack_type_id': 4, - 'open_time': datetime.datetime.timestamp(datetime.datetime.now()) * 1000} + "team_id": team["id"], + "pack_type_id": 4, + "open_time": datetime.datetime.timestamp(datetime.datetime.now()) + * 1000, + }, ) try: - await give_cards_to_team(team, player_ids=all_player_ids, pack_id=this_pack['id']) + await give_cards_to_team( + team, player_ids=all_player_ids, pack_id=this_pack["id"] + ) except Exception as e: - logger.error(f'failed to create cards: {e}') - raise ConnectionError(f'Failed to distribute these cards.') + logger.error(f"failed to create cards: {e}") + raise ConnectionError(f"Failed to distribute these cards.") - await question.edit(content=f'Alrighty, now I\'ll refresh their sheet...') + await question.edit(content=f"Alrighty, now I'll refresh their sheet...") await refresh_sheet(team, self.bot) - await question.edit(content=f'All done!') + await question.edit(content=f"All done!") await send_to_channel( self.bot, - channel_name='commissioners-office', - content=f'Just sent {len(all_player_ids)} players to {ctx.message.author.mention}:\n{all_player_ids}' + channel_name="commissioners-office", + content=f"Just sent {len(all_player_ids)} players to {ctx.message.author.mention}:\n{all_player_ids}", ) - @commands.command(name='cleartest', hidden=True) + @commands.command(name="cleartest", hidden=True) @commands.is_owner() async def clear_test_command(self, ctx): team = await get_team_by_owner(ctx.author.id) - msg = await ctx.send('Alright, let\'s go find your cards...') - all_cards = await db_get( - 'cards', - params=[('team_id', team['id'])] - ) + msg = await ctx.send("Alright, let's go find your cards...") + all_cards = await db_get("cards", params=[("team_id", team["id"])]) if all_cards: - await msg.edit(content=f'I found {len(all_cards["cards"])} cards; deleting now...') - for x in all_cards['cards']: - await db_delete( - 'cards', - object_id=x['id'] - ) + await msg.edit( + content=f"I found {len(all_cards['cards'])} cards; deleting now..." + ) + for x in all_cards["cards"]: + await db_delete("cards", object_id=x["id"]) - await msg.edit(content=f'All done with cards. Now I\'ll wipe out your packs...') - p_query = await db_get('packs', params=[('team_id', team['id'])]) - if p_query['count']: - for x in p_query['packs']: - await db_delete('packs', object_id=x['id']) + await msg.edit(content=f"All done with cards. Now I'll wipe out your packs...") + p_query = await db_get("packs", params=[("team_id", team["id"])]) + if p_query["count"]: + for x in p_query["packs"]: + await db_delete("packs", object_id=x["id"]) - await msg.edit(content=f'All done with packs. Now I\'ll wipe out your paperdex...') - p_query = await db_get('paperdex', params=[('team_id', team['id'])]) - if p_query['count']: - for x in p_query['paperdex']: - await db_delete('paperdex', object_id=x['id']) + await msg.edit( + content=f"All done with packs. Now I'll wipe out your paperdex..." + ) + p_query = await db_get("paperdex", params=[("team_id", team["id"])]) + if p_query["count"]: + for x in p_query["paperdex"]: + await db_delete("paperdex", object_id=x["id"]) - await msg.edit(content=f'All done with paperdex. Now I\'ll wipe out your team...') - if db_delete('teams', object_id=team['id']): - await msg.edit(content=f'All done!') + await msg.edit( + content=f"All done with paperdex. Now I'll wipe out your team..." + ) + if db_delete("teams", object_id=team["id"]): + await msg.edit(content=f"All done!") - @commands.command(name='packtest', hidden=True) + @commands.command(name="packtest", hidden=True) @commands.is_owner() async def pack_test_command(self, ctx): team = await get_team_by_owner(ctx.author.id) await display_cards( - await get_test_pack(ctx, team), team, ctx.channel, ctx.author, self.bot, - pack_cover=IMAGES['pack-sta'], - pack_name='Standard Pack' + await get_test_pack(ctx, team), + team, + ctx.channel, + ctx.author, + self.bot, + pack_cover=IMAGES["pack-sta"], + pack_name="Standard Pack", ) diff --git a/cogs/economy_new/team_setup.py b/cogs/economy_new/team_setup.py index 043d52e..5337e6f 100644 --- a/cogs/economy_new/team_setup.py +++ b/cogs/economy_new/team_setup.py @@ -15,131 +15,161 @@ from api_calls import db_get, db_post, db_patch, db_delete, get_team_by_abbrev from help_text import SHEET_SHARE_STEPS, HELP_SHEET_SCRIPTS from helpers.constants import PD_PLAYERS, ALL_MLB_TEAMS from helpers import ( - get_team_by_owner, share_channel, get_role, get_cal_user, get_or_create_role, - display_cards, give_packs, get_all_pos, get_sheets, refresh_sheet, - post_ratings_guide, team_summary_embed, get_roster_sheet, Question, Confirm, - ButtonOptions, legal_channel, get_channel, create_channel, get_context_user + get_team_by_owner, + share_channel, + get_role, + get_cal_user, + get_or_create_role, + display_cards, + give_packs, + get_all_pos, + get_sheets, + refresh_sheet, + post_ratings_guide, + team_summary_embed, + get_roster_sheet, + Question, + Confirm, + ButtonOptions, + legal_channel, + get_channel, + create_channel, + get_context_user, ) from api_calls import team_hash from helpers.discord_utils import get_team_embed, send_to_channel -logger = logging.getLogger('discord_app') +logger = logging.getLogger("discord_app") class TeamSetup(commands.Cog): """Team creation and Google Sheets integration functionality for Paper Dynasty.""" - + def __init__(self, bot): self.bot = bot - @app_commands.command(name='newteam', description='Get your fresh team for a new season') + @app_commands.command( + name="newteam", description="Get your fresh team for a new season" + ) @app_commands.checks.has_any_role(PD_PLAYERS) @app_commands.describe( - gm_name='The fictional name of your team\'s GM', - team_abbrev='2, 3, or 4 character abbreviation (e.g. WV, ATL, MAD)', - team_full_name='City/location and name (e.g. Baltimore Orioles)', - team_short_name='Name of team (e.g. Yankees)', - mlb_anchor_team='2 or 3 character abbreviation of your anchor MLB team (e.g. NYM, MKE)', - team_logo_url='[Optional] URL ending in .png or .jpg for your team logo', - color='[Optional] Hex color code to highlight your team' + gm_name="The fictional name of your team's GM", + team_abbrev="2, 3, or 4 character abbreviation (e.g. WV, ATL, MAD)", + team_full_name="City/location and name (e.g. Baltimore Orioles)", + team_short_name="Name of team (e.g. Yankees)", + mlb_anchor_team="2 or 3 character abbreviation of your anchor MLB team (e.g. NYM, MKE)", + team_logo_url="[Optional] URL ending in .png or .jpg for your team logo", + color="[Optional] Hex color code to highlight your team", ) async def new_team_slash( - self, interaction: discord.Interaction, gm_name: str, team_abbrev: str, team_full_name: str, - team_short_name: str, mlb_anchor_team: str, team_logo_url: str = None, color: str = None): + self, + interaction: discord.Interaction, + gm_name: str, + team_abbrev: str, + team_full_name: str, + team_short_name: str, + mlb_anchor_team: str, + team_logo_url: str = None, + color: str = None, + ): owner_team = await get_team_by_owner(interaction.user.id) - current = await db_get('current') + current = await db_get("current") # Check for existing team - if owner_team and not os.environ.get('TESTING'): + if owner_team and not os.environ.get("TESTING"): await interaction.response.send_message( - f'Whoa there, bucko. I already have you down as GM of the {owner_team["sname"]}.' + f"Whoa there, bucko. I already have you down as GM of the {owner_team['sname']}." ) return # Check for duplicate team data - dupes = await db_get('teams', params=[('abbrev', team_abbrev)]) - if dupes['count']: + dupes = await db_get("teams", params=[("abbrev", team_abbrev)]) + if dupes["count"]: await interaction.response.send_message( - f'Yikes! {team_abbrev.upper()} is a popular abbreviation - it\'s already in use by the ' - f'{dupes["teams"][0]["sname"]}. No worries, though, you can run the `/newteam` command again to get ' - f'started!' + f"Yikes! {team_abbrev.upper()} is a popular abbreviation - it's already in use by the " + f"{dupes['teams'][0]['sname']}. No worries, though, you can run the `/newteam` command again to get " + f"started!" ) return # Check for duplicate team data - dupes = await db_get('teams', params=[('lname', team_full_name)]) - if dupes['count']: + dupes = await db_get("teams", params=[("lname", team_full_name)]) + if dupes["count"]: await interaction.response.send_message( - f'Yikes! {team_full_name.title()} is a popular name - it\'s already in use by ' - f'{dupes["teams"][0]["abbrev"]}. No worries, though, you can run the `/newteam` command again to get ' - f'started!' + f"Yikes! {team_full_name.title()} is a popular name - it's already in use by " + f"{dupes['teams'][0]['abbrev']}. No worries, though, you can run the `/newteam` command again to get " + f"started!" ) return # Get personal bot channel hello_channel = discord.utils.get( interaction.guild.text_channels, - name=f'hello-{interaction.user.name.lower()}' + name=f"hello-{interaction.user.name.lower()}", ) if hello_channel: op_ch = hello_channel else: op_ch = await create_channel( interaction, - channel_name=f'hello-{interaction.user.name}', - category_name='Paper Dynasty Team', + channel_name=f"hello-{interaction.user.name}", + category_name="Paper Dynasty Team", everyone_read=False, - read_send_members=[interaction.user] + read_send_members=[interaction.user], ) await share_channel(op_ch, interaction.guild.me) await share_channel(op_ch, interaction.user) try: - poke_role = get_role(interaction, 'Pokétwo') + poke_role = get_role(interaction, "Pokétwo") await share_channel(op_ch, poke_role, read_only=True) except Exception as e: - logger.error(f'unable to share sheet with Poketwo') + logger.error(f"unable to share sheet with Poketwo") await interaction.response.send_message( - f'Let\'s head down to your private channel: {op_ch.mention}', - ephemeral=True + f"Let's head down to your private channel: {op_ch.mention}", ephemeral=True + ) + await op_ch.send( + f"Hey there, {interaction.user.mention}! I am Paper Domo - welcome to season " + f"{current['season']} of Paper Dynasty! We've got a lot of special updates in store for this " + f"season including live cards, throwback cards, and special events." ) - await op_ch.send(f'Hey there, {interaction.user.mention}! I am Paper Domo - welcome to season ' - f'{current["season"]} of Paper Dynasty! We\'ve got a lot of special updates in store for this ' - f'season including live cards, throwback cards, and special events.') # Confirm user is happy with branding embed = get_team_embed( - f'Branding Check', + f"Branding Check", { - 'logo': team_logo_url if team_logo_url else None, - 'color': color if color else 'a6ce39', - 'season': 4 - } + "logo": team_logo_url if team_logo_url else None, + "color": color if color else "a6ce39", + "season": 4, + }, ) - embed.add_field(name='GM Name', value=gm_name, inline=False) - embed.add_field(name='Full Team Name', value=team_full_name) - embed.add_field(name='Short Team Name', value=team_short_name) - embed.add_field(name='Team Abbrev', value=team_abbrev.upper()) + embed.add_field(name="GM Name", value=gm_name, inline=False) + embed.add_field(name="Full Team Name", value=team_full_name) + embed.add_field(name="Short Team Name", value=team_short_name) + embed.add_field(name="Team Abbrev", value=team_abbrev.upper()) view = Confirm(responders=[interaction.user]) - question = await op_ch.send('Are you happy with this branding? Don\'t worry - you can update it later!', - embed=embed, view=view) + question = await op_ch.send( + "Are you happy with this branding? Don't worry - you can update it later!", + embed=embed, + view=view, + ) await view.wait() if not view.value: await question.edit( - content='~~Are you happy with this branding?~~\n\nI gotta go, but when you\'re ready to start again ' - 'run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the ' - 'command from last time and make edits.', - view=None + content="~~Are you happy with this branding?~~\n\nI gotta go, but when you're ready to start again " + "run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the " + "command from last time and make edits.", + view=None, ) return await question.edit( - content='Looking good, champ in the making! Let\'s get you your starter team!', - view=None + content="Looking good, champ in the making! Let's get you your starter team!", + view=None, ) team_choice = None @@ -147,26 +177,31 @@ class TeamSetup(commands.Cog): team_choice = mlb_anchor_team.title() else: for x in ALL_MLB_TEAMS: - if mlb_anchor_team.upper() in ALL_MLB_TEAMS[x] or mlb_anchor_team.title() in ALL_MLB_TEAMS[x]: + if ( + mlb_anchor_team.upper() in ALL_MLB_TEAMS[x] + or mlb_anchor_team.title() in ALL_MLB_TEAMS[x] + ): team_choice = x break team_string = mlb_anchor_team - logger.debug(f'team_string: {team_string} / team_choice: {team_choice}') + logger.debug(f"team_string: {team_string} / team_choice: {team_choice}") if not team_choice: # Get MLB anchor team while True: - prompt = f'I don\'t recognize **{team_string}**. I try to recognize abbreviations (BAL), ' \ - f'short names (Orioles), and long names ("Baltimore Orioles").\n\nWhat MLB club would you ' \ - f'like to use as your anchor team?' - this_q = Question(self.bot, op_ch, prompt, 'text', 120) + prompt = ( + f"I don't recognize **{team_string}**. I try to recognize abbreviations (BAL), " + f'short names (Orioles), and long names ("Baltimore Orioles").\n\nWhat MLB club would you ' + f"like to use as your anchor team?" + ) + this_q = Question(self.bot, op_ch, prompt, "text", 120) team_string = await this_q.ask([interaction.user]) if not team_string: await op_ch.send( - f'Tell you hwat. You think on it and come back I gotta go, but when you\'re ready to start again ' - 'run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the ' - 'command from last time and make edits.' + f"Tell you hwat. You think on it and come back I gotta go, but when you're ready to start again " + "run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the " + "command from last time and make edits." ) return @@ -176,166 +211,257 @@ class TeamSetup(commands.Cog): else: match = False for x in ALL_MLB_TEAMS: - if team_string.upper() in ALL_MLB_TEAMS[x] or team_string.title() in ALL_MLB_TEAMS[x]: + if ( + team_string.upper() in ALL_MLB_TEAMS[x] + or team_string.title() in ALL_MLB_TEAMS[x] + ): team_choice = x match = True break if not match: - await op_ch.send(f'Got it!') + await op_ch.send(f"Got it!") - team = await db_post('teams', payload={ - 'abbrev': team_abbrev.upper(), - 'sname': team_short_name, - 'lname': team_full_name, - 'gmid': interaction.user.id, - 'gmname': gm_name, - 'gsheet': 'None', - 'season': current['season'], - 'wallet': 100, - 'color': color if color else 'a6ce39', - 'logo': team_logo_url if team_logo_url else None - }) + team = await db_post( + "teams", + payload={ + "abbrev": team_abbrev.upper(), + "sname": team_short_name, + "lname": team_full_name, + "gmid": interaction.user.id, + "gmname": gm_name, + "gsheet": "None", + "season": current["season"], + "wallet": 100, + "color": color if color else "a6ce39", + "logo": team_logo_url if team_logo_url else None, + }, + ) if not team: - await op_ch.send(f'Frick. {get_cal_user(interaction).mention}, can you help? I can\'t find this team.') + await op_ch.send( + f"Frick. {get_cal_user(interaction).mention}, can you help? I can't find this team." + ) return - t_role = await get_or_create_role(interaction, f'{team_abbrev} - {team_full_name}') + t_role = await get_or_create_role( + interaction, f"{team_abbrev} - {team_full_name}" + ) await interaction.user.add_roles(t_role) anchor_players = [] anchor_all_stars = await db_get( - 'players/random', + "players/random", params=[ - ('min_rarity', 3), ('max_rarity', 3), ('franchise', team_choice), ('pos_exclude', 'RP'), ('limit', 1), - ('in_packs', True) - ] + ("min_rarity", 3), + ("max_rarity", 3), + ("franchise", team_choice), + ("pos_exclude", "RP"), + ("limit", 1), + ("in_packs", True), + ], ) anchor_starters = await db_get( - 'players/random', + "players/random", params=[ - ('min_rarity', 2), ('max_rarity', 2), ('franchise', team_choice), ('pos_exclude', 'RP'), ('limit', 2), - ('in_packs', True) - ] + ("min_rarity", 2), + ("max_rarity", 2), + ("franchise", team_choice), + ("pos_exclude", "RP"), + ("limit", 2), + ("in_packs", True), + ], ) if not anchor_all_stars: - await op_ch.send(f'I am so sorry, but the {team_choice} do not have an All-Star to ' - f'provide as your anchor player. Let\'s start this process over - will you please ' - f'run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the ' - 'command from last time and make edits.') - await db_delete('teams', object_id=team['id']) + await op_ch.send( + f"I am so sorry, but the {team_choice} do not have an All-Star to " + f"provide as your anchor player. Let's start this process over - will you please " + f"run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the " + "command from last time and make edits." + ) + await db_delete("teams", object_id=team["id"]) return - if not anchor_starters or anchor_starters['count'] <= 1: - await op_ch.send(f'I am so sorry, but the {team_choice} do not have two Starters to ' - f'provide as your anchor players. Let\'s start this process over - will you please ' - f'run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the ' - 'command from last time and make edits.') - await db_delete('teams', object_id=team['id']) + if not anchor_starters or anchor_starters["count"] <= 1: + await op_ch.send( + f"I am so sorry, but the {team_choice} do not have two Starters to " + f"provide as your anchor players. Let's start this process over - will you please " + f"run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the " + "command from last time and make edits." + ) + await db_delete("teams", object_id=team["id"]) return - anchor_players.append(anchor_all_stars['players'][0]) - anchor_players.append(anchor_starters['players'][0]) - anchor_players.append(anchor_starters['players'][1]) + anchor_players.append(anchor_all_stars["players"][0]) + anchor_players.append(anchor_starters["players"][0]) + anchor_players.append(anchor_starters["players"][1]) - this_pack = await db_post('packs/one', - payload={'team_id': team['id'], 'pack_type_id': 2, - 'open_time': datetime.datetime.timestamp(datetime.datetime.now())*1000}) + this_pack = await db_post( + "packs/one", + payload={ + "team_id": team["id"], + "pack_type_id": 2, + "open_time": datetime.datetime.timestamp(datetime.datetime.now()) + * 1000, + }, + ) roster_counts = { - 'SP': 0, - 'RP': 0, - 'CP': 0, - 'C': 0, - '1B': 0, - '2B': 0, - '3B': 0, - 'SS': 0, - 'LF': 0, - 'CF': 0, - 'RF': 0, - 'DH': 0, - 'All-Star': 0, - 'Starter': 0, - 'Reserve': 0, - 'Replacement': 0, + "SP": 0, + "RP": 0, + "CP": 0, + "C": 0, + "1B": 0, + "2B": 0, + "3B": 0, + "SS": 0, + "LF": 0, + "CF": 0, + "RF": 0, + "DH": 0, + "All-Star": 0, + "Starter": 0, + "Reserve": 0, + "Replacement": 0, } def update_roster_counts(players: list): for pl in players: - roster_counts[pl['rarity']['name']] += 1 + roster_counts[pl["rarity"]["name"]] += 1 for x in get_all_pos(pl): roster_counts[x] += 1 - logger.warning(f'Roster counts for {team["sname"]}: {roster_counts}') + logger.warning(f"Roster counts for {team['sname']}: {roster_counts}") # Add anchor position coverage update_roster_counts(anchor_players) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in anchor_players] - }, timeout=10) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in anchor_players + ] + }, + timeout=10, + ) # Get 10 pitchers to seed team - five_sps = await db_get('players/random', params=[('pos_include', 'SP'), ('max_rarity', 1), ('limit', 5)]) - five_rps = await db_get('players/random', params=[('pos_include', 'RP'), ('max_rarity', 1), ('limit', 5)]) - team_sp = [x for x in five_sps['players']] - team_rp = [x for x in five_rps['players']] + five_sps = await db_get( + "players/random", + params=[("pos_include", "SP"), ("max_rarity", 1), ("limit", 5)], + ) + five_rps = await db_get( + "players/random", + params=[("pos_include", "RP"), ("max_rarity", 1), ("limit", 5)], + ) + team_sp = [x for x in five_sps["players"]] + team_rp = [x for x in five_rps["players"]] update_roster_counts([*team_sp, *team_rp]) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in [*team_sp, *team_rp]] - }, timeout=10) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in [*team_sp, *team_rp] + ] + }, + timeout=10, + ) - # TODO: track reserve vs replacement and if rep < res, get rep, else get res # Collect infielders team_infielders = [] - for pos in ['C', '1B', '2B', '3B', 'SS']: - max_rar = 1 - if roster_counts['Replacement'] < roster_counts['Reserve']: - max_rar = 0 + for pos in ["C", "1B", "2B", "3B", "SS"]: + if roster_counts["Replacement"] < roster_counts["Reserve"]: + rarity_param = ("rarity", 0) + else: + rarity_param = ("rarity", 1) r_draw = await db_get( - 'players/random', params=[('pos_include', pos), ('max_rarity', max_rar), ('limit', 2)], none_okay=False + "players/random", + params=[("pos_include", pos), rarity_param, ("limit", 2)], + none_okay=False, ) - team_infielders.extend(r_draw['players']) + team_infielders.extend(r_draw["players"]) update_roster_counts(team_infielders) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in team_infielders] - }, timeout=10) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in team_infielders + ] + }, + timeout=10, + ) # Collect outfielders team_outfielders = [] - for pos in ['LF', 'CF', 'RF']: - max_rar = 1 - if roster_counts['Replacement'] < roster_counts['Reserve']: - max_rar = 0 + for pos in ["LF", "CF", "RF"]: + if roster_counts["Replacement"] < roster_counts["Reserve"]: + rarity_param = ("rarity", 0) + else: + rarity_param = ("rarity", 1) r_draw = await db_get( - 'players/random', params=[('pos_include', pos), ('max_rarity', max_rar), ('limit', 2)], none_okay=False + "players/random", + params=[("pos_include", pos), rarity_param, ("limit", 2)], + none_okay=False, ) - team_outfielders.extend(r_draw['players']) + team_outfielders.extend(r_draw["players"]) update_roster_counts(team_outfielders) - await db_post('cards', payload={'cards': [ - {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in team_outfielders] - }, timeout=10) + await db_post( + "cards", + payload={ + "cards": [ + { + "player_id": x["player_id"], + "team_id": team["id"], + "pack_id": this_pack["id"], + } + for x in team_outfielders + ] + }, + timeout=10, + ) async with op_ch.typing(): done_anc = await display_cards( - [{'player': x, 'team': team} for x in anchor_players], team, op_ch, interaction.user, self.bot, - cust_message=f'Let\'s take a look at your three {team_choice} anchor players.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in anchor_players], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"Let's take a look at your three {team_choice} anchor players.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) - error_text = f'Yikes - I can\'t display the rest of your team. {get_cal_user(interaction).mention} plz halp' + error_text = f"Yikes - I can't display the rest of your team. {get_cal_user(interaction).mention} plz halp" if not done_anc: await op_ch.send(error_text) async with op_ch.typing(): done_sp = await display_cards( - [{'player': x, 'team': team} for x in team_sp], team, op_ch, interaction.user, self.bot, - cust_message=f'Here are your starting pitchers.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in team_sp], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"Here are your starting pitchers.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) if not done_sp: @@ -343,10 +469,14 @@ class TeamSetup(commands.Cog): async with op_ch.typing(): done_rp = await display_cards( - [{'player': x, 'team': team} for x in team_rp], team, op_ch, interaction.user, self.bot, - cust_message=f'And now for your bullpen.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in team_rp], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"And now for your bullpen.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) if not done_rp: @@ -354,10 +484,14 @@ class TeamSetup(commands.Cog): async with op_ch.typing(): done_inf = await display_cards( - [{'player': x, 'team': team} for x in team_infielders], team, op_ch, interaction.user, self.bot, - cust_message=f'Next let\'s take a look at your infielders.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in team_infielders], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"Next let's take a look at your infielders.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) if not done_inf: @@ -365,10 +499,14 @@ class TeamSetup(commands.Cog): async with op_ch.typing(): done_out = await display_cards( - [{'player': x, 'team': team} for x in team_outfielders], team, op_ch, interaction.user, self.bot, - cust_message=f'Now let\'s take a look at your outfielders.\n' - f'Press `Close Pack` to continue.', - add_roster=False + [{"player": x, "team": team} for x in team_outfielders], + team, + op_ch, + interaction.user, + self.bot, + cust_message=f"Now let's take a look at your outfielders.\n" + f"Press `Close Pack` to continue.", + add_roster=False, ) if not done_out: @@ -376,129 +514,154 @@ class TeamSetup(commands.Cog): await give_packs(team, 1) await op_ch.send( - f'To get you started, I\'ve spotted you 100₼ and a pack of cards. You can rip that with the ' - f'`/open` command once your google sheet is set up!' + f"To get you started, I've spotted you 100₼ and a pack of cards. You can rip that with the " + f"`/open` command once your google sheet is set up!" ) await op_ch.send( - f'{t_role.mention}\n\n' - f'There\'s your roster! We have one more step and you will be ready to play.\n\n{SHEET_SHARE_STEPS}\n\n' - f'{get_roster_sheet({"gsheet": current["gsheet_template"]})}' + f"{t_role.mention}\n\n" + f"There's your roster! We have one more step and you will be ready to play.\n\n{SHEET_SHARE_STEPS}\n\n" + f"{get_roster_sheet({'gsheet': current['gsheet_template']})}" ) - new_team_embed = await team_summary_embed(team, interaction, include_roster=False) + new_team_embed = await team_summary_embed( + team, interaction, include_roster=False + ) await send_to_channel( - self.bot, "pd-network-news", content='A new challenger approaches...', embed=new_team_embed + self.bot, + "pd-network-news", + content="A new challenger approaches...", + embed=new_team_embed, ) - @commands.hybrid_command(name='newsheet', help='Link a new team sheet with your team') + @commands.hybrid_command( + name="newsheet", help="Link a new team sheet with your team" + ) @commands.has_any_role(PD_PLAYERS) async def share_sheet_command( - self, ctx, google_sheet_url: str, team_abbrev: Optional[str], copy_rosters: Optional[bool] = True): + self, + ctx, + google_sheet_url: str, + team_abbrev: Optional[str], + copy_rosters: Optional[bool] = True, + ): owner_team = await get_team_by_owner(get_context_user(ctx).id) if not owner_team: - await ctx.send(f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!') + await ctx.send( + f"I don't see a team for you, yet. You can sign up with the `/newteam` command!" + ) return team = owner_team - if team_abbrev and team_abbrev != owner_team['abbrev']: + if team_abbrev and team_abbrev != owner_team["abbrev"]: if get_context_user(ctx).id != 258104532423147520: - await ctx.send(f'You can only update the team sheet for your own team, you goober.') + await ctx.send( + f"You can only update the team sheet for your own team, you goober." + ) return else: team = await get_team_by_abbrev(team_abbrev) - current = await db_get('current') - if current['gsheet_template'] in google_sheet_url: - await ctx.send(f'Ope, looks like that is the template sheet. Would you please make a copy and then share?') + current = await db_get("current") + if current["gsheet_template"] in google_sheet_url: + await ctx.send( + f"Ope, looks like that is the template sheet. Would you please make a copy and then share?" + ) return - gauntlet_team = await get_team_by_abbrev(f'Gauntlet-{owner_team["abbrev"]}') + gauntlet_team = await get_team_by_abbrev(f"Gauntlet-{owner_team['abbrev']}") if gauntlet_team: - view = ButtonOptions([ctx.author], timeout=30, labels=['Main Team', 'Gauntlet Team', None, None, None]) - question = await ctx.send(f'Is this sheet for your main PD team or your active Gauntlet team?', view=view) + view = ButtonOptions( + [ctx.author], + timeout=30, + labels=["Main Team", "Gauntlet Team", None, None, None], + ) + question = await ctx.send( + f"Is this sheet for your main PD team or your active Gauntlet team?", + view=view, + ) await view.wait() if not view.value: await question.edit( - content=f'Okay you keep thinking on it and get back to me when you\'re ready.', view=None + content=f"Okay you keep thinking on it and get back to me when you're ready.", + view=None, ) return - elif view.value == 'Gauntlet Team': + elif view.value == "Gauntlet Team": await question.delete() team = gauntlet_team sheets = get_sheets(self.bot) - response = await ctx.send(f'I\'ll go grab that sheet...') + response = await ctx.send(f"I'll go grab that sheet...") try: new_sheet = sheets.open_by_url(google_sheet_url) except Exception as e: - logger.error(f'Error accessing {team["abbrev"]} sheet: {e}') - current = await db_get('current') - await ctx.send(f'I wasn\'t able to access that sheet. Did you remember to share it with my PD email?' - f'\n\nHere\'s a quick refresher:\n{SHEET_SHARE_STEPS}\n\n' - f'{get_roster_sheet({"gsheet": current["gsheet_template"]})}') + logger.error(f"Error accessing {team['abbrev']} sheet: {e}") + current = await db_get("current") + await ctx.send( + f"I wasn't able to access that sheet. Did you remember to share it with my PD email?" + f"\n\nHere's a quick refresher:\n{SHEET_SHARE_STEPS}\n\n" + f"{get_roster_sheet({'gsheet': current['gsheet_template']})}" + ) return - team_data = new_sheet.worksheet_by_title('Team Data') + team_data = new_sheet.worksheet_by_title("Team Data") if not gauntlet_team or owner_team != gauntlet_team: team_data.update_values( - crange='B1:B2', - values=[[f'{team["id"]}'], [f'{team_hash(team)}']] + crange="B1:B2", values=[[f"{team['id']}"], [f"{team_hash(team)}"]] ) - if copy_rosters and team['gsheet'].lower() != 'none': - old_sheet = sheets.open_by_key(team['gsheet']) - r_sheet = old_sheet.worksheet_by_title(f'My Rosters') - roster_ids = r_sheet.range('B3:B80') - lineups_data = r_sheet.range('H4:M26') + if copy_rosters and team["gsheet"].lower() != "none": + old_sheet = sheets.open_by_key(team["gsheet"]) + r_sheet = old_sheet.worksheet_by_title(f"My Rosters") + roster_ids = r_sheet.range("B3:B80") + lineups_data = r_sheet.range("H4:M26") new_r_data, new_l_data = [], [] for row in roster_ids: - if row[0].value != '': + if row[0].value != "": new_r_data.append([int(row[0].value)]) else: new_r_data.append([None]) - logger.debug(f'new_r_data: {new_r_data}') + logger.debug(f"new_r_data: {new_r_data}") for row in lineups_data: - logger.debug(f'row: {row}') - new_l_data.append([ - row[0].value if row[0].value != '' else None, - int(row[1].value) if row[1].value != '' else None, - row[2].value if row[2].value != '' else None, - int(row[3].value) if row[3].value != '' else None, - row[4].value if row[4].value != '' else None, - int(row[5].value) if row[5].value != '' else None - ]) - logger.debug(f'new_l_data: {new_l_data}') + logger.debug(f"row: {row}") + new_l_data.append( + [ + row[0].value if row[0].value != "" else None, + int(row[1].value) if row[1].value != "" else None, + row[2].value if row[2].value != "" else None, + int(row[3].value) if row[3].value != "" else None, + row[4].value if row[4].value != "" else None, + int(row[5].value) if row[5].value != "" else None, + ] + ) + logger.debug(f"new_l_data: {new_l_data}") - new_r_sheet = new_sheet.worksheet_by_title(f'My Rosters') - new_r_sheet.update_values( - crange='B3:B80', - values=new_r_data - ) - new_r_sheet.update_values( - crange='H4:M26', - values=new_l_data - ) + new_r_sheet = new_sheet.worksheet_by_title(f"My Rosters") + new_r_sheet.update_values(crange="B3:B80", values=new_r_data) + new_r_sheet.update_values(crange="H4:M26", values=new_l_data) - if team['has_guide']: + if team["has_guide"]: post_ratings_guide(team, self.bot, this_sheet=new_sheet) - team = await db_patch('teams', object_id=team['id'], params=[('gsheet', new_sheet.id)]) + team = await db_patch( + "teams", object_id=team["id"], params=[("gsheet", new_sheet.id)] + ) await refresh_sheet(team, self.bot, sheets) - conf_message = f'Alright, your sheet is linked to your team - good luck' + conf_message = f"Alright, your sheet is linked to your team - good luck" if owner_team == team: - conf_message += ' this season!' + conf_message += " this season!" else: - conf_message += ' on your run!' - conf_message += f'\n\n{HELP_SHEET_SCRIPTS}' - await response.edit(content=f'{conf_message}') + conf_message += " on your run!" + conf_message += f"\n\n{HELP_SHEET_SCRIPTS}" + await response.edit(content=f"{conf_message}") async def setup(bot): """Setup function for the TeamSetup cog.""" - await bot.add_cog(TeamSetup(bot)) \ No newline at end of file + await bot.add_cog(TeamSetup(bot)) diff --git a/db_calls_gameplay.py b/db_calls_gameplay.py index cc0387f..97d1f56 100644 --- a/db_calls_gameplay.py +++ b/db_calls_gameplay.py @@ -16,28 +16,24 @@ from api_calls import db_get from in_game.data_cache import get_pd_player, CardPosition, BattingCard, get_pd_team db = SqliteDatabase( - 'storage/gameplay-legacy.db', - pragmas={ - 'journal_mode': 'wal', - 'cache_size': -1 * 64000, - 'synchronous': 0 - } + "storage/gameplay-legacy.db", + pragmas={"journal_mode": "wal", "cache_size": -1 * 64000, "synchronous": 0}, ) -SBA_DB_URL = 'http://database/api' -logger = logging.getLogger('discord_app') +SBA_DB_URL = "http://database/api" +logger = logging.getLogger("discord_app") def param_char(other_params): if other_params: - return '&' + return "&" else: - return '?' + return "?" def get_sba_team(id_or_abbrev, season=None): - req_url = f'{SBA_DB_URL}/v1/teams/{id_or_abbrev}' + req_url = f"{SBA_DB_URL}/v1/teams/{id_or_abbrev}" if season: - req_url += f'?season={season}' + req_url += f"?season={season}" resp = requests.get(req_url, timeout=3) @@ -45,33 +41,36 @@ def get_sba_team(id_or_abbrev, season=None): return resp.json() else: logger.warning(resp.text) - raise ValueError(f'DB: {resp.text}') + raise ValueError(f"DB: {resp.text}") def get_sba_player(id_or_name, season=None): - req_url = f'{SBA_DB_URL}/v2/players/{id_or_name}' + req_url = f"{SBA_DB_URL}/v2/players/{id_or_name}" if season is not None: - req_url += f'?season={season}' + req_url += f"?season={season}" resp = requests.get(req_url, timeout=3) if resp.status_code == 200: return resp.json() else: logger.warning(resp.text) - raise ValueError(f'DB: {resp.text}') + raise ValueError(f"DB: {resp.text}") def get_sba_team_by_owner(season, owner_id): - resp = requests.get(f'{SBA_DB_URL}/v1/teams?season={season}&owner_id={owner_id}&active_only=True', timeout=3) + resp = requests.get( + f"{SBA_DB_URL}/v1/teams?season={season}&owner_id={owner_id}&active_only=True", + timeout=3, + ) if resp.status_code == 200: full_resp = resp.json() - if len(full_resp['teams']) != 1: - raise ValueError(f'One team requested, but {len(full_resp)} were returned') + if len(full_resp["teams"]) != 1: + raise ValueError(f"One team requested, but {len(full_resp)} were returned") else: - return full_resp['teams'][0] + return full_resp["teams"][0] else: logger.warning(resp.text) - raise ValueError(f'DB: {resp.text}') + raise ValueError(f"DB: {resp.text}") # def pd_await db_get(endpoint: str, api_ver: int = 1, object_id: int = None, params: list = None, none_okay: bool = True): @@ -151,9 +150,7 @@ class ManagerAi(BaseModel): def load_ai(): - all_ai = [ - {'name': 'Basic'} - ] + all_ai = [{"name": "Basic"}] for x in all_ai: ManagerAi.create(**x) @@ -161,8 +158,9 @@ def load_ai(): def ai_batting(this_game, this_play) -> bool: - return (this_play.inning_half == 'Top' and this_game.ai_team == 'away') or \ - (this_play.inning_half == 'Bot' and this_game.ai_team == 'home') + return (this_play.inning_half == "Top" and this_game.ai_team == "away") or ( + this_play.inning_half == "Bot" and this_game.ai_team == "home" + ) db.create_tables([ManagerAi]) @@ -183,12 +181,10 @@ class Game(BaseModel): home_roster_num = IntegerField(null=True) first_message = IntegerField(null=True) ai_team = CharField(null=True) - game_type = CharField(default='minor-league') + game_type = CharField(default="minor-league") cardset_ids = CharField(null=True) backup_cardset_ids = CharField(null=True) - # TODO: add get_away_team and get_home_team that deals with SBa/PD and returns Team object - @dataclass class StratGame: @@ -211,6 +207,12 @@ class StratGame: cardset_ids: str = None backup_cardset_ids: str = None + async def get_away_team(self): + return await get_game_team(self, team_id=self.away_team_id) + + async def get_home_team(self): + return await get_game_team(self, team_id=self.home_team_id) + db.create_tables([Game]) @@ -227,9 +229,10 @@ db.create_tables([Game]) def count_team_games(team_id: int, active: bool = True): all_games = Game.select().where( - ((Game.away_team_id == team_id) | (Game.home_team_id == team_id)) & (Game.active == active) + ((Game.away_team_id == team_id) | (Game.home_team_id == team_id)) + & (Game.active == active) ) - return {'count': all_games.count(), 'games': [model_to_dict(x) for x in all_games]} + return {"count": all_games.count(), "games": [model_to_dict(x) for x in all_games]} def post_game(game_dict: dict): @@ -247,18 +250,39 @@ def post_game(game_dict: dict): new_game = Game.create(**game_dict) # return_game = model_to_dict(new_game) return_game = StratGame( - new_game.id, new_game.away_team_id, new_game.home_team_id, new_game.channel_id, new_game.season, - new_game.active, new_game.is_pd, new_game.ranked, new_game.short_game, new_game.week_num, new_game.game_num, - new_game.away_roster_num, new_game.home_roster_num, new_game.first_message, new_game.ai_team, - new_game.game_type, new_game.cardset_ids, new_game.backup_cardset_ids + new_game.id, + new_game.away_team_id, + new_game.home_team_id, + new_game.channel_id, + new_game.season, + new_game.active, + new_game.is_pd, + new_game.ranked, + new_game.short_game, + new_game.week_num, + new_game.game_num, + new_game.away_roster_num, + new_game.home_roster_num, + new_game.first_message, + new_game.ai_team, + new_game.game_type, + new_game.cardset_ids, + new_game.backup_cardset_ids, ) db.close() return return_game -def get_one_game(game_id=None, away_team_id=None, home_team_id=None, week_num=None, game_num=None, - channel_id=None, active=None) -> Optional[StratGame]: +def get_one_game( + game_id=None, + away_team_id=None, + home_team_id=None, + week_num=None, + game_num=None, + channel_id=None, + active=None, +) -> Optional[StratGame]: single_game, this_game = None, None if game_id is not None: single_game = Game.get_by_id(game_id) @@ -289,13 +313,21 @@ def get_one_game(game_id=None, away_team_id=None, home_team_id=None, week_num=No async def get_game_team( - game: StratGame, gm_id: int = None, team_abbrev: str = None, team_id: int = None, - skip_cache: bool = False) -> dict: + game: StratGame, + gm_id: int = None, + team_abbrev: str = None, + team_id: int = None, + skip_cache: bool = False, +) -> dict: if not gm_id and not team_abbrev and not team_id: - raise KeyError(f'get_game_team requires either one of gm_id, team_abbrev, or team_id to not be None') + raise KeyError( + f"get_game_team requires either one of gm_id, team_abbrev, or team_id to not be None" + ) - logger.debug(f'getting game team for game {game.id} / gm_id: {gm_id} / ' - f'tm_abbrev: {team_abbrev} / team_id: {team_id} / game: {game}') + logger.debug( + f"getting game team for game {game.id} / gm_id: {gm_id} / " + f"tm_abbrev: {team_abbrev} / team_id: {team_id} / game: {game}" + ) if game.is_pd: if team_id: return await get_pd_team(team_id, skip_cache=skip_cache) @@ -304,8 +336,10 @@ async def get_game_team( # t_query = await db_get('teams', params=[('season', PD_SEASON), ('gm_id', gm_id)]) # return t_query['teams'][0] else: - t_query = await db_get('teams', params=[('season', PD_SEASON), ('abbrev', team_abbrev)]) - return t_query['teams'][0] + t_query = await db_get( + "teams", params=[("season", PD_SEASON), ("abbrev", team_abbrev)] + ) + return t_query["teams"][0] else: if gm_id: return get_sba_team_by_owner(season=SBA_SEASON, owner_id=gm_id) @@ -316,9 +350,20 @@ async def get_game_team( def patch_game( - game_id, away_team_id=None, home_team_id=None, week_num=None, game_num=None, channel_id=None, active=None, - first_message=None, home_roster_num=None, away_roster_num=None, ai_team=None, cardset_ids=None, - backup_cardset_ids=None): + game_id, + away_team_id=None, + home_team_id=None, + week_num=None, + game_num=None, + channel_id=None, + active=None, + first_message=None, + home_roster_num=None, + away_roster_num=None, + ai_team=None, + cardset_ids=None, + backup_cardset_ids=None, +): this_game = Game.get_by_id(game_id) if away_team_id is not None: this_game.away_team_id = away_team_id @@ -347,10 +392,24 @@ def patch_game( this_game.save() # return_game = model_to_dict(this_game) return_game = StratGame( - this_game.id, this_game.away_team_id, this_game.home_team_id, this_game.channel_id, this_game.season, - this_game.active, this_game.is_pd, this_game.ranked, this_game.short_game, this_game.week_num, - this_game.game_num, this_game.away_roster_num, this_game.home_roster_num, this_game.first_message, - this_game.ai_team, this_game.game_type, this_game.cardset_ids, this_game.backup_cardset_ids + this_game.id, + this_game.away_team_id, + this_game.home_team_id, + this_game.channel_id, + this_game.season, + this_game.active, + this_game.is_pd, + this_game.ranked, + this_game.short_game, + this_game.week_num, + this_game.game_num, + this_game.away_roster_num, + this_game.home_roster_num, + this_game.first_message, + this_game.ai_team, + this_game.game_type, + this_game.cardset_ids, + this_game.backup_cardset_ids, ) db.close() return return_game @@ -402,7 +461,7 @@ class StratLineup: def convert_stratlineup(lineup: Lineup) -> StratLineup: lineup_dict = model_to_dict(lineup) - lineup_dict['game'] = StratGame(**lineup_dict['game']) + lineup_dict["game"] = StratGame(**lineup_dict["game"]) return StratLineup(**lineup_dict) @@ -410,28 +469,43 @@ db.create_tables([Lineup]) def get_one_lineup( - game_id: int, lineup_id: int = None, team_id: int = None, batting_order: int = None, position: str = None, - card_id: int = None, active: bool = True, as_obj: bool = False) -> Optional[StratLineup]: + game_id: int, + lineup_id: int = None, + team_id: int = None, + batting_order: int = None, + position: str = None, + card_id: int = None, + active: bool = True, + as_obj: bool = False, +) -> Optional[StratLineup]: if not batting_order and not position and not lineup_id and not card_id: - raise KeyError(f'One of batting_order, position, card_id , or lineup_id must not be None') + raise KeyError( + f"One of batting_order, position, card_id , or lineup_id must not be None" + ) if lineup_id: this_lineup = Lineup.get_by_id(lineup_id) elif card_id: this_lineup = Lineup.get_or_none( - Lineup.game_id == game_id, Lineup.card_id == card_id, Lineup.active == active + Lineup.game_id == game_id, + Lineup.card_id == card_id, + Lineup.active == active, ) elif batting_order: this_lineup = Lineup.get_or_none( - Lineup.game_id == game_id, Lineup.team_id == team_id, Lineup.batting_order == batting_order, - Lineup.active == active + Lineup.game_id == game_id, + Lineup.team_id == team_id, + Lineup.batting_order == batting_order, + Lineup.active == active, ) else: this_lineup = Lineup.get_or_none( - Lineup.game_id == game_id, Lineup.team_id == team_id, Lineup.position == position, - Lineup.active == active + Lineup.game_id == game_id, + Lineup.team_id == team_id, + Lineup.position == position, + Lineup.active == active, ) - logger.debug(f'get_one_lineup / this_lineup: {this_lineup}') + logger.debug(f"get_one_lineup / this_lineup: {this_lineup}") if as_obj: return this_lineup @@ -456,25 +530,32 @@ def get_one_lineup( async def get_team_lineups( - game_id: int, team_id: int, inc_inactive: bool = False, pitchers_only: bool = False, as_string: bool = True): - all_lineups = Lineup.select().where( - (Lineup.game_id == game_id) & (Lineup.team_id == team_id) - ).order_by(Lineup.batting_order) + game_id: int, + team_id: int, + inc_inactive: bool = False, + pitchers_only: bool = False, + as_string: bool = True, +): + all_lineups = ( + Lineup.select() + .where((Lineup.game_id == game_id) & (Lineup.team_id == team_id)) + .order_by(Lineup.batting_order) + ) if not inc_inactive: all_lineups = all_lineups.where(Lineup.active == True) if pitchers_only: - all_lineups = all_lineups.where(Lineup.position == 'P') + all_lineups = all_lineups.where(Lineup.position == "P") # if all_lineups.count() == 0: # return None if as_string: - l_string = '' + l_string = "" this_game = Game.get_by_id(game_id) for x in all_lineups: - l_string += f'{x.batting_order}. {player_link(this_game, await get_player(this_game, x))} - {x.position}\n' + l_string += f"{x.batting_order}. {player_link(this_game, await get_player(this_game, x))} - {x.position}\n" db.close() return l_string @@ -494,8 +575,13 @@ def post_lineups(lineups: list): db.close() -def patch_lineup(lineup_id, active: Optional[bool] = None, position: Optional[str] = None, - replacing_id: Optional[int] = None, is_fatigued: Optional[bool] = None) -> StratLineup: +def patch_lineup( + lineup_id, + active: Optional[bool] = None, + position: Optional[str] = None, + replacing_id: Optional[int] = None, + is_fatigued: Optional[bool] = None, +) -> StratLineup: this_lineup = Lineup.get_by_id(lineup_id) if active is not None: this_lineup.active = active @@ -516,45 +602,51 @@ def patch_lineup(lineup_id, active: Optional[bool] = None, position: Optional[st def make_sub(lineup_dict: dict): # Check for dupe player / card - this_game = Game.get_by_id(lineup_dict['game_id']) + this_game = Game.get_by_id(lineup_dict["game_id"]) if this_game.is_pd: player_conflict = Lineup.select().where( - (Lineup.game_id == lineup_dict['game_id']) & (Lineup.team_id == lineup_dict['team_id']) & - (Lineup.card_id == lineup_dict['card_id']) + (Lineup.game_id == lineup_dict["game_id"]) + & (Lineup.team_id == lineup_dict["team_id"]) + & (Lineup.card_id == lineup_dict["card_id"]) ) - db_error = f'This card is already in the lineup' + db_error = f"This card is already in the lineup" else: player_conflict = Lineup.select().where( - (Lineup.game_id == lineup_dict['game_id']) & (Lineup.team_id == lineup_dict['team_id']) & - (Lineup.player_id == lineup_dict['player_id']) + (Lineup.game_id == lineup_dict["game_id"]) + & (Lineup.team_id == lineup_dict["team_id"]) + & (Lineup.player_id == lineup_dict["player_id"]) ) - db_error = f'This player is already in the lineup' + db_error = f"This player is already in the lineup" if player_conflict.count(): db.close() raise DatabaseError(db_error) subbed_player = Lineup.get_or_none( - Lineup.game_id == lineup_dict['game_id'], Lineup.team_id == lineup_dict['team_id'], - Lineup.batting_order == lineup_dict['batting_order'], Lineup.active == True + Lineup.game_id == lineup_dict["game_id"], + Lineup.team_id == lineup_dict["team_id"], + Lineup.batting_order == lineup_dict["batting_order"], + Lineup.active == True, ) - logger.debug(f'subbed_player: {subbed_player}') + logger.debug(f"subbed_player: {subbed_player}") if subbed_player: subbed_player = patch_lineup(subbed_player.id, active=False) - lineup_dict['replacing_id'] = subbed_player.id + lineup_dict["replacing_id"] = subbed_player.id new_lineup = Lineup.create(**lineup_dict) # return_lineup = model_to_dict(new_lineup) return_value = convert_stratlineup(new_lineup) - curr_play = get_current_play(lineup_dict['game_id']) - logger.debug(f'\n\nreturn_value: {return_value}\n\ncurr_play: {curr_play}\n\n') + curr_play = get_current_play(lineup_dict["game_id"]) + logger.debug(f"\n\nreturn_value: {return_value}\n\ncurr_play: {curr_play}\n\n") # Check current play for updates if curr_play: - if (not curr_play.pitcher and curr_play.batter.team_id != return_value.team_id) or return_value.position == 'P': + if ( + not curr_play.pitcher and curr_play.batter.team_id != return_value.team_id + ) or return_value.position == "P": patch_play(curr_play.id, pitcher_id=return_value.id) if subbed_player: @@ -577,20 +669,24 @@ def make_sub(lineup_dict: dict): def undo_subs(game: StratGame, new_play_num: int): - logger.info(f'get new players') - new_players = Lineup.select().where((Lineup.game_id == game.id) & (Lineup.after_play > new_play_num)) - logger.info(f'new_player count: {new_players.count()}') + logger.info(f"get new players") + new_players = Lineup.select().where( + (Lineup.game_id == game.id) & (Lineup.after_play > new_play_num) + ) + logger.info(f"new_player count: {new_players.count()}") replacements = [(x.id, x.replacing_id) for x in new_players] for x in replacements: - logger.info(f'replacing {x[0]} with {x[1]}') + logger.info(f"replacing {x[0]} with {x[1]}") old_player = get_one_lineup(game_id=game.id, lineup_id=x[1]) - logger.info(f'old_player: {old_player}') + logger.info(f"old_player: {old_player}") patch_lineup(old_player.id, active=True) - logger.info(f'activated!') + logger.info(f"activated!") - logger.info(f'done activating old players') - Lineup.delete().where((Lineup.game_id == game.id) & (Lineup.after_play > new_play_num)).execute() + logger.info(f"done activating old players") + Lineup.delete().where( + (Lineup.game_id == game.id) & (Lineup.after_play > new_play_num) + ).execute() async def get_player(game, lineup_member, as_dict: bool = True): @@ -599,49 +695,53 @@ async def get_player(game, lineup_member, as_dict: bool = True): if isinstance(game, Game): if game.is_pd: - this_card = await db_get(f'cards', object_id=lineup_member.card_id) - player = this_card['player'] - player['name'] = player['p_name'] - player['team'] = this_card['team'] + this_card = await db_get(f"cards", object_id=lineup_member.card_id) + player = this_card["player"] + player["name"] = player["p_name"] + player["team"] = this_card["team"] return player else: return get_sba_player(lineup_member.player_id) elif isinstance(game, StratGame): if game.is_pd: # card_id = lineup_member.card_id if isinstance(lineup_member, Lineup) else lineup_member['card_id'] - card_id = lineup_member['card_id'] if isinstance(lineup_member, dict) else lineup_member.card_id - this_card = await db_get(f'cards', object_id=card_id) - player = this_card['player'] - player['name'] = player['p_name'] - player['team'] = this_card['team'] - logger.debug(f'player: {player}') + card_id = ( + lineup_member["card_id"] + if isinstance(lineup_member, dict) + else lineup_member.card_id + ) + this_card = await db_get(f"cards", object_id=card_id) + player = this_card["player"] + player["name"] = player["p_name"] + player["team"] = this_card["team"] + logger.debug(f"player: {player}") return player else: return get_sba_player(lineup_member.player_id) else: - raise TypeError(f'Cannot get player; game is not a valid object') + raise TypeError(f"Cannot get player; game is not a valid object") def player_link(game, player): if isinstance(game, Game): if game.is_pd: - return f'[{player["p_name"]}]({player["image"]})' + return f"[{player['p_name']}]({player['image']})" else: return get_player_url(player) elif isinstance(game, StratGame): if game.is_pd: - return f'[{player["p_name"]}]({player["image"]})' + return f"[{player['p_name']}]({player['image']})" else: return get_player_url(player) else: - raise TypeError(f'Cannot get player link; game is not a valid object') + raise TypeError(f"Cannot get player link; game is not a valid object") class Play(BaseModel): game = ForeignKeyField(Game) play_num = IntegerField() batter = ForeignKeyField(Lineup) - batter_pos = CharField(default='DH') + batter_pos = CharField(default="DH") pitcher = ForeignKeyField(Lineup, null=True) on_base_code = IntegerField() inning_half = CharField() @@ -770,7 +870,7 @@ class StratPlay: is_new_inning: bool = False def ai_run_diff(self): - if self.game.ai_team == 'away': + if self.game.ai_team == "away": return self.away_score - self.home_score else: return self.home_score - self.away_score @@ -778,23 +878,23 @@ class StratPlay: def convert_stratplay(play: Play) -> StratPlay: play_dict = model_to_dict(play) - play_dict['game'] = StratGame(**play_dict['game']) - if play_dict['batter']: - play_dict['batter'] = convert_stratlineup(play.batter) - if play_dict['pitcher']: - play_dict['pitcher'] = convert_stratlineup(play.pitcher) - if play_dict['on_first']: - play_dict['on_first'] = convert_stratlineup(play.on_first) - if play_dict['on_second']: - play_dict['on_second'] = convert_stratlineup(play.on_second) - if play_dict['on_third']: - play_dict['on_third'] = convert_stratlineup(play.on_third) - if play_dict['catcher']: - play_dict['catcher'] = convert_stratlineup(play.catcher) - if play_dict['defender']: - play_dict['defender'] = convert_stratlineup(play.defender) - if play_dict['runner']: - play_dict['runner'] = convert_stratlineup(play.runner) + play_dict["game"] = StratGame(**play_dict["game"]) + if play_dict["batter"]: + play_dict["batter"] = convert_stratlineup(play.batter) + if play_dict["pitcher"]: + play_dict["pitcher"] = convert_stratlineup(play.pitcher) + if play_dict["on_first"]: + play_dict["on_first"] = convert_stratlineup(play.on_first) + if play_dict["on_second"]: + play_dict["on_second"] = convert_stratlineup(play.on_second) + if play_dict["on_third"]: + play_dict["on_third"] = convert_stratlineup(play.on_third) + if play_dict["catcher"]: + play_dict["catcher"] = convert_stratlineup(play.catcher) + if play_dict["defender"]: + play_dict["defender"] = convert_stratlineup(play.defender) + if play_dict["runner"]: + play_dict["runner"] = convert_stratlineup(play.runner) return StratPlay(**play_dict) @@ -803,7 +903,7 @@ db.create_tables([Play]) def post_play(play_dict: dict) -> StratPlay: - logger.debug(f'play_dict: {play_dict}') + logger.debug(f"play_dict: {play_dict}") new_play = Play.create(**play_dict) # return_play = model_to_dict(new_play) return_play = convert_stratplay(new_play) @@ -813,15 +913,52 @@ def post_play(play_dict: dict) -> StratPlay: def patch_play( - play_id, batter_id: int = None, pitcher_id: int = None, catcher_id: int = None, locked: bool = None, - pa: int = None, ab: int = None, hit: int = None, double: int = None, triple: int = None, homerun: int = None, - outs: int = None, so: int = None, bp1b: int = None, bplo: int = None, bphr: int = None, bpfo: int = None, - walk: int = None, hbp: int = None, ibb: int = None, sac: int = None, sb: int = None, is_go_ahead: bool = None, - defender_id: int = None, check_pos: str = None, error: int = None, play_num: int = None, cs: int = None, - on_first_id: int = None, on_first_final: int = None, on_second_id: int = None, on_second_final: int = None, - on_third_id: int = None, on_third_final: int = None, starting_outs: int = None, runner_id: int = None, - complete: bool = None, rbi: int = None, wp: int = None, pb: int = None, pick: int = None, balk: int = None, - is_new_inning: bool = None, batter_final: int = None, in_pow: bool = None): + play_id, + batter_id: int = None, + pitcher_id: int = None, + catcher_id: int = None, + locked: bool = None, + pa: int = None, + ab: int = None, + hit: int = None, + double: int = None, + triple: int = None, + homerun: int = None, + outs: int = None, + so: int = None, + bp1b: int = None, + bplo: int = None, + bphr: int = None, + bpfo: int = None, + walk: int = None, + hbp: int = None, + ibb: int = None, + sac: int = None, + sb: int = None, + is_go_ahead: bool = None, + defender_id: int = None, + check_pos: str = None, + error: int = None, + play_num: int = None, + cs: int = None, + on_first_id: int = None, + on_first_final: int = None, + on_second_id: int = None, + on_second_final: int = None, + on_third_id: int = None, + on_third_final: int = None, + starting_outs: int = None, + runner_id: int = None, + complete: bool = None, + rbi: int = None, + wp: int = None, + pb: int = None, + pick: int = None, + balk: int = None, + is_new_inning: bool = None, + batter_final: int = None, + in_pow: bool = None, +): this_play = Play.get_by_id(play_id) if batter_id is not None: @@ -890,7 +1027,7 @@ def patch_play( else: this_play.defender_id = defender_id if check_pos is not None: - if check_pos.lower() == 'false': + if check_pos.lower() == "false": this_play.check_pos = None else: this_play.check_pos = check_pos @@ -964,9 +1101,9 @@ def get_plays(game_id: int = None, pitcher_id: int = None): if pitcher_id is not None: all_plays = all_plays.where(Play.pitcher_id == pitcher_id) - return_plays = {'count': all_plays.count(), 'plays': []} + return_plays = {"count": all_plays.count(), "plays": []} for line in all_plays: - return_plays['plays'].append(convert_stratplay(line)) + return_plays["plays"].append(convert_stratplay(line)) db.close() return return_plays @@ -983,7 +1120,9 @@ def get_play_by_num(game_id, play_num: int): def get_latest_play(game_id): - latest_play = Play.select().where(Play.game_id == game_id).order_by(-Play.id).limit(1) + latest_play = ( + Play.select().where(Play.game_id == game_id).order_by(-Play.id).limit(1) + ) if not latest_play: return None @@ -995,7 +1134,7 @@ def get_latest_play(game_id): def undo_play(game_id): p_query = Play.delete().where(Play.game_id == game_id).order_by(-Play.id).limit(1) - logger.debug(f'p_query: {p_query}') + logger.debug(f"p_query: {p_query}") count = p_query.execute() db.close() @@ -1005,12 +1144,16 @@ def undo_play(game_id): def get_current_play(game_id) -> Optional[StratPlay]: curr_play = Play.get_or_none(Play.game_id == game_id, Play.complete == False) if not curr_play: - latest_play = Play.select().where(Play.game_id == game_id).order_by(-Play.id).limit(1) + latest_play = ( + Play.select().where(Play.game_id == game_id).order_by(-Play.id).limit(1) + ) if not latest_play: return None else: complete_play(latest_play[0].id, batter_to_base=latest_play[0].batter_final) - curr_play = Play.get_or_none(Play.game_id == game_id, Play.complete == False) + curr_play = Play.get_or_none( + Play.game_id == game_id, Play.complete == False + ) # return_play = model_to_dict(curr_play) return_play = convert_stratplay(curr_play) @@ -1019,9 +1162,15 @@ def get_current_play(game_id) -> Optional[StratPlay]: def get_last_inning_end_play(game_id, inning_half, inning_num): - this_play = Play.select().where( - (Play.game_id == game_id) & (Play.inning_half == inning_half) & (Play.inning_num == inning_num) - ).order_by(-Play.id) + this_play = ( + Play.select() + .where( + (Play.game_id == game_id) + & (Play.inning_half == inning_half) + & (Play.inning_num == inning_num) + ) + .order_by(-Play.id) + ) # return_play = model_to_dict(this_play[0]) if this_play.count() > 0: @@ -1036,7 +1185,7 @@ def add_run_last_player_ab(lineup: Lineup, is_erun: bool = True): try: last_ab = Play.select().where(Play.batter == lineup).order_by(-Play.id).get() except DoesNotExist as e: - logger.error(f'Unable to apply run to Lineup {lineup}') + logger.error(f"Unable to apply run to Lineup {lineup}") else: last_ab.run = 1 last_ab.e_run = 1 if is_erun else 0 @@ -1048,26 +1197,26 @@ def get_dbready_plays(game_id: int, db_game_id: int): prep_plays = [model_to_dict(x) for x in all_plays] db.close() - obc_list = ['000', '001', '010', '100', '011', '101', '110', '111'] + obc_list = ["000", "001", "010", "100", "011", "101", "110", "111"] for x in prep_plays: - x['pitcher_id'] = x['pitcher']['player_id'] - x['batter_id'] = x['batter']['player_id'] - x['batter_team_id'] = x['batter']['team_id'] - x['pitcher_team_id'] = x['pitcher']['team_id'] - if x['catcher'] is not None: - x['catcher_id'] = x['catcher']['player_id'] - x['catcher_team_id'] = x['catcher']['team_id'] - if x['defender'] is not None: - x['defender_id'] = x['defender']['player_id'] - x['defender_team_id'] = x['defender']['team_id'] - if x['runner'] is not None: - x['runner_id'] = x['runner']['player_id'] - x['runner_team_id'] = x['runner']['team_id'] - x['game_id'] = db_game_id - x['on_base_code'] = obc_list[x['on_base_code']] + x["pitcher_id"] = x["pitcher"]["player_id"] + x["batter_id"] = x["batter"]["player_id"] + x["batter_team_id"] = x["batter"]["team_id"] + x["pitcher_team_id"] = x["pitcher"]["team_id"] + if x["catcher"] is not None: + x["catcher_id"] = x["catcher"]["player_id"] + x["catcher_team_id"] = x["catcher"]["team_id"] + if x["defender"] is not None: + x["defender_id"] = x["defender"]["player_id"] + x["defender_team_id"] = x["defender"]["team_id"] + if x["runner"] is not None: + x["runner_id"] = x["runner"]["player_id"] + x["runner_team_id"] = x["runner"]["team_id"] + x["game_id"] = db_game_id + x["on_base_code"] = obc_list[x["on_base_code"]] - logger.debug(f'all_plays:\n\n{prep_plays}\n') + logger.debug(f"all_plays:\n\n{prep_plays}\n") return prep_plays @@ -1110,13 +1259,22 @@ def convert_bullpen_to_strat(bullpen: Bullpen) -> StratBullpen: def get_or_create_bullpen(ai_team, bot): - this_pen = Bullpen.get_or_none(Bullpen.ai_team_id == ai_team['id']) + this_pen = Bullpen.get_or_none(Bullpen.ai_team_id == ai_team["id"]) if this_pen: return convert_bullpen_to_strat(this_pen) - three_days_ago = int(datetime.datetime.timestamp(datetime.datetime.now() - datetime.timedelta(days=3))) * 1000 - logger.debug(f'3da: {three_days_ago} / last_up: {this_pen.last_updated} / L > 3: ' - f'{this_pen.last_updated > three_days_ago}') + three_days_ago = ( + int( + datetime.datetime.timestamp( + datetime.datetime.now() - datetime.timedelta(days=3) + ) + ) + * 1000 + ) + logger.debug( + f"3da: {three_days_ago} / last_up: {this_pen.last_updated} / L > 3: " + f"{this_pen.last_updated > three_days_ago}" + ) if this_pen and this_pen.last_updated > three_days_ago: return convert_bullpen_to_strat(this_pen) @@ -1124,33 +1282,35 @@ def get_or_create_bullpen(ai_team, bot): this_pen.delete_instance() sheets = get_sheets(bot) - this_sheet = sheets.open_by_key(ai_team['gsheet']) - r_sheet = this_sheet.worksheet_by_title('My Rosters') + this_sheet = sheets.open_by_key(ai_team["gsheet"]) + r_sheet = this_sheet.worksheet_by_title("My Rosters") - bullpen_range = f'N30:N41' + bullpen_range = f"N30:N41" raw_cells = r_sheet.range(bullpen_range) - logger.debug(f'raw_cells: {raw_cells}') + logger.debug(f"raw_cells: {raw_cells}") bullpen = Bullpen( - ai_team_id=ai_team['id'], + ai_team_id=ai_team["id"], closer_id=raw_cells[0][0].value, setup_id=raw_cells[1][0].value, - middle_one_id=raw_cells[2][0].value if raw_cells[2][0].value != '' else None, - middle_two_id=raw_cells[3][0].value if raw_cells[3][0].value != '' else None, - middle_three_id=raw_cells[4][0].value if raw_cells[4][0].value != '' else None, - long_one_id=raw_cells[5][0].value if raw_cells[5][0].value != '' else None, - long_two_id=raw_cells[6][0].value if raw_cells[6][0].value != '' else None, - long_three_id=raw_cells[7][0].value if raw_cells[7][0].value != '' else None, - long_four_id=raw_cells[8][0].value if raw_cells[8][0].value != '' else None, - last_updated=int(datetime.datetime.timestamp(datetime.datetime.now())*1000) + middle_one_id=raw_cells[2][0].value if raw_cells[2][0].value != "" else None, + middle_two_id=raw_cells[3][0].value if raw_cells[3][0].value != "" else None, + middle_three_id=raw_cells[4][0].value if raw_cells[4][0].value != "" else None, + long_one_id=raw_cells[5][0].value if raw_cells[5][0].value != "" else None, + long_two_id=raw_cells[6][0].value if raw_cells[6][0].value != "" else None, + long_three_id=raw_cells[7][0].value if raw_cells[7][0].value != "" else None, + long_four_id=raw_cells[8][0].value if raw_cells[8][0].value != "" else None, + last_updated=int(datetime.datetime.timestamp(datetime.datetime.now()) * 1000), ) bullpen.save() - logger.debug(f'bullpen: {bullpen}') + logger.debug(f"bullpen: {bullpen}") return convert_bullpen_to_strat(bullpen) -def advance_runners(play_id: int, num_bases: int, is_error: bool = False, only_forced: bool = False): +def advance_runners( + play_id: int, num_bases: int, is_error: bool = False, only_forced: bool = False +): """ Advances runners and tallies RBIs """ @@ -1272,13 +1432,21 @@ def complete_play(play_id, batter_to_base: int = None): this_play.complete = True this_play.save() - logger.debug(f'starting the inning calc') + logger.debug(f"starting the inning calc") new_inning_half = this_play.inning_half new_inning_num = this_play.inning_num - if this_play.runner or this_play.wild_pitch or this_play.passed_ball or this_play.pick_off or this_play.balk: + if ( + this_play.runner + or this_play.wild_pitch + or this_play.passed_ball + or this_play.pick_off + or this_play.balk + ): new_batting_order = this_play.batting_order else: - new_batting_order = this_play.batting_order + 1 if this_play.batting_order < 9 else 1 + new_batting_order = ( + this_play.batting_order + 1 if this_play.batting_order < 9 else 1 + ) new_bteam_id = this_play.batter.team_id new_pteam_id = this_play.pitcher.team_id new_starting_outs = this_play.starting_outs + this_play.outs @@ -1286,16 +1454,17 @@ def complete_play(play_id, batter_to_base: int = None): new_on_second = None new_on_third = None # score_increment = this_play.homerun - # patch to handle little league home runs TODO: standardize on just _on_final for these - logger.debug(f'complete_play - this_play: {this_play}') - if this_play.batter_final == 4 or batter_to_base == 4: + if batter_to_base is not None: + this_play.batter_final = batter_to_base + logger.debug(f"complete_play - this_play: {this_play}") + if this_play.batter_final == 4: this_play.run = 1 score_increment = 1 if not this_play.error: this_play.e_run = 1 else: score_increment = 0 - logger.debug(f'complete_play - score_increment: {score_increment}') + logger.debug(f"complete_play - score_increment: {score_increment}") if this_play.on_first_final == 99: this_play.on_first_final = None @@ -1324,33 +1493,40 @@ def complete_play(play_id, batter_to_base: int = None): if this_play.starting_outs + this_play.outs > 2: new_starting_outs = 0 new_obc = 0 - if this_play.inning_half == 'Top': - new_inning_half = 'Bot' + if this_play.inning_half == "Top": + new_inning_half = "Bot" new_bteam_id = this_play.game.home_team_id new_pteam_id = this_play.game.away_team_id else: - new_inning_half = 'Top' + new_inning_half = "Top" new_inning_num += 1 new_bteam_id = this_play.game.away_team_id new_pteam_id = this_play.game.home_team_id if new_inning_num > 1: - last_inning_play = get_last_inning_end_play(this_play.game.id, new_inning_half, new_inning_num - 1) + last_inning_play = get_last_inning_end_play( + this_play.game.id, new_inning_half, new_inning_num - 1 + ) if last_inning_play.runner or last_inning_play.pick_off: new_batting_order = last_inning_play.batting_order else: - new_batting_order = last_inning_play.batting_order + 1 if last_inning_play.batting_order < 9 else 1 + new_batting_order = ( + last_inning_play.batting_order + 1 + if last_inning_play.batting_order < 9 + else 1 + ) else: new_batting_order = 1 # Not an inning-ending play else: - logger.debug(f'starting the obc calc') + logger.debug(f"starting the obc calc") bases_occ = [False, False, False, False] # Set the occupied bases for the next play and lineup member occupying it for runner, base in [ - (this_play.on_first, this_play.on_first_final), (this_play.on_second, this_play.on_second_final), - (this_play.on_third, this_play.on_third_final) + (this_play.on_first, this_play.on_first_final), + (this_play.on_second, this_play.on_second_final), + (this_play.on_third, this_play.on_third_final), ]: if base: bases_occ[base - 1] = True @@ -1399,7 +1575,7 @@ def complete_play(play_id, batter_to_base: int = None): else: new_obc = 0 - if this_play.inning_half == 'Top': + if this_play.inning_half == "Top": new_away_score = this_play.away_score + score_increment new_home_score = this_play.home_score else: @@ -1408,22 +1584,28 @@ def complete_play(play_id, batter_to_base: int = None): # A team score if score_increment: - logger.debug(f'complete_play: \n\nscore_increment: {score_increment}\n\nnew home score: {new_home_score}\n\n' - f'new_away_score: {new_away_score}\n\nthis_play.away_score: {this_play.away_score}\n\n' - f'this_player.home_score: {this_play.home_score}') + logger.debug( + f"complete_play: \n\nscore_increment: {score_increment}\n\nnew home score: {new_home_score}\n\n" + f"new_away_score: {new_away_score}\n\nthis_play.away_score: {this_play.away_score}\n\n" + f"this_player.home_score: {this_play.home_score}" + ) # Game is now tied if new_home_score == new_away_score: - logger.debug(f'\n\nGame {this_play.game} is now tied\n\n') + logger.debug(f"\n\nGame {this_play.game} is now tied\n\n") this_play.is_tied = 1 # One team took the lead - elif (this_play.away_score <= this_play.home_score) and (new_away_score > new_home_score): - logger.debug(f'\n\nTeam {this_play.batter.team_id} took the lead\n\n') + elif (this_play.away_score <= this_play.home_score) and ( + new_away_score > new_home_score + ): + logger.debug(f"\n\nTeam {this_play.batter.team_id} took the lead\n\n") this_play.is_go_ahead = 1 this_play.save() - elif (this_play.home_score <= this_play.away_score) and (new_home_score > new_away_score): - logger.debug(f'\n\nteam {this_play.batter.team_id} took the lead\n\n') + elif (this_play.home_score <= this_play.away_score) and ( + new_home_score > new_away_score + ): + logger.debug(f"\n\nteam {this_play.batter.team_id} took the lead\n\n") this_play.is_go_ahead = 1 this_play.save() @@ -1436,37 +1618,45 @@ def complete_play(play_id, batter_to_base: int = None): 3: [1.340, 0.874, 0.287], 5: [1.687, 1.042, 0.406], 6: [1.973, 1.311, 0.448], - 7: [2.295, 1.440, 0.618] + 7: [2.295, 1.440, 0.618], } start_re24 = re_data[this_play.on_base_code][this_play.starting_outs] - end_re24 = 0 if this_play.starting_outs + this_play.outs == 3 else re_data[new_obc][new_starting_outs] + end_re24 = ( + 0 + if this_play.starting_outs + this_play.outs == 3 + else re_data[new_obc][new_starting_outs] + ) this_play.re24 = end_re24 - start_re24 + score_increment this_play.save() - batter = get_one_lineup(this_play.game.id, team_id=new_bteam_id, batting_order=new_batting_order) + batter = get_one_lineup( + this_play.game.id, team_id=new_bteam_id, batting_order=new_batting_order + ) batter_id = batter.id if batter else None - pitcher = get_one_lineup(this_play.game_id, team_id=new_pteam_id, position='P') + pitcher = get_one_lineup(this_play.game_id, team_id=new_pteam_id, position="P") pitcher_id = pitcher.id if pitcher else None - logger.debug(f'done the obc calc') - next_play = Play.create(**{ - 'game_id': this_play.game.id, - 'play_num': this_play.play_num + 1, - 'batter_id': batter_id, - 'pitcher_id': pitcher_id, - 'on_base_code': new_obc, - 'inning_half': new_inning_half, - 'inning_num': new_inning_num, - 'next_inning_num': new_inning_num, - 'batting_order': new_batting_order, - 'starting_outs': new_starting_outs, - 'away_score': new_away_score, - 'home_score': new_home_score, - 'on_first': new_on_first, - 'on_second': new_on_second, - 'on_third': new_on_third, - 'is_new_inning': 1 if new_inning_half != this_play.inning_half else 0 - }) + logger.debug(f"done the obc calc") + next_play = Play.create( + **{ + "game_id": this_play.game.id, + "play_num": this_play.play_num + 1, + "batter_id": batter_id, + "pitcher_id": pitcher_id, + "on_base_code": new_obc, + "inning_half": new_inning_half, + "inning_num": new_inning_num, + "next_inning_num": new_inning_num, + "batting_order": new_batting_order, + "starting_outs": new_starting_outs, + "away_score": new_away_score, + "home_score": new_home_score, + "on_first": new_on_first, + "on_second": new_on_second, + "on_third": new_on_third, + "is_new_inning": 1 if new_inning_half != this_play.inning_half else 0, + } + ) # return_play = model_to_dict(next_play) return_play = convert_stratplay(next_play) db.close() @@ -1474,55 +1664,67 @@ def complete_play(play_id, batter_to_base: int = None): def get_batting_stats(game_id, lineup_id: int = None, team_id: int = None): - batting_stats = Play.select( - Play.batter, - fn.SUM(Play.pa).over(partition_by=[Play.batter_id]).alias('pl_pa'), - fn.SUM(Play.ab).over(partition_by=[Play.batter_id]).alias('pl_ab'), - fn.SUM(Play.hit).over(partition_by=[Play.batter_id]).alias('pl_hit'), - fn.SUM(Play.rbi).over(partition_by=[Play.batter_id]).alias('pl_rbi'), - # fn.COUNT(Play.on_first_final).filter( - # Play.on_first_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_first'), - # fn.COUNT(Play.on_second_final).filter( - # Play.on_second_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_second'), - # fn.COUNT(Play.on_third_final).filter( - # Play.on_third_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_third'), - # fn.COUNT(Play.batter_final).filter( - # Play.batter_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_batter'), - fn.SUM(Play.double).over(partition_by=[Play.batter_id]).alias('pl_double'), - fn.SUM(Play.triple).over(partition_by=[Play.batter_id]).alias('pl_triple'), - fn.SUM(Play.homerun).over(partition_by=[Play.batter_id]).alias('pl_homerun'), - fn.SUM(Play.bb).over(partition_by=[Play.batter_id]).alias('pl_bb'), - fn.SUM(Play.so).over(partition_by=[Play.batter_id]).alias('pl_so'), - fn.SUM(Play.hbp).over(partition_by=[Play.batter_id]).alias('pl_hbp'), - fn.SUM(Play.sac).over(partition_by=[Play.batter_id]).alias('pl_sac'), - fn.SUM(Play.ibb).over(partition_by=[Play.batter_id]).alias('pl_ibb'), - fn.SUM(Play.gidp).over(partition_by=[Play.batter_id]).alias('pl_gidp'), - fn.SUM(Play.sb).over(partition_by=[Play.runner_id]).alias('pl_sb'), - fn.SUM(Play.cs).over(partition_by=[Play.runner_id]).alias('pl_cs'), - fn.SUM(Play.bphr).over(partition_by=[Play.batter_id]).alias('pl_bphr'), - fn.SUM(Play.bpfo).over(partition_by=[Play.batter_id]).alias('pl_bpfo'), - fn.SUM(Play.bp1b).over(partition_by=[Play.batter_id]).alias('pl_bp1b'), - fn.SUM(Play.bplo).over(partition_by=[Play.batter_id]).alias('pl_bplo'), - fn.SUM(Play.pa).over(partition_by=[Play.batter.team_id]).alias('tm_pa'), - fn.SUM(Play.ab).over(partition_by=[Play.batter.team_id]).alias('tm_ab'), - fn.SUM(Play.hit).over(partition_by=[Play.batter.team_id]).alias('tm_hit'), - fn.SUM(Play.rbi).over(partition_by=[Play.batter.team_id]).alias('tm_rbi'), - fn.SUM(Play.double).over(partition_by=[Play.batter.team_id]).alias('tm_double'), - fn.SUM(Play.triple).over(partition_by=[Play.batter.team_id]).alias('tm_triple'), - fn.SUM(Play.homerun).over(partition_by=[Play.batter.team_id]).alias('tm_homerun'), - fn.SUM(Play.bb).over(partition_by=[Play.batter.team_id]).alias('tm_bb'), - fn.SUM(Play.so).over(partition_by=[Play.batter.team_id]).alias('tm_so'), - fn.SUM(Play.hbp).over(partition_by=[Play.batter.team_id]).alias('tm_hbp'), - fn.SUM(Play.sac).over(partition_by=[Play.batter.team_id]).alias('tm_sac'), - fn.SUM(Play.ibb).over(partition_by=[Play.batter.team_id]).alias('tm_ibb'), - fn.SUM(Play.gidp).over(partition_by=[Play.batter.team_id]).alias('tm_gidp'), - fn.SUM(Play.sb).over(partition_by=[Play.batter.team_id]).alias('tm_sb'), - fn.SUM(Play.cs).over(partition_by=[Play.batter.team_id]).alias('tm_cs'), - fn.SUM(Play.bphr).over(partition_by=[Play.batter.team_id]).alias('tm_bphr'), - fn.SUM(Play.bpfo).over(partition_by=[Play.batter.team_id]).alias('tm_bpfo'), - fn.SUM(Play.bp1b).over(partition_by=[Play.batter.team_id]).alias('tm_bp1b'), - fn.SUM(Play.bplo).over(partition_by=[Play.batter.team_id]).alias('tm_bplo'), - ).join(Lineup, on=Play.batter).where(Play.game_id == game_id) + batting_stats = ( + Play.select( + Play.batter, + fn.SUM(Play.pa).over(partition_by=[Play.batter_id]).alias("pl_pa"), + fn.SUM(Play.ab).over(partition_by=[Play.batter_id]).alias("pl_ab"), + fn.SUM(Play.hit).over(partition_by=[Play.batter_id]).alias("pl_hit"), + fn.SUM(Play.rbi).over(partition_by=[Play.batter_id]).alias("pl_rbi"), + # fn.COUNT(Play.on_first_final).filter( + # Play.on_first_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_first'), + # fn.COUNT(Play.on_second_final).filter( + # Play.on_second_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_second'), + # fn.COUNT(Play.on_third_final).filter( + # Play.on_third_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_third'), + # fn.COUNT(Play.batter_final).filter( + # Play.batter_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_batter'), + fn.SUM(Play.double).over(partition_by=[Play.batter_id]).alias("pl_double"), + fn.SUM(Play.triple).over(partition_by=[Play.batter_id]).alias("pl_triple"), + fn.SUM(Play.homerun) + .over(partition_by=[Play.batter_id]) + .alias("pl_homerun"), + fn.SUM(Play.bb).over(partition_by=[Play.batter_id]).alias("pl_bb"), + fn.SUM(Play.so).over(partition_by=[Play.batter_id]).alias("pl_so"), + fn.SUM(Play.hbp).over(partition_by=[Play.batter_id]).alias("pl_hbp"), + fn.SUM(Play.sac).over(partition_by=[Play.batter_id]).alias("pl_sac"), + fn.SUM(Play.ibb).over(partition_by=[Play.batter_id]).alias("pl_ibb"), + fn.SUM(Play.gidp).over(partition_by=[Play.batter_id]).alias("pl_gidp"), + fn.SUM(Play.sb).over(partition_by=[Play.runner_id]).alias("pl_sb"), + fn.SUM(Play.cs).over(partition_by=[Play.runner_id]).alias("pl_cs"), + fn.SUM(Play.bphr).over(partition_by=[Play.batter_id]).alias("pl_bphr"), + fn.SUM(Play.bpfo).over(partition_by=[Play.batter_id]).alias("pl_bpfo"), + fn.SUM(Play.bp1b).over(partition_by=[Play.batter_id]).alias("pl_bp1b"), + fn.SUM(Play.bplo).over(partition_by=[Play.batter_id]).alias("pl_bplo"), + fn.SUM(Play.pa).over(partition_by=[Play.batter.team_id]).alias("tm_pa"), + fn.SUM(Play.ab).over(partition_by=[Play.batter.team_id]).alias("tm_ab"), + fn.SUM(Play.hit).over(partition_by=[Play.batter.team_id]).alias("tm_hit"), + fn.SUM(Play.rbi).over(partition_by=[Play.batter.team_id]).alias("tm_rbi"), + fn.SUM(Play.double) + .over(partition_by=[Play.batter.team_id]) + .alias("tm_double"), + fn.SUM(Play.triple) + .over(partition_by=[Play.batter.team_id]) + .alias("tm_triple"), + fn.SUM(Play.homerun) + .over(partition_by=[Play.batter.team_id]) + .alias("tm_homerun"), + fn.SUM(Play.bb).over(partition_by=[Play.batter.team_id]).alias("tm_bb"), + fn.SUM(Play.so).over(partition_by=[Play.batter.team_id]).alias("tm_so"), + fn.SUM(Play.hbp).over(partition_by=[Play.batter.team_id]).alias("tm_hbp"), + fn.SUM(Play.sac).over(partition_by=[Play.batter.team_id]).alias("tm_sac"), + fn.SUM(Play.ibb).over(partition_by=[Play.batter.team_id]).alias("tm_ibb"), + fn.SUM(Play.gidp).over(partition_by=[Play.batter.team_id]).alias("tm_gidp"), + fn.SUM(Play.sb).over(partition_by=[Play.batter.team_id]).alias("tm_sb"), + fn.SUM(Play.cs).over(partition_by=[Play.batter.team_id]).alias("tm_cs"), + fn.SUM(Play.bphr).over(partition_by=[Play.batter.team_id]).alias("tm_bphr"), + fn.SUM(Play.bpfo).over(partition_by=[Play.batter.team_id]).alias("tm_bpfo"), + fn.SUM(Play.bp1b).over(partition_by=[Play.batter.team_id]).alias("tm_bp1b"), + fn.SUM(Play.bplo).over(partition_by=[Play.batter.team_id]).alias("tm_bplo"), + ) + .join(Lineup, on=Play.batter) + .where(Play.game_id == game_id) + ) if lineup_id is not None: batting_stats = batting_stats.where(Play.batter_id == lineup_id) @@ -1533,60 +1735,68 @@ def get_batting_stats(game_id, lineup_id: int = None, team_id: int = None): return_batters = [] for x in batting_stats: if x.batter.id not in done_batters: - runs_scored = Play.select(Play.pa).where( - ((Play.on_first == x.batter) & (Play.on_first_final == 4)) | - ((Play.on_second == x.batter) & (Play.on_second_final == 4)) | - ((Play.on_third == x.batter) & (Play.on_third_final == 4)) | - ((Play.batter == x.batter) & (Play.batter_final == 4)) - ).count() - stolen_bases = Play.select(Play.pa).where( - (Play.runner == x.batter) & (Play.sb == 1) - ).count() - return_batters.append({ - 'batter_id': x.batter_id, - 'card_id': x.batter.card_id, - 'team_id': x.batter.team_id, - 'pos': x.batter.position, - 'pl_run': runs_scored, - 'pl_pa': x.pl_pa, - 'pl_ab': x.pl_ab, - 'pl_hit': x.pl_hit, - 'pl_rbi': x.pl_rbi, - 'pl_double': x.pl_double, - 'pl_triple': x.pl_triple, - 'pl_homerun': x.pl_homerun, - 'pl_bb': x.pl_bb, - 'pl_so': x.pl_so, - 'pl_hbp': x.pl_hbp, - 'pl_sac': x.pl_sac, - 'pl_ibb': x.pl_ibb, - 'pl_gidp': x.pl_gidp, - 'pl_sb': stolen_bases, - 'pl_cs': x.pl_cs, - 'pl_bphr': x.pl_bphr, - 'pl_bpfo': x.pl_bpfo, - 'pl_bp1b': x.pl_bp1b, - 'pl_bplo': x.pl_bplo, - 'tm_pa': x.tm_pa, - 'tm_ab': x.tm_ab, - 'tm_hit': x.tm_hit, - 'tm_rbi': x.tm_rbi, - 'tm_double': x.tm_double, - 'tm_triple': x.tm_triple, - 'tm_homerun': x.tm_homerun, - 'tm_bb': x.tm_bb, - 'tm_so': x.tm_so, - 'tm_hbp': x.tm_hbp, - 'tm_sac': x.tm_sac, - 'tm_ibb': x.tm_ibb, - 'tm_gidp': x.tm_gidp, - 'tm_sb': x.tm_sb, - 'tm_cs': x.tm_cs, - 'tm_bphr': x.tm_bphr, - 'tm_bpfo': x.tm_bpfo, - 'tm_bp1b': x.tm_bp1b, - 'tm_bplo': x.tm_bplo, - }) + runs_scored = ( + Play.select(Play.pa) + .where( + ((Play.on_first == x.batter) & (Play.on_first_final == 4)) + | ((Play.on_second == x.batter) & (Play.on_second_final == 4)) + | ((Play.on_third == x.batter) & (Play.on_third_final == 4)) + | ((Play.batter == x.batter) & (Play.batter_final == 4)) + ) + .count() + ) + stolen_bases = ( + Play.select(Play.pa) + .where((Play.runner == x.batter) & (Play.sb == 1)) + .count() + ) + return_batters.append( + { + "batter_id": x.batter_id, + "card_id": x.batter.card_id, + "team_id": x.batter.team_id, + "pos": x.batter.position, + "pl_run": runs_scored, + "pl_pa": x.pl_pa, + "pl_ab": x.pl_ab, + "pl_hit": x.pl_hit, + "pl_rbi": x.pl_rbi, + "pl_double": x.pl_double, + "pl_triple": x.pl_triple, + "pl_homerun": x.pl_homerun, + "pl_bb": x.pl_bb, + "pl_so": x.pl_so, + "pl_hbp": x.pl_hbp, + "pl_sac": x.pl_sac, + "pl_ibb": x.pl_ibb, + "pl_gidp": x.pl_gidp, + "pl_sb": stolen_bases, + "pl_cs": x.pl_cs, + "pl_bphr": x.pl_bphr, + "pl_bpfo": x.pl_bpfo, + "pl_bp1b": x.pl_bp1b, + "pl_bplo": x.pl_bplo, + "tm_pa": x.tm_pa, + "tm_ab": x.tm_ab, + "tm_hit": x.tm_hit, + "tm_rbi": x.tm_rbi, + "tm_double": x.tm_double, + "tm_triple": x.tm_triple, + "tm_homerun": x.tm_homerun, + "tm_bb": x.tm_bb, + "tm_so": x.tm_so, + "tm_hbp": x.tm_hbp, + "tm_sac": x.tm_sac, + "tm_ibb": x.tm_ibb, + "tm_gidp": x.tm_gidp, + "tm_sb": x.tm_sb, + "tm_cs": x.tm_cs, + "tm_bphr": x.tm_bphr, + "tm_bpfo": x.tm_bpfo, + "tm_bp1b": x.tm_bp1b, + "tm_bplo": x.tm_bplo, + } + ) done_batters.append(x.batter.id) db.close() @@ -1594,14 +1804,22 @@ def get_batting_stats(game_id, lineup_id: int = None, team_id: int = None): def get_fielding_stats(game_id, lineup_id: int = None, team_id: int = None): - fielding_stats = Play.select( - Play.defender, - Play.check_pos, - fn.SUM(Play.error).over(partition_by=[Play.defender_id]).alias('pl_error'), - fn.SUM(Play.hit).over(partition_by=[Play.defender_id]).alias('pl_xhit'), - fn.COUNT(Play.defender).over(partition_by=[Play.defender_id]).alias('pl_xch'), - fn.SUM(Play.error).over(partition_by=[Play.defender.team_id]).alias('tm_error'), - ).join(Lineup, on=Play.defender).where(Play.game_id == game_id) + fielding_stats = ( + Play.select( + Play.defender, + Play.check_pos, + fn.SUM(Play.error).over(partition_by=[Play.defender_id]).alias("pl_error"), + fn.SUM(Play.hit).over(partition_by=[Play.defender_id]).alias("pl_xhit"), + fn.COUNT(Play.defender) + .over(partition_by=[Play.defender_id]) + .alias("pl_xch"), + fn.SUM(Play.error) + .over(partition_by=[Play.defender.team_id]) + .alias("tm_error"), + ) + .join(Lineup, on=Play.defender) + .where(Play.game_id == game_id) + ) if lineup_id is not None: fielding_stats = fielding_stats.where(Play.defender_id == lineup_id) @@ -1613,26 +1831,34 @@ def get_fielding_stats(game_id, lineup_id: int = None, team_id: int = None): for x in fielding_stats: if x.defender.card_id not in added_card_ids: added_card_ids.append(x.defender.card_id) - all_stats.append({ - 'defender_id': x.defender_id, - 'card_id': x.defender.card_id, - 'team_id': x.defender.team_id, - 'pos': x.check_pos, - 'pl_error': x.pl_error, - 'pl_xhit': x.pl_xhit, - 'pl_xch': x.pl_xch, - 'tm_error': x.pl_error, - 'pl_pb': 0, - 'pl_sbc': 0, - 'pl_csc': 0 - }) + all_stats.append( + { + "defender_id": x.defender_id, + "card_id": x.defender.card_id, + "team_id": x.defender.team_id, + "pos": x.check_pos, + "pl_error": x.pl_error, + "pl_xhit": x.pl_xhit, + "pl_xch": x.pl_xch, + "tm_error": x.pl_error, + "pl_pb": 0, + "pl_sbc": 0, + "pl_csc": 0, + } + ) - catching_stats = Play.select( - Play.catcher, - fn.SUM(Play.passed_ball).over(partition_by=[Play.catcher_id]).alias('pl_pb'), - fn.SUM(Play.sb).over(partition_by=[Play.catcher_id]).alias('pl_sbc'), - fn.SUM(Play.cs).over(partition_by=[Play.catcher_id]).alias('pl_csc') - ).join(Lineup, on=Play.catcher).where(Play.game_id == game_id) + catching_stats = ( + Play.select( + Play.catcher, + fn.SUM(Play.passed_ball) + .over(partition_by=[Play.catcher_id]) + .alias("pl_pb"), + fn.SUM(Play.sb).over(partition_by=[Play.catcher_id]).alias("pl_sbc"), + fn.SUM(Play.cs).over(partition_by=[Play.catcher_id]).alias("pl_csc"), + ) + .join(Lineup, on=Play.catcher) + .where(Play.game_id == game_id) + ) if lineup_id is not None: catching_stats = catching_stats.where(Play.defender_id == lineup_id) @@ -1640,24 +1866,27 @@ def get_fielding_stats(game_id, lineup_id: int = None, team_id: int = None): catching_stats = catching_stats.where(Play.defender.team_id == team_id) for x in catching_stats: - all_stats.append({ - 'defender_id': x.catcher_id, - 'card_id': x.catcher.card_id, - 'team_id': x.catcher.team_id, - 'pos': 'C', - 'pl_error': 0, - 'pl_xhit': 0, - 'pl_xch': 0, - 'tm_error': 0, - 'pl_pb': x.pl_pb, - 'pl_sbc': x.pl_sbc, - 'pl_csc': x.pl_csc - }) + all_stats.append( + { + "defender_id": x.catcher_id, + "card_id": x.catcher.card_id, + "team_id": x.catcher.team_id, + "pos": "C", + "pl_error": 0, + "pl_xhit": 0, + "pl_xch": 0, + "tm_error": 0, + "pl_pb": x.pl_pb, + "pl_sbc": x.pl_sbc, + "pl_csc": x.pl_csc, + } + ) - logger.debug(f'fielding_stats: {all_stats}') + logger.debug(f"fielding_stats: {all_stats}") db.close() return all_stats + # def new_get_batting_stats(game_id, lineup_id: int = None, team_id: int = None): # return_stats = [] # @@ -1784,54 +2013,101 @@ def get_fielding_stats(game_id, lineup_id: int = None, team_id: int = None): def get_pitching_stats( - game_id, lineup_id: int = None, team_id: int = None, in_pow: bool = None, in_innings: list = None): + game_id, + lineup_id: int = None, + team_id: int = None, + in_pow: bool = None, + in_innings: list = None, +): if in_innings is None: in_innings = [x for x in range(1, 30)] - logger.info(f'db_calls_gameplay - get_pitching_stats - in_innings: {in_innings}') - pitching_stats = Play.select( - Play.pitcher, - fn.SUM(Play.outs).over(partition_by=[Play.pitcher_id]).alias('pl_outs'), - fn.SUM(Play.hit).over(partition_by=[Play.pitcher_id]).alias('pl_hit'), - fn.COUNT(Play.on_first_final).filter( - Play.on_first_final == 4).over(partition_by=[Play.pitcher_id]).alias('pl_run_first'), - fn.COUNT(Play.on_second_final).filter( - Play.on_second_final == 4).over(partition_by=[Play.pitcher_id]).alias('pl_run_second'), - fn.COUNT(Play.on_third_final).filter( - Play.on_third_final == 4).over(partition_by=[Play.pitcher_id]).alias('pl_run_third'), - fn.COUNT(Play.batter_final).filter( - Play.batter_final == 4).over(partition_by=[Play.pitcher_id]).alias('pl_run_batter'), - fn.COUNT(Play.on_first_final).filter( - (Play.on_first_final == 4) & (Play.inning_num << in_innings)).over(partition_by=[Play.pitcher_id]).alias('pl_in_run_first'), - fn.COUNT(Play.on_second_final).filter( - (Play.on_second_final == 4) & (Play.inning_num << in_innings)).over(partition_by=[Play.pitcher_id]).alias('pl_in_run_second'), - fn.COUNT(Play.on_third_final).filter( - (Play.on_third_final == 4) & (Play.inning_num << in_innings)).over(partition_by=[Play.pitcher_id]).alias('pl_in_run_third'), - fn.COUNT(Play.batter_final).filter( - (Play.batter_final == 4) & (Play.inning_num << in_innings)).over(partition_by=[Play.pitcher_id]).alias('pl_in_run_batter'), - fn.SUM(Play.so).over(partition_by=[Play.pitcher_id]).alias('pl_so'), - fn.SUM(Play.bb).over(partition_by=[Play.pitcher_id]).alias('pl_bb'), - fn.SUM(Play.hbp).over(partition_by=[Play.pitcher_id]).alias('pl_hbp'), - fn.SUM(Play.wild_pitch).over(partition_by=[Play.pitcher_id]).alias('pl_wild_pitch'), - fn.SUM(Play.balk).over(partition_by=[Play.pitcher_id]).alias('pl_balk'), - fn.SUM(Play.homerun).over(partition_by=[Play.pitcher_id]).alias('pl_homerun'), - fn.SUM(Play.outs).over(partition_by=[Play.pitcher.team_id]).alias('tm_outs'), - fn.SUM(Play.hit).over(partition_by=[Play.pitcher.team_id]).alias('tm_hit'), - fn.COUNT(Play.on_first_final).filter( - Play.on_first_final == 4).over(partition_by=[Play.pitcher.team_id]).alias('tm_run_first'), - fn.COUNT(Play.on_second_final).filter( - Play.on_second_final == 4).over(partition_by=[Play.pitcher.team_id]).alias('tm_run_second'), - fn.COUNT(Play.on_third_final).filter( - Play.on_third_final == 4).over(partition_by=[Play.pitcher.team_id]).alias('tm_run_third'), - fn.COUNT(Play.batter_final).filter( - Play.batter_final == 4).over(partition_by=[Play.pitcher.team_id]).alias('tm_run_batter'), - fn.SUM(Play.so).over(partition_by=[Play.pitcher.team_id]).alias('tm_so'), - fn.SUM(Play.bb).over(partition_by=[Play.pitcher.team_id]).alias('tm_bb'), - fn.SUM(Play.hbp).over(partition_by=[Play.pitcher.team_id]).alias('tm_hbp'), - fn.SUM(Play.wild_pitch).over(partition_by=[Play.pitcher.team_id]).alias('tm_wild_pitch'), - fn.SUM(Play.balk).over(partition_by=[Play.pitcher.team_id]).alias('tm_balk'), - fn.SUM(Play.homerun).over(partition_by=[Play.pitcher.team_id]).alias('tm_homerun'), - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) - logger.debug(f'db_calls_gameplay - get_pitching_stats - pitching_stats: {pitching_stats}') + logger.info(f"db_calls_gameplay - get_pitching_stats - in_innings: {in_innings}") + pitching_stats = ( + Play.select( + Play.pitcher, + fn.SUM(Play.outs).over(partition_by=[Play.pitcher_id]).alias("pl_outs"), + fn.SUM(Play.hit).over(partition_by=[Play.pitcher_id]).alias("pl_hit"), + fn.COUNT(Play.on_first_final) + .filter(Play.on_first_final == 4) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_run_first"), + fn.COUNT(Play.on_second_final) + .filter(Play.on_second_final == 4) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_run_second"), + fn.COUNT(Play.on_third_final) + .filter(Play.on_third_final == 4) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_run_third"), + fn.COUNT(Play.batter_final) + .filter(Play.batter_final == 4) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_run_batter"), + fn.COUNT(Play.on_first_final) + .filter((Play.on_first_final == 4) & (Play.inning_num << in_innings)) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_in_run_first"), + fn.COUNT(Play.on_second_final) + .filter((Play.on_second_final == 4) & (Play.inning_num << in_innings)) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_in_run_second"), + fn.COUNT(Play.on_third_final) + .filter((Play.on_third_final == 4) & (Play.inning_num << in_innings)) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_in_run_third"), + fn.COUNT(Play.batter_final) + .filter((Play.batter_final == 4) & (Play.inning_num << in_innings)) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_in_run_batter"), + fn.SUM(Play.so).over(partition_by=[Play.pitcher_id]).alias("pl_so"), + fn.SUM(Play.bb).over(partition_by=[Play.pitcher_id]).alias("pl_bb"), + fn.SUM(Play.hbp).over(partition_by=[Play.pitcher_id]).alias("pl_hbp"), + fn.SUM(Play.wild_pitch) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_wild_pitch"), + fn.SUM(Play.balk).over(partition_by=[Play.pitcher_id]).alias("pl_balk"), + fn.SUM(Play.homerun) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_homerun"), + fn.SUM(Play.outs) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_outs"), + fn.SUM(Play.hit).over(partition_by=[Play.pitcher.team_id]).alias("tm_hit"), + fn.COUNT(Play.on_first_final) + .filter(Play.on_first_final == 4) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_run_first"), + fn.COUNT(Play.on_second_final) + .filter(Play.on_second_final == 4) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_run_second"), + fn.COUNT(Play.on_third_final) + .filter(Play.on_third_final == 4) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_run_third"), + fn.COUNT(Play.batter_final) + .filter(Play.batter_final == 4) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_run_batter"), + fn.SUM(Play.so).over(partition_by=[Play.pitcher.team_id]).alias("tm_so"), + fn.SUM(Play.bb).over(partition_by=[Play.pitcher.team_id]).alias("tm_bb"), + fn.SUM(Play.hbp).over(partition_by=[Play.pitcher.team_id]).alias("tm_hbp"), + fn.SUM(Play.wild_pitch) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_wild_pitch"), + fn.SUM(Play.balk) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_balk"), + fn.SUM(Play.homerun) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_homerun"), + ) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) + logger.debug( + f"db_calls_gameplay - get_pitching_stats - pitching_stats: {pitching_stats}" + ) # This is counging plays with multiple runs scored on 1 ER and the rest unearned # earned_runs_pl = Play.select().where( @@ -1840,18 +2116,30 @@ def get_pitching_stats( # ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) # logger.info(f'earned_runs: {earned_runs_pl}') - er_first = Play.select().where( - (Play.on_first_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) - er_second = Play.select().where( - (Play.on_second_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) - er_third = Play.select().where( - (Play.on_third_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) - er_batter = Play.select().where( - (Play.batter_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + er_first = ( + Play.select() + .where((Play.on_first_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + ) + er_second = ( + Play.select() + .where((Play.on_second_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + ) + er_third = ( + Play.select() + .where((Play.on_third_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + ) + er_batter = ( + Play.select() + .where((Play.batter_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + ) # earned_runs_tm = Play.select().where( # ((Play.on_first_final == 4) | (Play.on_second_final == 4) | (Play.on_third_final == 4) | @@ -1871,18 +2159,30 @@ def get_pitching_stats( tm_earned_runs = None if team_id is not None: - tm_er_first = Play.select().where( - (Play.on_first_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) - tm_er_second = Play.select().where( - (Play.on_second_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) - tm_er_third = Play.select().where( - (Play.on_third_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) - tm_er_batter = Play.select().where( - (Play.batter_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) + tm_er_first = ( + Play.select() + .where((Play.on_first_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) + tm_er_second = ( + Play.select() + .where((Play.on_second_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) + tm_er_third = ( + Play.select() + .where((Play.on_third_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) + tm_er_batter = ( + Play.select() + .where((Play.batter_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) # er_first = er_first.where(Play.pitcher.team_id == team_id) # er_second = er_second.where(Play.pitcher.team_id == team_id) @@ -1896,45 +2196,63 @@ def get_pitching_stats( tm_er_third = tm_er_third.where(Play.pitcher.team_id == team_id) tm_er_batter = tm_er_batter.where(Play.pitcher.team_id == team_id) - tm_earned_runs = tm_er_first.count() + tm_er_second.count() + tm_er_third.count() + tm_er_batter.count() + tm_earned_runs = ( + tm_er_first.count() + + tm_er_second.count() + + tm_er_third.count() + + tm_er_batter.count() + ) - pl_earned_runs = er_first.count() + er_second.count() + er_third.count() + er_batter.count() + pl_earned_runs = ( + er_first.count() + er_second.count() + er_third.count() + er_batter.count() + ) done_pitchers = [] return_pitchers = [] for x in pitching_stats: if x.pitcher.id not in done_pitchers: - return_pitchers.append({ - 'pitcher_id': x.pitcher_id, - 'card_id': x.pitcher.card_id, - 'team_id': x.pitcher.team_id, - 'pl_outs': x.pl_outs, - 'pl_hit': x.pl_hit, - 'pl_eruns': pl_earned_runs, - 'pl_runs': x.pl_run_first + x.pl_run_second + x.pl_run_third + x.pl_run_batter, - 'pl_in_runs': x.pl_in_run_first + x.pl_in_run_second + x.pl_in_run_third + x.pl_in_run_batter, - 'pl_so': x.pl_so, - 'pl_bb': x.pl_bb, - 'pl_hbp': x.pl_hbp, - 'pl_homerun': x.pl_homerun, - 'pl_wild_pitch': x.pl_wild_pitch, - 'pl_balk': x.pl_balk, - 'tm_outs': x.tm_outs, - 'tm_hit': x.tm_hit, - 'tm_eruns': tm_earned_runs, - 'tm_runs': x.tm_run_first + x.tm_run_second + x.tm_run_third + x.tm_run_batter, - 'tm_so': x.tm_so, - 'tm_bb': x.tm_bb, - 'tm_hbp': x.tm_hbp, - 'tm_homerun': x.tm_homerun, - 'tm_wild_pitch': x.tm_wild_pitch, - 'tm_balk': x.tm_balk, - 'pl_gs': 1 if x.pitcher.after_play == 0 else 0 - }) + return_pitchers.append( + { + "pitcher_id": x.pitcher_id, + "card_id": x.pitcher.card_id, + "team_id": x.pitcher.team_id, + "pl_outs": x.pl_outs, + "pl_hit": x.pl_hit, + "pl_eruns": pl_earned_runs, + "pl_runs": x.pl_run_first + + x.pl_run_second + + x.pl_run_third + + x.pl_run_batter, + "pl_in_runs": x.pl_in_run_first + + x.pl_in_run_second + + x.pl_in_run_third + + x.pl_in_run_batter, + "pl_so": x.pl_so, + "pl_bb": x.pl_bb, + "pl_hbp": x.pl_hbp, + "pl_homerun": x.pl_homerun, + "pl_wild_pitch": x.pl_wild_pitch, + "pl_balk": x.pl_balk, + "tm_outs": x.tm_outs, + "tm_hit": x.tm_hit, + "tm_eruns": tm_earned_runs, + "tm_runs": x.tm_run_first + + x.tm_run_second + + x.tm_run_third + + x.tm_run_batter, + "tm_so": x.tm_so, + "tm_bb": x.tm_bb, + "tm_hbp": x.tm_hbp, + "tm_homerun": x.tm_homerun, + "tm_wild_pitch": x.tm_wild_pitch, + "tm_balk": x.tm_balk, + "pl_gs": 1 if x.pitcher.after_play == 0 else 0, + } + ) done_pitchers.append(x.pitcher_id) db.close() - logger.debug(f'pitching stats: {return_pitchers}') + logger.debug(f"pitching stats: {return_pitchers}") return return_pitchers @@ -1946,7 +2264,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): # home_pitchers = [] # [(pitcher, first_play), (pitcher2, their_first_play)] # last_play = get_current_play(game.id) - logger.debug(f'this game: {game}') + logger.debug(f"this game: {game}") winner = None loser = None save = None @@ -1955,10 +2273,18 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): holds = [] # Get starting pitchers and update this as a pointer for the play crawl - away_pitcher = Lineup.get(Lineup.game_id == game.id, Lineup.team_id == game.away_team_id, Lineup.position == 'P') - home_pitcher = Lineup.get(Lineup.game_id == game.id, Lineup.team_id == game.home_team_id, Lineup.position == 'P') + away_pitcher = Lineup.get( + Lineup.game_id == game.id, + Lineup.team_id == game.away_team_id, + Lineup.position == "P", + ) + home_pitcher = Lineup.get( + Lineup.game_id == game.id, + Lineup.team_id == game.home_team_id, + Lineup.position == "P", + ) gs.extend([away_pitcher.card_id, home_pitcher.card_id]) - logger.debug(f'SPs: {away_pitcher} / {home_pitcher}') + logger.debug(f"SPs: {away_pitcher} / {home_pitcher}") decisions = { away_pitcher.player_id: DecisionModel( @@ -1967,7 +2293,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): week=game.week_num, pitcher_id=away_pitcher.player_id, pitcher_team_id=away_pitcher.team_id, - is_start=True + is_start=True, ), home_pitcher.player_id: DecisionModel( game_id=db_game_id, @@ -1975,13 +2301,13 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): week=game.week_num, pitcher_id=home_pitcher.player_id, pitcher_team_id=home_pitcher.team_id, - is_start=True - ) + is_start=True, + ), } # { : DecisionModel } for x in Play.select().where(Play.game_id == game.id): - logger.debug(f'checking play num {x.play_num}') - if x.inning_half == 'Top' and home_pitcher != x.pitcher: + logger.debug(f"checking play num {x.play_num}") + if x.inning_half == "Top" and home_pitcher != x.pitcher: if save == home_pitcher: if x.home_score > x.away_score: holds.append(save) @@ -1994,7 +2320,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if x.home_score > x.away_score and x.home_score - x.away_score <= 3: save = home_pitcher - elif x.inning_half == 'Bot' and away_pitcher != x.pitcher: + elif x.inning_half == "Bot" and away_pitcher != x.pitcher: if save == away_pitcher: if x.away_score > x.home_score: holds.append(save) @@ -2008,7 +2334,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): save = away_pitcher if x.is_go_ahead: - logger.debug(f'is go ahead: {x}') + logger.debug(f"is go ahead: {x}") if x.on_third_final == 4: # winning_run = x.on_third # @@ -2021,7 +2347,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if save == loser: b_save.append(save) save = None - winner = home_pitcher if x.inning_half == 'Bot' else away_pitcher + winner = home_pitcher if x.inning_half == "Bot" else away_pitcher elif x.on_second_final == 4: # winning_run = x.on_second @@ -2035,7 +2361,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if save == loser: b_save.append(save) save = None - winner = home_pitcher if x.inning_half == 'Bot' else away_pitcher + winner = home_pitcher if x.inning_half == "Bot" else away_pitcher elif x.on_first_final == 4: # winning_run = x.on_first @@ -2049,7 +2375,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if save == loser: b_save.append(save) save = None - winner = home_pitcher if x.inning_half == 'Bot' else away_pitcher + winner = home_pitcher if x.inning_half == "Bot" else away_pitcher elif x.batter_final == 4: # winning_run = x.batter @@ -2063,10 +2389,10 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if save == loser: b_save.append(save) save = None - winner = home_pitcher if x.inning_half == 'Bot' else away_pitcher + winner = home_pitcher if x.inning_half == "Bot" else away_pitcher if x.is_tied: - logger.debug(f'is tied: {x}') + logger.debug(f"is tied: {x}") winner, loser = None, None if save: b_save.append(save) @@ -2078,7 +2404,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): season=game.season, week=game.week_num, pitcher_id=home_pitcher.player_id, - pitcher_team_id=home_pitcher.team_id + pitcher_team_id=home_pitcher.team_id, ) if away_pitcher.player_id not in decisions: @@ -2087,7 +2413,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): season=game.season, week=game.week_num, pitcher_id=away_pitcher.player_id, - pitcher_team_id=away_pitcher.team_id + pitcher_team_id=away_pitcher.team_id, ) decisions[winner.player_id].win = 1 @@ -2102,17 +2428,19 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): return [x.dict() for x in decisions.values()] - logger.debug(f'\n\nWin: {winner}\nLose: {loser}\nSave: {save}\nBlown Save: {b_save}\nHolds: {holds}') + logger.debug( + f"\n\nWin: {winner}\nLose: {loser}\nSave: {save}\nBlown Save: {b_save}\nHolds: {holds}" + ) return { - 'winner': winner.card_id, - 'loser': loser.card_id, - 'save': save.card_id if save else None, - 'b_save': b_save, - 'holds': holds, - 'starters': gs, - 'w_lineup': winner, - 'l_lineup': loser, - 's_lineup': save + "winner": winner.card_id, + "loser": loser.card_id, + "save": save.card_id if save else None, + "b_save": b_save, + "holds": holds, + "starters": gs, + "w_lineup": winner, + "l_lineup": loser, + "s_lineup": save, } # for count, pit_pair in enumerate(away_pitchers): @@ -2221,11 +2549,11 @@ class StratManagerAi(pydantic.BaseModel): def check_jump(self, to_base: int, outs: int) -> Optional[str]: """Returns a string to be appended to the AI note""" - steal_base = f'attempt to steal' + steal_base = f"attempt to steal" if to_base == 2 or to_base == 3: if self.steal == 10: if to_base == 2: - return f'{steal_base} second if the runner has an ***** auto-jump or the safe range is 13+' + return f"{steal_base} second if the runner has an ***** auto-jump or the safe range is 13+" else: steal_range = 13 elif self.steal >= 8: @@ -2242,7 +2570,7 @@ class StratManagerAi(pydantic.BaseModel): elif outs == 0: steal_range -= 1 - return f'{steal_base} {"second" if to_base == 2 else "third"} if their safe range is {steal_range}+' + return f"{steal_base} {'second' if to_base == 2 else 'third'} if their safe range is {steal_range}+" else: return None @@ -2250,7 +2578,7 @@ class StratManagerAi(pydantic.BaseModel): def tag_from_second(self, outs: int) -> str: """Returns a string to be posted ahead of tag up message""" - tag_base = f'attempt to tag up if their safe range is' + tag_base = f"attempt to tag up if their safe range is" if self.running >= 8: tag_range = 5 elif self.running >= 5: @@ -2263,12 +2591,12 @@ class StratManagerAi(pydantic.BaseModel): elif outs == 0: tag_range -= 2 - return f'{tag_base} {tag_range}+' + return f"{tag_base} {tag_range}+" def tag_from_third(self, outs: int) -> str: """Returns a string to be posted with the tag up message""" - tag_base = f'attempt to tag up if their safe range is' + tag_base = f"attempt to tag up if their safe range is" if self.running >= 8: tag_range = 8 elif self.running >= 5: @@ -2281,12 +2609,12 @@ class StratManagerAi(pydantic.BaseModel): elif outs == 0: tag_range += 2 - return f'{tag_base} {tag_range}+' + return f"{tag_base} {tag_range}+" def uncapped_advance(self, to_base: int, outs: int) -> str: """Returns a string to be posted with the advancement message""" - advance_base = f'attempt to advance if their safe range is' + advance_base = f"attempt to advance if their safe range is" if to_base == 3: if self.uncapped_third >= 8: @@ -2294,7 +2622,7 @@ class StratManagerAi(pydantic.BaseModel): elif self.uncapped_third >= 5: advance_range = 18 else: - return f'not attempt to advance' + return f"not attempt to advance" if outs == 2: advance_range += 2 @@ -2312,27 +2640,26 @@ class StratManagerAi(pydantic.BaseModel): elif outs == 0: advance_range += 3 - return f'{advance_base} {advance_range}+' + return f"{advance_base} {advance_range}+" # def uncapped_advance_runner(self, this_play: StratPlay, to_base: int, runner: BattingCard, defender_pos: CardPosition, modifier: int = -1): # total_mod = modifier + defender_pos.arm # if to_base == 3: - def trail_advance(self, to_base: int, outs: int, sent_home: bool = False) -> str: """Returns a string to be posted with the advancement message""" - advance_base = f'attempt to advance if their safe range is' + advance_base = f"attempt to advance if their safe range is" if sent_home: if self.uncapped_trail >= 8: - return 'attempt to advance' + return "attempt to advance" elif self.uncapped_trail >= 5: if outs == 2: - return 'attempt to advance' + return "attempt to advance" else: advance_range = 14 else: - return 'not attempt to advance' + return "not attempt to advance" else: if self.uncapped_trail >= 8: @@ -2340,25 +2667,25 @@ class StratManagerAi(pydantic.BaseModel): else: advance_range = 16 - return f'{advance_base} {advance_range}+' + return f"{advance_base} {advance_range}+" def throw_lead_runner(self, to_base: int, outs: int) -> str: """Returns a string to be posted with the throw message""" - return 'throw for the lead runner' + return "throw for the lead runner" def throw_which_runner(self, to_base: int, outs: int) -> str: """Returns a string to be posted with the throw message""" if to_base == 4: - return 'throw for the lead runner' + return "throw for the lead runner" else: - return 'throw for the lead runner if their safe range is 14-' + return "throw for the lead runner if their safe range is 14-" def gb_decide_advance(self, starting_outs: int, run_lead: int): """Returns a string to be posted with the advancement message""" - advance_base = f'attempt to advance if their safe range is' + advance_base = f"attempt to advance if their safe range is" if self.running >= 8: advance_range = 10 elif self.running >= 5: @@ -2374,12 +2701,12 @@ class StratManagerAi(pydantic.BaseModel): elif run_lead < 0: advance_range += 3 - return f'{advance_base} {min(advance_range, 20)}+' + return f"{advance_base} {min(advance_range, 20)}+" def gb_decide_throw(self, starting_outs: int, run_lead: int): """Returns a string to be posted with the advancement message""" - throw_base = f'throw for the lead runner if their safe range is' + throw_base = f"throw for the lead runner if their safe range is" if self.decide_throw >= 8: throw_range = 13 elif self.decide_throw >= 5: @@ -2395,50 +2722,78 @@ class StratManagerAi(pydantic.BaseModel): elif run_lead < 0: throw_range += 3 - return f'{throw_base} {max(throw_range, 0)}-' + return f"{throw_base} {max(throw_range, 0)}-" def go_to_reliever( - self, this_play, tot_allowed: int, is_starter: bool = False) -> bool: + self, this_play, tot_allowed: int, is_starter: bool = False + ) -> bool: run_lead = this_play.ai_run_diff() obc = this_play.on_base_code - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: ' - f'outs: {this_play.starting_outs}, obc: {obc}, run_lead: {run_lead}, ' - f'tot_allowed: {tot_allowed}') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: " + f"outs: {this_play.starting_outs}, obc: {obc}, run_lead: {run_lead}, " + f"tot_allowed: {tot_allowed}" + ) lead_target = run_lead if is_starter else 3 # AI up big if tot_allowed < 5 and is_starter: - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 1') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 1" + ) return False elif run_lead > 5 or (run_lead > 2 and self.ahead_aggression > 5): - if tot_allowed <= lead_target or obc <= 3 or (this_play.starting_outs == 2 and not is_starter): - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 2') + if ( + tot_allowed <= lead_target + or obc <= 3 + or (this_play.starting_outs == 2 and not is_starter) + ): + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 2" + ) return False elif run_lead > 2 or (run_lead >= 0 and self.ahead_aggression > 5): - if tot_allowed < lead_target or obc <= 1 or (this_play.starting_outs == 2 and not is_starter): - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 3') + if ( + tot_allowed < lead_target + or obc <= 1 + or (this_play.starting_outs == 2 and not is_starter) + ): + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 3" + ) return False elif run_lead >= 0 or (run_lead >= -2 and self.behind_aggression > 5): - if tot_allowed < 5 or obc <= run_lead or (this_play.starting_outs == 2 and not is_starter): - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 4') + if ( + tot_allowed < 5 + or obc <= run_lead + or (this_play.starting_outs == 2 and not is_starter) + ): + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 4" + ) return False elif run_lead >= -3 and self.behind_aggression > 5: if tot_allowed < 5 and obc <= 1: - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 5') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 5" + ) return False elif run_lead <= -5: if is_starter and this_play.inning_num <= 3: - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 6') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 6" + ) return False if this_play.starting_outs != 0: - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 7') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 7" + ) return False return True - def convert_strat_manager(manager: ManagerAi) -> StratManagerAi: manager_dict = model_to_dict(manager) return StratManagerAi(**manager_dict) @@ -2450,21 +2805,20 @@ def get_manager(game) -> Optional[StratManagerAi]: # manager_ai_id = game.home_team_id if game.ai_team == 'home' else game.away_team_id # manager_ai_id = 1 - team_id = game.home_team_id if game.ai_team == 'home' else game.away_team_id + team_id = game.home_team_id if game.ai_team == "home" else game.away_team_id manager_ai_id = ((datetime.datetime.now().day * team_id) % 3) + 1 if manager_ai_id > 3 or manager_ai_id < 1: manager_ai_id = 1 - logger.debug(f'manager id: {manager_ai_id} for game {game}') + logger.debug(f"manager id: {manager_ai_id} for game {game}") try: this_manager = ManagerAi.get_by_id(manager_ai_id) except Exception as e: - e_message = f'Could not find manager id {manager_ai_id}' - logger.error(f'{e_message}: {type(e)}: {e}') - raise KeyError(f'Could not find this AI manager\'s playbook') + e_message = f"Could not find manager id {manager_ai_id}" + logger.error(f"{e_message}: {type(e)}: {e}") + raise KeyError(f"Could not find this AI manager's playbook") return convert_strat_manager(this_manager) db.close() -