From f5bf7df1662d6715f6f5903f4229fa20b4d3cef6 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Wed, 3 May 2023 13:28:14 -0500 Subject: [PATCH] DB calls to async --- ai_manager.py | 35 +++++---- cogs/admins.py | 41 +++++----- cogs/economy.py | 179 ++++++++++++++++++++++--------------------- cogs/gameplay.py | 133 +++++++++++++++++--------------- cogs/players.py | 70 ++++++++--------- db_calls.py | 18 ++--- db_calls_gameplay.py | 16 ++-- gauntlets.py | 75 +++++++++--------- helpers.py | 119 ++++++++++++++-------------- 9 files changed, 355 insertions(+), 331 deletions(-) diff --git a/ai_manager.py b/ai_manager.py index 1e5d22b..cd5c153 100644 --- a/ai_manager.py +++ b/ai_manager.py @@ -90,18 +90,17 @@ def batter_grading(vs_hand, rg_data): } -def get_or_create_card(player: dict, team: dict) -> int: +async def get_or_create_card(player: dict, team: dict) -> int: # get player card; create one if none found z = 0 card_id = None while z < 2 and card_id is None: z += 1 - c_query = db_get('cards', - params=[('team_id', team['id']), ('player_id', player['player_id'])]) + c_query = await db_get('cards', params=[('team_id', team['id']), ('player_id', player['player_id'])]) if c_query['count'] > 0: card_id = c_query['cards'][0]['id'] else: - db_post( + await db_post( 'cards', payload={'cards': [ {'player_id': player['player_id'], 'team_id': team['id'], 'pack_id': 1} @@ -115,7 +114,7 @@ def get_or_create_card(player: dict, team: dict) -> int: # First attempt - pulls ratings guide info -def build_lineup_graded(team_object: dict, vs_hand: str, league_name: str, num_innings: int, batter_rg): +async def build_lineup_graded(team_object: dict, vs_hand: str, league_name: str, num_innings: int, batter_rg): in_lineup = [] # player ids for quick checking players = { @@ -132,11 +131,12 @@ def build_lineup_graded(team_object: dict, vs_hand: str, league_name: str, num_i # Get all eligible players try: - all_players = db_get( + p_query = await db_get( endpoint='players', params=[('mlbclub', team_object['lname']), ('pos_exclude', 'RP'), ('inc_dex', False)], timeout=10 - )['players'] + ) + all_players = p_query['players'] except ConnectionError as e: raise ConnectionError(f'Error pulling players for the {team_object["lname"]}. Cal help plz.') @@ -212,7 +212,7 @@ def build_lineup_graded(team_object: dict, vs_hand: str, league_name: str, num_i return batting_order -def build_lineup(team_object: dict, game_id: int, league_name: str, vs_hand: str = 'r') -> list: +async def build_lineup(team_object: dict, game_id: int, league_name: str, vs_hand: str = 'r') -> list: players = { 'C': None, '1B': None, @@ -244,7 +244,7 @@ def build_lineup(team_object: dict, game_id: int, league_name: str, vs_hand: str ('pos_include', 'RF'), ('pos_include', 'DH'), ('inc_dex', False), ('sort_by', 'cost-desc') ] params.extend(set_params) - all_players = db_get( + all_players = await db_get( endpoint='players', params=params, timeout=10 @@ -308,7 +308,7 @@ def build_lineup(team_object: dict, game_id: int, league_name: str, vs_hand: str i = 1 for x in [grp_1, grp_2, grp_3]: for y in x: - card_id = get_or_create_card(y[1], team_object) + card_id = await get_or_create_card(y[1], team_object) lineups.append({ 'game_id': game_id, @@ -326,7 +326,7 @@ def build_lineup(team_object: dict, game_id: int, league_name: str, vs_hand: str return lineups -def get_starting_pitcher(team_object: dict, game_id: int, is_home: bool, league_name: str = None) -> dict: +async def get_starting_pitcher(team_object: dict, game_id: int, is_home: bool, league_name: str = None) -> dict: set_params = [('cardset_id_exclude', 2)] if league_name == 'minor-league': set_params = MINOR_CARDSET_PARAMS @@ -348,7 +348,7 @@ def get_starting_pitcher(team_object: dict, game_id: int, is_home: bool, league_ logging.info(f'counter: {counter} / params: {params}') try: params.extend(set_params) - pitchers = db_get( + pitchers = await db_get( endpoint='players', params=params, timeout=10 @@ -402,7 +402,7 @@ def get_starting_pitcher(team_object: dict, game_id: int, is_home: bool, league_ starter = pitchers['players'][0] # get player card; create one if none found - card_id = get_or_create_card(starter, team_object) + card_id = await get_or_create_card(starter, team_object) return { 'game_id': game_id, @@ -415,8 +415,9 @@ def get_starting_pitcher(team_object: dict, game_id: int, is_home: bool, league_ } -def get_relief_pitcher(this_play: StratPlay, ai_team: dict, used_pitchers: list, league_name: str = None) -> dict: - used_codes = [db_get('cards', object_id=x.card_id)["player"]["strat_code"] for x in used_pitchers] +async def get_relief_pitcher(this_play: StratPlay, ai_team: dict, used_pitchers: list, league_name: str = None) -> dict: + c_query = await db_get('cards', object_id=x.card_id) + used_codes = [c_query["player"]["strat_code"] for x in used_pitchers] logging.info(f'get_rp - used_pitchers: {used_codes}') reliever = None @@ -465,7 +466,7 @@ def get_relief_pitcher(this_play: StratPlay, ai_team: dict, used_pitchers: list, params.append(('pos_exclude', 'SP')) try: - pitchers = db_get( + pitchers = await db_get( endpoint='players', params=params, timeout=10 @@ -482,7 +483,7 @@ def get_relief_pitcher(this_play: StratPlay, ai_team: dict, used_pitchers: list, for count, guy in enumerate(pitchers['players']): if count >= start and guy['strat_code'] not in used_codes: - card_id = get_or_create_card(guy, ai_team) + card_id = await get_or_create_card(guy, ai_team) return { 'game_id': this_play.game.id, diff --git a/cogs/admins.py b/cogs/admins.py index b3cfa0e..47cf604 100644 --- a/cogs/admins.py +++ b/cogs/admins.py @@ -37,7 +37,7 @@ class Admins(commands.Cog): async def dev_startup(self): # Check for Paper Sluggers event - e_query = db_get('events', params=[('name', 'Paper Sluggers')]) + e_query = await db_get('events', params=[('name', 'Paper Sluggers')]) if e_query is None: this_event = db_post( 'events', @@ -55,7 +55,7 @@ class Admins(commands.Cog): this_event = e_query['events'][0] # Check for Game Rewards - gr_query = db_get('gamerewards', params=[('name', 'MVP Pack')]) + gr_query = await db_get('gamerewards', params=[('name', 'MVP Pack')]) if gr_query['count'] == 0: mv_pack = db_post( 'gamerewards', @@ -67,7 +67,7 @@ class Admins(commands.Cog): else: mv_pack = gr_query['gamerewards'][0] - gr_query = db_get('gamerewards', params=[('name', 'All-Star Pack')]) + gr_query = await db_get('gamerewards', params=[('name', 'All-Star Pack')]) if gr_query['count'] == 0: as_pack = db_post( 'gamerewards', @@ -79,9 +79,9 @@ class Admins(commands.Cog): else: as_pack = gr_query['gamerewards'][0] - gr_query = db_get('gamerewards', params=[('name', 'Mario Pack')]) + gr_query = await db_get('gamerewards', params=[('name', 'Mario Pack')]) if gr_query['count'] == 0: - m_pack = db_post( + m_pack = await db_post( 'gamerewards', payload={ 'name': 'Mario Pack', @@ -92,9 +92,9 @@ class Admins(commands.Cog): m_pack = gr_query['gamerewards'][0] # Check for Gauntlet rewards - gr_query = db_get('gauntletrewards', params=[('gauntlet_id', this_event['id'])]) + gr_query = await db_get('gauntletrewards', params=[('gauntlet_id', this_event['id'])]) if gr_query['count'] == 0: - db_post( + await db_post( 'gauntletrewards', payload={ 'rewards': [ @@ -148,25 +148,26 @@ class Admins(commands.Cog): await interaction.response.send_message(random_no_gif()) return - current = db_get('current') + current = await db_get('current') await interaction.response.defer() - p_query = db_get('packtypes', params=[('name', pack_type)]) + p_query = await db_get('packtypes', params=[('name', pack_type)]) response = '' for x in team_abbrevs.split(' '): - team = db_get('teams', params=[('abbrev', x), ('season', current['season'])])['teams'][0] + t_query = await db_get('teams', params=[('abbrev', x), ('season', current['season'])]) + team = t_query['teams'][0] if team: - total_packs = give_packs(team, num_packs, pack_type=p_query['packtypes'][0]) + total_packs = await give_packs(team, num_packs, pack_type=p_query['packtypes'][0]) response += f'Just gave {num_packs} {pack_type} pack{"s" if num_packs > 1 else ""} to the ' \ f'{team["sname"]}. They now have {total_packs["count"]} ' \ f'pack{"s" if total_packs["count"] > 1 else ""}.\n' elif x.upper() == 'LEAGUE': - all_teams = db_get('teams', params=[('season', current['season'])]) + all_teams = await db_get('teams', params=[('season', current['season'])]) for y in all_teams['teams']: logging.warning(f'Giving {num_packs} pack(s) to team: {y["abbrev"]}') - give_packs(team, num_packs) + await give_packs(team, num_packs) response = f'Just gave all {all_teams["count"]} teams {num_packs} ' \ f'standard pack{"s" if num_packs > 1 else ""}!' @@ -180,8 +181,8 @@ class Admins(commands.Cog): @commands.hybrid_command(name='post-guide', help='Mod: Post the ratings guide to team sheet') @commands.is_owner() async def post_guide_command(self, ctx, gm: Member): - team = get_team_by_owner(gm.id) - db_patch('teams', object_id=team['id'], params=[('has_guide', True)]) + team = await get_team_by_owner(gm.id) + await db_patch('teams', object_id=team['id'], params=[('has_guide', True)]) post_ratings_guide(team, self.bot) @@ -190,7 +191,7 @@ class Admins(commands.Cog): @commands.hybrid_command(name='sync-sheets', help='Mod: Sync AI team sheets') @commands.is_owner() async def sync_sheets_command(self, ctx): - t_query = db_get('teams', params=[('is_ai', True)]) + t_query = await db_get('teams', params=[('is_ai', True)]) response = await ctx.send(f'Alright, I\'m getting started...') @@ -293,7 +294,7 @@ class Admins(commands.Cog): if line[4].value == 'CHANGE': try: logging.info(f'Updating {line[1].value}') - this_player = db_get('players', object_id=line[0].value) + this_player = await db_get('players', object_id=line[0].value) logging.info(f'this_player: {this_player["p_name"]}') new_player = copy.deepcopy(this_player) @@ -305,7 +306,7 @@ class Admins(commands.Cog): new_player['cost'] = new_cost(this_player, rarities[line[3].value], rarities[line[2].value]) logging.info(f'new_player cost: {new_player["cost"]}') - this_player = db_patch('players', object_id=this_player['player_id'], params=[ + this_player = await db_patch('players', object_id=this_player['player_id'], params=[ ('cost', new_player['cost']) ]) logging.info(f'patched_player: {this_player["p_name"]} / cardset: {this_player["cardset"]["id"]}') @@ -321,7 +322,7 @@ class Admins(commands.Cog): logging.error(e_message) errors.append(e_message) - db_post('players', payload={'players': new_players}) + await db_post('players', payload={'players': new_players}) await ctx.send(f'Updated {done} players!') if len(errors) > 0: e_string = "\n- ".join(errors) @@ -331,7 +332,7 @@ class Admins(commands.Cog): @commands.is_owner() async def test_choices_command(self, ctx): await ctx.send(f'Wiping AI dexes...') - db_post('paperdex/wipe-ai', timeout=15) + await db_post('paperdex/wipe-ai', timeout=15) await ctx.send(f'All done!') diff --git a/cogs/economy.py b/cogs/economy.py index 074f022..b7fa6d2 100644 --- a/cogs/economy.py +++ b/cogs/economy.py @@ -15,7 +15,7 @@ from discord.app_commands import Choice import datetime import pygsheets -from db_calls import db_get, db_post, db_patch, db_delete, get_team_by_abbrev, post_to_dex +from db_calls import db_get, db_post, db_patch, db_delete, get_team_by_abbrev from help_text import * # date = f'{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}' @@ -127,7 +127,7 @@ class Economy(commands.Cog): return # Check for notifications - all_notifs = db_get('notifs', params=[('ack', False)]) + all_notifs = await db_get('notifs', params=[('ack', False)]) if not all_notifs: logging.debug(f'No notifications') return @@ -162,7 +162,7 @@ class Economy(commands.Cog): } else: p_list[x['field_name']]['message'] += f'\n{x["message"]}' - db_patch('notifs', object_id=x['id'], params=[('ack', True)]) + await db_patch('notifs', object_id=x['id'], params=[('ack', True)]) logging.debug(f'p_list: {p_list}') for player in p_list: @@ -240,7 +240,7 @@ class Economy(commands.Cog): @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 = db_get('current') + current = await db_get('current') embed = get_team_embed(f'Paper Dynasty Help') embed.description = 'Resources & Links' embed.add_field( @@ -362,13 +362,13 @@ class Economy(commands.Cog): await ctx.send('Wait a second. You\'re not in charge here!') return - team = get_team_by_owner(gm.id) - p_query = db_get('packtypes', params=[('name', 'Premium')]) + 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') return - total_packs = give_packs(team, num_packs, pack_type=p_query['packtypes'][0]) + 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']) @@ -377,25 +377,25 @@ class Economy(commands.Cog): await ctx.send('Wait a second. You\'re not in charge here!') return - team = get_team_by_owner(gm.id) - p_query = db_get('packtypes', params=[('name', 'Standard')]) + 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') return - total_packs = give_packs(team, num_packs, pack_type=p_query['packtypes'][0]) + 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.check(legal_channel) @commands.has_any_role(PD_PLAYERS_ROLE_NAME) async def last_pack_command(self, ctx: commands.Context): - team = get_team_by_owner(ctx.author.id) + 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!') return - p_query = db_get( + p_query = await db_get( 'packs', params=[('opened', True), ('team_id', team['id']), ('new_to_old', True), ('limit', 1)] ) @@ -411,7 +411,7 @@ class Economy(commands.Cog): else: pack_cover = None - c_query = db_get( + c_query = await db_get( 'cards', params=[('pack_id', p_query['packs'][0]['id'])] ) @@ -425,7 +425,7 @@ class Economy(commands.Cog): @commands.has_any_role(PD_PLAYERS) @commands.check(legal_channel) async def daily_checkin(self, ctx: commands.Context): - team = get_team_by_owner(ctx.author.id) + 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!', @@ -433,10 +433,10 @@ class Economy(commands.Cog): ) return - current = 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 = db_get('rewards', params=[ + daily = await db_get('rewards', params=[ ('name', 'Daily Check-in'), ('team_id', team['id']), ('created_after', midnight) ]) logging.debug(f'midnight: {midnight} / now: {int_timestamp(now)}') @@ -449,12 +449,13 @@ class Economy(commands.Cog): ) return - db_post('rewards', payload={ + await db_post('rewards', payload={ 'name': 'Daily Check-in', 'team_id': team['id'], 'season': current['season'], 'week': current['week'], 'created': int_timestamp(now) }) - check_ins = db_get('rewards', params=[ - ('name', 'Daily Check-in'), ('team_id', team['id']), ('season', db_get('current')['season']) + 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 @@ -466,7 +467,7 @@ class Economy(commands.Cog): greeting = await ctx.send(f'Hey, you just earned a Standard pack of cards!') pack_channel = get_channel(ctx, 'pack-openings') - p_query = db_get('packtypes', params=[('name', 'Standard')]) + p_query = await db_get('packtypes', params=[('name', 'Standard')]) if not p_query: await ctx.send(f'I was not able to pull this pack for you. Maybe ping {get_cal_user(ctx).mention}?') return @@ -476,13 +477,13 @@ class Economy(commands.Cog): greeting = await ctx.send(f'Hey, you just earned a player card!') pack_channel = ctx.channel - p_query = db_get('packtypes', params=[('name', 'Check-In Player')]) + p_query = await db_get('packtypes', params=[('name', 'Check-In Player')]) if not p_query: await ctx.send(f'I was not able to pull this card for you. Maybe ping {get_cal_user(ctx).mention}?') return - give_packs(team, 1, p_query['packtypes'][0]) - p_query = db_get( + 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)] ) @@ -499,7 +500,7 @@ class Economy(commands.Cog): all_cards = [] for p_id in pack_ids: - new_cards = db_get('cards', params=[('pack_id', p_id)]) + new_cards = await db_get('cards', params=[('pack_id', p_id)]) all_cards.extend(new_cards['cards']) if not all_cards: @@ -526,7 +527,7 @@ class Economy(commands.Cog): else: m_reward = 25 - team = db_post(f'teams/{team["id"]}/money/{m_reward}') + team = await db_post(f'teams/{team["id"]}/money/{m_reward}') await ctx.send(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') @@ -539,14 +540,14 @@ class Economy(commands.Cog): ) return - owner_team = get_team_by_owner(interaction.user.id) + 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!' ) return - p_query = db_get('packs', params=[ + p_query = await db_get('packs', params=[ ('team_id', owner_team['id']), ('opened', False) ]) if p_query['count'] == 0: @@ -640,7 +641,7 @@ class Economy(commands.Cog): ) return - owner_team = get_team_by_owner(interaction.user.id) + 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!' @@ -654,10 +655,10 @@ class Economy(commands.Cog): all_params = [('name', proper_name)] if player_cardset: - this_cardset = cardset_search(player_cardset, player_cog.cardset_list) + this_cardset = await cardset_search(player_cardset, player_cog.cardset_list) all_params.append(('cardset_id', this_cardset['id'])) - p_query = db_get('players', params=all_params) + p_query = await db_get('players', params=all_params) if p_query['count'] == 0: await interaction.response.send_message( @@ -674,7 +675,7 @@ class Economy(commands.Cog): this_player = p_query['players'][0] logging.debug(f'this_player: {this_player}') - c_query = db_get('cards', + 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 @@ -720,7 +721,7 @@ class Economy(commands.Cog): ) return - purchase = db_get( + 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 @@ -749,14 +750,14 @@ class Economy(commands.Cog): ephemeral=True ) return - owner_team = get_team_by_owner(interaction.user.id) + 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!' ) if not pack_name: - p_query = db_get('packtypes', params=[('available', True)]) + 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 ' @@ -775,7 +776,7 @@ class Economy(commands.Cog): ) return - p_query = db_get('packtypes', params=[('name', pack_name.lower().replace('pack', '')), ('available', True)]) + p_query = await db_get('packtypes', params=[('name', pack_name.lower().replace('pack', '')), ('available', True)]) if 'count' not in p_query: await interaction.response.send_message( f'Hmm...I don\'t recognize {pack_name.title()} as a pack type. Check on that and get back to me.', @@ -854,7 +855,7 @@ class Economy(commands.Cog): if question is None: return - purchase = db_get( + purchase = await db_get( f'teams/{owner_team["id"]}/buy/pack/{pack_type["id"]}', params=[('ts', team_hash(owner_team)), ('quantity', num_packs)] ) @@ -876,7 +877,7 @@ class Economy(commands.Cog): @commands.check(legal_channel) @app_commands.describe(immediately='Skip all prompts and sell dupes immediately; default False') async def sell_dupes_command(self, interaction: discord.Interaction, immediately: bool = False): - team = get_team_by_owner(interaction.user.id) + 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!', @@ -889,7 +890,7 @@ class Economy(commands.Cog): ) try: - c_query = 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' @@ -935,7 +936,7 @@ class Economy(commands.Cog): await question.edit(content=f'The sale is going through...', view=None) # for card in dupe_cards: - sale = db_get( + sale = await db_get( f'teams/{team["id"]}/sell/cards', params=[('ts', team_hash(team)), ('ids', dupe_ids)], timeout=10 @@ -947,7 +948,7 @@ class Economy(commands.Cog): return await refresh_sheet(team, self.bot) - team = db_get('teams', object_id=team['id']) + 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') @@ -964,8 +965,8 @@ class Economy(commands.Cog): 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): - owner_team = get_team_by_owner(interaction.user.id) - current = db_get('current') + owner_team = await get_team_by_owner(interaction.user.id) + current = await db_get('current') # Check for existing team if owner_team and not os.environ.get('TESTING'): @@ -975,7 +976,7 @@ class Economy(commands.Cog): return # Check for duplicate team data - dupes = db_get('teams', params=[('abbrev', team_abbrev)]) + 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 ' @@ -985,7 +986,7 @@ class Economy(commands.Cog): return # Check for duplicate team data - dupes = db_get('teams', params=[('lname', team_full_name)]) + 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 ' @@ -1100,7 +1101,7 @@ class Economy(commands.Cog): if not match: await op_ch.send(f'Got it!') - team = db_post('teams', payload={ + team = await db_post('teams', payload={ 'abbrev': team_abbrev.upper(), 'sname': team_short_name, 'lname': team_full_name, @@ -1121,14 +1122,14 @@ class Economy(commands.Cog): await interaction.user.add_roles(t_role) anchor_players = [] - anchor_all_stars = db_get( + anchor_all_stars = await db_get( 'players/random', params=[ ('min_rarity', 3), ('max_rarity', 3), ('franchise', team_choice), ('pos_exclude', 'RP'), ('limit', 1), ('in_packs', True) ] ) - anchor_starters = db_get( + anchor_starters = await db_get( 'players/random', params=[ ('min_rarity', 2), ('max_rarity', 2), ('franchise', team_choice), ('pos_exclude', 'RP'), ('limit', 2), @@ -1140,21 +1141,21 @@ class Economy(commands.Cog): 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.') - db_delete('teams', object_id=team['id']) + 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.') - db_delete('teams', object_id=team['id']) + 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]) - this_pack = db_post('packs/one', + 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}) @@ -1186,17 +1187,17 @@ class Economy(commands.Cog): # Add anchor position coverage update_roster_counts(anchor_players) - db_post('cards', payload={'cards': [ + 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 = db_get('players/random', params=[('pos_include', 'SP'), ('max_rarity', 1), ('limit', 5)]) - five_rps = db_get('players/random', params=[('pos_include', 'RP'), ('max_rarity', 1), ('limit', 5)]) + 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]) - db_post('cards', payload={'cards': [ + 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) @@ -1208,13 +1209,13 @@ class Economy(commands.Cog): if roster_counts['Replacement'] < roster_counts['Reserve']: max_rar = 0 - r_draw = db_get( + r_draw = await db_get( 'players/random', params=[('pos_include', pos), ('max_rarity', max_rar), ('limit', 2)], none_okay=False ) team_infielders.extend(r_draw['players']) update_roster_counts(team_infielders) - db_post('cards', payload={'cards': [ + 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) @@ -1225,13 +1226,13 @@ class Economy(commands.Cog): if roster_counts['Replacement'] < roster_counts['Reserve']: max_rar = 0 - r_draw = db_get( + r_draw = await db_get( 'players/random', params=[('pos_include', pos), ('max_rarity', max_rar), ('limit', 2)], none_okay=False ) team_outfielders.extend(r_draw['players']) update_roster_counts(team_outfielders) - db_post('cards', payload={'cards': [ + 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) @@ -1291,7 +1292,7 @@ class Economy(commands.Cog): if not done_out: await op_ch.send(error_text) - give_packs(team, 1) + 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!' @@ -1303,7 +1304,7 @@ class Economy(commands.Cog): f'{get_roster_sheet({"gsheet": current["gsheet_template"]}, allow_embed=True)}' ) - new_team_embed = 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 ) @@ -1314,7 +1315,7 @@ class Economy(commands.Cog): 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 = db_get('teams', params=[('abbrev', abbrev)]) + 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 ' @@ -1324,7 +1325,7 @@ class Economy(commands.Cog): return # Check for duplicate team data - dupes = db_get('teams', params=[('lname', lname)]) + 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 ' @@ -1333,9 +1334,9 @@ class Economy(commands.Cog): ) return - current = db_get('current') + current = await db_get('current') - team = db_post('teams', payload={ + team = await db_post('teams', payload={ 'abbrev': abbrev.upper(), 'sname': sname, 'lname': lname, @@ -1350,16 +1351,16 @@ class Economy(commands.Cog): 'is_ai': True }) - p_query = db_get('players', params=[('franchise', lname)]) + p_query = await db_get('players', params=[('franchise', lname)]) - this_pack = db_post( + 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'] - db_post('cards', payload={'cards': [ + 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) @@ -1369,7 +1370,7 @@ class Economy(commands.Cog): @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 = db_get('teams', params=[('is_ai', True)]) + 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 @@ -1377,7 +1378,7 @@ class Economy(commands.Cog): total_cards = 0 total_teams = 0 for team in ai_teams['teams']: - all_players = db_get('players', params=[('franchise', team['lname'])]) + all_players = await db_get('players', params=[('franchise', team['lname'])]) new_players = [] if all_players: @@ -1391,12 +1392,12 @@ class Economy(commands.Cog): 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 = db_post( + 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} ) - db_post('cards', payload={'cards': [ + 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) @@ -1408,7 +1409,7 @@ class Economy(commands.Cog): @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): - owner_team = get_team_by_owner(ctx.author.id) + 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!') return @@ -1419,14 +1420,14 @@ class Economy(commands.Cog): await ctx.send(f'You can only update the team sheet for your own team, you goober.') return else: - team = get_team_by_abbrev(team_abbrev) + team = await get_team_by_abbrev(team_abbrev) - current = db_get('current') + 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 = 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) @@ -1447,7 +1448,7 @@ class Economy(commands.Cog): new_sheet = sheets.open_by_url(google_sheet_url) except Exception as e: logging.error(f'Error accessing {team["abbrev"]} sheet: {e}') - current = db_get('current') + 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"]}, allow_embed=True)}') @@ -1500,7 +1501,7 @@ class Economy(commands.Cog): if team['has_guide']: post_ratings_guide(team, self.bot, this_sheet=new_sheet) - team = 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' @@ -1518,7 +1519,7 @@ class Economy(commands.Cog): # await ctx.send(f'Slide on down to the {get_channel(ctx, "pd-bot-hole").mention} ;)') # return # - # team = get_team_by_owner(ctx.author.id) + # 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!' @@ -1575,13 +1576,13 @@ class Economy(commands.Cog): question = await ctx.send(f'I\'ll go put that card on their roster...') all_player_ids = player_ids.split(" ") - t_query = db_get('teams', params=[('abbrev', 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] - this_pack = db_post( + this_pack = await db_post( 'packs/one', payload={ 'team_id': team['id'], @@ -1590,7 +1591,7 @@ class Economy(commands.Cog): ) try: - 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: logging.error(f'failed to create cards: {e}') raise ConnectionError(f'Failed to distribute these cards.') @@ -1607,9 +1608,9 @@ class Economy(commands.Cog): @commands.command(name='cleartest', hidden=True) @commands.is_owner() async def clear_test_command(self, ctx): - team = get_team_by_owner(ctx.author.id) + team = await get_team_by_owner(ctx.author.id) msg = await ctx.send('Alright, let\'s go find your cards...') - all_cards = db_get( + all_cards = await db_get( 'cards', params=[('team_id', team['id'])] ) @@ -1617,22 +1618,22 @@ class Economy(commands.Cog): if all_cards: await msg.edit(content=f'I found {len(all_cards["cards"])} cards; deleting now...') for x in all_cards['cards']: - db_delete( + 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 = db_get('packs', params=[('team_id', team['id'])]) + p_query = await db_get('packs', params=[('team_id', team['id'])]) if p_query['count']: for x in p_query['packs']: - db_delete('packs', object_id=x['id']) + 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 = db_get('paperdex', params=[('team_id', team['id'])]) + p_query = await db_get('paperdex', params=[('team_id', team['id'])]) if p_query['count']: for x in p_query['paperdex']: - db_delete('paperdex', object_id=x['id']) + 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']): @@ -1641,7 +1642,7 @@ class Economy(commands.Cog): @commands.command(name='packtest', hidden=True) @commands.is_owner() async def pack_test_command(self, ctx): - team = get_team_by_owner(ctx.author.id) + 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, diff --git a/cogs/gameplay.py b/cogs/gameplay.py index 7221cf8..cae4d2d 100644 --- a/cogs/gameplay.py +++ b/cogs/gameplay.py @@ -97,7 +97,7 @@ class Gameplay(commands.Cog): f'Skipping Game {game_id} in scoreboard: {e}' ) - current = db_get('current') + current = await db_get('current') try: s_channel = self.bot.get_channel(int(os.environ.get('SCOREBOARD_CHANNEL'))) @@ -109,7 +109,7 @@ class Gameplay(commands.Cog): content=None, embed=embed ) - db_patch('current', object_id=current['id'], params=[('live_scoreboard', s_message.id)]) + await db_patch('current', object_id=current['id'], params=[('live_scoreboard', s_message.id)]) else: s_message = await s_channel.fetch_message(message_id) @@ -170,9 +170,9 @@ class Gameplay(commands.Cog): return game_string async def post_rewards(self, winning_team: dict, losing_team: dict, this_game: StratGame): - wr_query = db_get( + wr_query = await db_get( 'gamerewards', params=[('name', f'{"Short" if this_game.short_game else "Full"} Game Win')]) - lr_query = db_get( + lr_query = await db_get( 'gamerewards', params=[('name', f'{"Short" if this_game.short_game else "Full"} Game Loss')]) if not wr_query['count'] or not lr_query['count']: raise KeyError(f'Game Rewards were not found. Leaving this game active.') @@ -187,7 +187,7 @@ class Gameplay(commands.Cog): # Post Team Choice packs if this_game.ai_team is not None and not this_game.short_game and 'gauntlet' not in this_game.game_type and \ losing_team['is_ai']: - r_query = db_get( + r_query = await db_get( 'results', params=[ ('team_one_id', winning_team['id']), ('team_two_id', losing_team['id']), @@ -200,8 +200,8 @@ class Gameplay(commands.Cog): x['home_score'] > x['away_score'] and x['home_team']['id'] == human_team['id']): wins += 1 - def post_tc_pack(): - db_post( + async def post_tc_pack(): + await db_post( 'packs/one', payload={ 'team_id': human_team['id'], @@ -212,13 +212,13 @@ class Gameplay(commands.Cog): if r_query['count'] > 0: if this_game.game_type == 'minor-league' and wins % 6 == 0: - post_tc_pack() + await post_tc_pack() win_string += f'1x {losing_team["abbrev"]} Team Choice pack\n' elif this_game.game_type == 'major-league' and wins % 4 == 0: - post_tc_pack() + await post_tc_pack() win_string += f'1x {losing_team["abbrev"]} Team Choice pack\n' elif this_game.game_type == 'hall-of-fame' and wins % 2 == 0: - post_tc_pack() + await post_tc_pack() win_string += f'1x {losing_team["abbrev"]} Team Choice pack\n' win_string += f'{win_reward["money"]}₼\n' @@ -227,13 +227,15 @@ class Gameplay(commands.Cog): # Post rewards if 'gauntlet' in this_game.game_type: if 'Gauntlet' in winning_team['abbrev']: - winning_team = db_get('teams', params=[('abbrev', winning_team['abbrev'].split('-')[1])])['teams'][0] + t_query = await db_get('teams', params=[('abbrev', winning_team['abbrev'].split('-')[1])]) + winning_team = t_query['teams'][0] if 'Gauntlet' in losing_team['abbrev']: - losing_team = db_get('teams', params=[('abbrev', losing_team['abbrev'].split('-')[1])])['teams'][0] + t_query = await db_get('teams', params=[('abbrev', losing_team['abbrev'].split('-')[1])]) + losing_team = t_query['teams'][0] - give_packs(winning_team, num_packs=1, pack_type=win_reward['pack_type']) - db_post(f'teams/{winning_team["id"]}/money/{win_reward["money"]}') - db_post(f'teams/{losing_team["id"]}/money/{loss_reward["money"]}') + await give_packs(winning_team, num_packs=1, pack_type=win_reward['pack_type']) + await db_post(f'teams/{winning_team["id"]}/money/{win_reward["money"]}') + await db_post(f'teams/{losing_team["id"]}/money/{loss_reward["money"]}') data = { 'win_string': win_string, @@ -902,7 +904,7 @@ class Gameplay(commands.Cog): # @commands.command(name='tl') # @commands.is_owner() # async def test_lineup_command(self, ctx, team_abbrev: str): - # t_query = db_get('teams', params=[('abbrev', team_abbrev)]) + # t_query = await db_get('teams', params=[('abbrev', team_abbrev)]) # if t_query['count'] > 0: # team = t_query['teams'][0] # await ctx.send(f'Pulling a lineup for the {team["lname"]}...') @@ -919,7 +921,7 @@ class Gameplay(commands.Cog): # async def test_reliever_command(self, ctx, game_id: int): # this_game = get_one_game(game_id=game_id) # ai_id = this_game.away_team_id if this_game.ai_team == 'away' else this_game.home_team_id - # ai_team = db_get('teams', object_id=ai_id) + # ai_team = await db_get('teams', object_id=ai_id) # used_pitchers = await get_team_lineups( # game_id=game_id, team_id=ai_team['id'], inc_inactive=True, pitchers_only=True, as_string=False # ) @@ -999,8 +1001,8 @@ class Gameplay(commands.Cog): except Exception as e: logging.error(f'Could not check channel category: {e}') - away_team = get_team_by_abbrev(away_team_abbrev) - home_team = get_team_by_abbrev(home_team_abbrev) + away_team = await get_team_by_abbrev(away_team_abbrev) + home_team = await get_team_by_abbrev(home_team_abbrev) if not away_team: await interaction.edit_original_response( @@ -1031,7 +1033,7 @@ class Gameplay(commands.Cog): ) return - current = db_get('current') + current = await db_get('current') week_num = current['week'] # logging.debug(f'away: {away_team} / home: {home_team} / week: {week_num} / ranked: {is_ranked}') logging.debug(f'away: {away_team} / home: {home_team} / week: {week_num}') @@ -1101,7 +1103,7 @@ class Gameplay(commands.Cog): ) logging.info(f'new-game - calling lineup for {ai_team["abbrev"]}') - all_lineups = ai_manager.build_lineup(ai_team, this_game.id, league_name) + all_lineups = await ai_manager.build_lineup(ai_team, this_game.id, league_name) logging.info(f'new-game - got lineup for {ai_team["abbrev"]}') except Exception as e: @@ -1125,7 +1127,7 @@ class Gameplay(commands.Cog): patch_game(this_game.id, home_roster_num=69, ai_team='home') # starter = starting_pitcher(ai_team, self.bot, True if home_team['is_ai'] else False) - starter = ai_manager.get_starting_pitcher( + starter = await ai_manager.get_starting_pitcher( ai_team, this_game.id, True if home_team['is_ai'] else False, @@ -1133,7 +1135,7 @@ class Gameplay(commands.Cog): ) all_lineups.append(starter) - this_card = db_get(f'cards', object_id=starter['card_id']) + this_card = await db_get(f'cards', object_id=starter['card_id']) await interaction.channel.send( content=f'The {ai_team["sname"]} are starting **{this_card["player"]["description"]}**:\n\n' f'{this_card["player"]["image"]}' @@ -1183,8 +1185,8 @@ class Gameplay(commands.Cog): except Exception as e: logging.error(f'Could not check channel category: {e}') - away_team = get_team_by_abbrev(away_team_abbrev) - home_team = get_team_by_abbrev(home_team_abbrev) + away_team = await get_team_by_abbrev(away_team_abbrev) + home_team = await get_team_by_abbrev(home_team_abbrev) if not away_team: await interaction.edit_original_response( @@ -1215,7 +1217,7 @@ class Gameplay(commands.Cog): ) return - current = db_get('current') + current = await db_get('current') week_num = current['week'] logging.debug(f'away: {away_team} / home: {home_team} / week: {week_num} / ranked: True') @@ -1274,8 +1276,8 @@ class Gameplay(commands.Cog): except Exception as e: logging.error(f'Could not check channel category: {e}') - away_team = get_team_by_abbrev(away_team_abbrev) - home_team = get_team_by_abbrev(home_team_abbrev) + away_team = await get_team_by_abbrev(away_team_abbrev) + home_team = await get_team_by_abbrev(home_team_abbrev) if not away_team: await interaction.edit_original_response( @@ -1306,7 +1308,7 @@ class Gameplay(commands.Cog): ) return - current = db_get('current') + current = await db_get('current') week_num = current['week'] logging.debug(f'away: {away_team} / home: {home_team} / week: {week_num} / ranked: True') @@ -1363,10 +1365,10 @@ class Gameplay(commands.Cog): except Exception as e: logging.error(f'Could not check channel category: {e}') - current = db_get('current') + current = await db_get('current') week_num = current['week'] - e_query = db_get('events', params=[("name", event_name), ("active", True)]) + e_query = await db_get('events', params=[("name", event_name), ("active", True)]) if e_query['count'] == 0: await interaction.edit_original_response( content=f'It looks like the {event_name} has ended! Cal should really remove it from this list.' @@ -1374,8 +1376,8 @@ class Gameplay(commands.Cog): return this_event = e_query['events'][0] - main_team = get_team_by_owner(interaction.user.id) - team = get_team_by_abbrev(f'Gauntlet-{main_team["abbrev"]}') + main_team = await get_team_by_owner(interaction.user.id) + team = await get_team_by_abbrev(f'Gauntlet-{main_team["abbrev"]}') if not main_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!' @@ -1396,7 +1398,7 @@ class Gameplay(commands.Cog): return # Get Gauntlet run - r_query = db_get( + r_query = await db_get( 'gauntletruns', params=[('team_id', team['id']), ('gauntlet_id', this_event['id']), ('is_active', True)] ) @@ -1412,7 +1414,7 @@ class Gameplay(commands.Cog): # If not new or after draft, create new AI game is_home = gauntlets.is_home_team(team, this_event, this_run) - opponent = gauntlets.get_opponent(team, this_event, this_run) + opponent = await gauntlets.get_opponent(team, this_event, this_run) if opponent is None: await interaction.edit_original_response( content=f'Yike. I\'m not sure who your next opponent is. {get_cal_user(interaction)} help plz!' @@ -1444,7 +1446,7 @@ class Gameplay(commands.Cog): ) logging.info(f'new-game - calling lineup for {opponent["abbrev"]}') - all_lineups = gauntlets.build_lineup(opponent, this_game, this_event) + all_lineups = await gauntlets.build_lineup(opponent, this_game, this_event) logging.info(f'new-game-gauntlet - got lineup for {opponent["abbrev"]}') except Exception as e: @@ -1467,10 +1469,10 @@ class Gameplay(commands.Cog): else: patch_game(this_game.id, home_roster_num=69, ai_team='home') - starter = gauntlets.get_starting_pitcher(opponent, this_game, this_event, this_run) + starter = await gauntlets.get_starting_pitcher(opponent, this_game, this_event, this_run) all_lineups.append(starter) - this_card = db_get(f'cards', object_id=starter['card_id']) + this_card = await db_get(f'cards', object_id=starter['card_id']) await interaction.channel.send( content=f'The {opponent["sname"]} are starting **{this_card["player"]["description"]}**:\n\n' f'{this_card["player"]["image"]}' @@ -1565,8 +1567,8 @@ class Gameplay(commands.Cog): await question.edit(content='It stays.', view=None) return - away_team = db_get('teams', object_id=this_game.away_team_id) - home_team = db_get('teams', object_id=this_game.home_team_id) + away_team = await db_get('teams', object_id=this_game.away_team_id) + home_team = await db_get('teams', object_id=this_game.home_team_id) away_stats = { # 'p_lines': get_pitching_stats(this_game.id, team_id=away_team['id']), @@ -1673,7 +1675,7 @@ class Gameplay(commands.Cog): logging.debug(f'Time to build statlines and submit the scorecard for this PD game!') # Post result - success = db_post( + success = await db_post( 'results', payload={ 'away_team_id': this_game.away_team_id, @@ -1703,25 +1705,29 @@ class Gameplay(commands.Cog): if line['pl_double']: if len(doubles): doubles += ', ' - doubles += f'{db_get("cards", object_id=line["card_id"])["player"]["p_name"]}' \ + card = await db_get("cards", object_id=line["card_id"]) + doubles += f'{card["player"]["p_name"]}' \ f'{" " if line["pl_double"] > 1 else ""}' \ f'{line["pl_double"] if line["pl_double"] > 1 else ""}' if line['pl_triple']: if len(triples): triples += ', ' - triples += f'{db_get("cards", object_id=line["card_id"])["player"]["p_name"]}' \ + card = await db_get("cards", object_id=line["card_id"]) + triples += f'{card["player"]["p_name"]}' \ f'{" " if line["pl_triple"] > 1 else ""}' \ f'{line["pl_triple"] if line["pl_triple"] > 1 else ""}' if line['pl_homerun']: if len(homers): homers += ', ' - homers += f'{db_get("cards", object_id=line["card_id"])["player"]["p_name"]}' \ + card = await db_get("cards", object_id=line["card_id"]) + homers += f'{card["player"]["p_name"]}' \ f'{" " if line["pl_homerun"] > 1 else ""}' \ f'{line["pl_homerun"] if line["pl_homerun"] > 1 else ""}' if line['pl_sb']: if len(s_bases): s_bases += ', ' - s_bases += f'{db_get("cards", object_id=line["card_id"])["player"]["p_name"]}' \ + card = await db_get("cards", object_id=line["card_id"]) + s_bases += f'{card["player"]["p_name"]}' \ f'{" " if line["pl_sb"] > 1 else ""}' \ f'{line["pl_sb"] if line["pl_sb"] > 1 else ""}' batter_stats.append( @@ -1765,7 +1771,8 @@ class Gameplay(commands.Cog): if line['pl_csc']: if len(caught_s): caught_s += ', ' - caught_s += f'{db_get("cards", object_id=line["card_id"])["player"]["p_name"]}' \ + card = await db_get("cards", object_id=line["card_id"]) + caught_s += f'{card["player"]["p_name"]}' \ f'{" " if line["pl_csc"] > 1 else ""}' \ f'{line["pl_csc"] if line["pl_csc"] > 1 else ""}' batter_stats.append( @@ -1832,8 +1839,8 @@ class Gameplay(commands.Cog): s_bases += '\n' if len(s_bases) else '' caught_s += '\n' if len(caught_s) else '' - db_post('batstats', payload={'stats': batter_stats}) - db_post('pitstats', payload={'stats': pitcher_stats}) + await db_post('batstats', payload={'stats': batter_stats}) + await db_post('pitstats', payload={'stats': pitcher_stats}) # Post a notification to PD last_play = get_current_play(this_game.id) @@ -1865,12 +1872,16 @@ class Gameplay(commands.Cog): name='Location', value=f'{ctx.guild.get_channel(this_game.channel_id).mention}' ) + wc_query = await db_get("cards", object_id=decisions["winner"]) + lc_query = await db_get("cards", object_id=decisions["loser"]) + if decisions["save"]: + sv_query = await db_get("cards", object_id=decisions["save"]) embed.add_field( name='Pitching', - value=f'Win: {db_get("cards", object_id=decisions["winner"])["player"]["p_name"]}\n' - f'Loss: {db_get("cards", object_id=decisions["loser"])["player"]["p_name"]}\n' + value=f'Win: {wc_query["player"]["p_name"]}\n' + f'Loss: {lc_query["player"]["p_name"]}\n' f'{"Save: " if decisions["save"] else ""}' - f'{db_get("cards", object_id=decisions["save"])["player"]["p_name"] if decisions["save"] else ""}', + f'{sv_query["player"]["p_name"] if decisions["save"] else ""}', inline=False ) if len(doubles) + len(triples) + len(homers) > 0: @@ -1913,7 +1924,7 @@ class Gameplay(commands.Cog): ctx=ctx ) - this_run = db_get('gauntletruns', object_id=int(this_game.game_type.split('-')[3])) + this_run = await db_get('gauntletruns', object_id=int(this_game.game_type.split('-')[3])) if this_run['losses'] == 2: await send_to_channel( bot=self.bot, @@ -2003,7 +2014,7 @@ class Gameplay(commands.Cog): raise SyntaxError(f'You have more than one {row[0].upper()} in this lineup. Please ' f'update and set the lineup again.') - this_card = db_get(f'cards', object_id=int(row[1])) + this_card = await db_get(f'cards', object_id=int(row[1])) if this_card['team']['id'] != lineup_team['id']: raise SyntaxError(f'Easy there, champ. Looks like card ID {row[1]} belongs to the ' f'{this_card["team"]["sname"]}. Try again with only cards you own.') @@ -2030,7 +2041,7 @@ class Gameplay(commands.Cog): if lineup_team['is_ai']: starter = starting_pitcher(lineup_team, self.bot, True if this_game.ai_team == 'home' else False) - this_card = db_get(f'cards', object_id=int(starter)) + this_card = await db_get(f'cards', object_id=int(starter)) all_lineups.append({ 'game_id': this_game.id, 'team_id': lineup_team['id'], @@ -2042,7 +2053,7 @@ class Gameplay(commands.Cog): }) all_pos.append('P') else: - this_card = db_get(f'cards', object_id=sp_card_id) + this_card = await db_get(f'cards', object_id=sp_card_id) logging.debug(f'this_card: {this_card}') if this_card['team']['id'] != lineup_team['id']: @@ -2070,7 +2081,7 @@ class Gameplay(commands.Cog): # Check roster legality if this_game.game_type in ['major-league', 'hall-of-fame']: l_string = "&card_id=".join(card_ids) - legality = db_post(f'cards/legal-check/ranked?card_id={l_string}') + legality = await db_post(f'cards/legal-check/ranked?card_id={l_string}') if legality['count'] > 0: il_string = "\n- ".join(legality['bad_cards']) await interaction.edit_original_response( @@ -2114,7 +2125,7 @@ class Gameplay(commands.Cog): @commands.command(name='get-bullpen', help='Mod: Sync an AI bullpen') @commands.is_owner() async def get_bullpen_command(self, ctx: commands.Context, team_id): - team = db_get('teams', object_id=team_id) + team = await db_get('teams', object_id=team_id) if not team: await ctx.send(f'I did not find a team with id {team_id}') return @@ -2158,7 +2169,7 @@ class Gameplay(commands.Cog): try: if this_game.is_pd: - this_card = db_get(f'cards', object_id=int(new_player)) + this_card = await db_get(f'cards', object_id=int(new_player)) if this_card["team"]["id"] != lineup_team['id']: raise SyntaxError(f'Easy there, champ. Looks like card ID {new_player} belongs to the ' f'{this_card["team"]["sname"]}. Try again with only cards you own.') @@ -2180,7 +2191,7 @@ class Gameplay(commands.Cog): return if this_game.game_type in ['major-league', 'hall-of-fame']: - legality = db_post(f'cards/legal-check/ranked?card_id={new_player}') + legality = await db_post(f'cards/legal-check/ranked?card_id={new_player}') if legality['count'] > 0: il_string = "\n- ".join(legality['bad_cards']) await ctx.send( @@ -3130,7 +3141,7 @@ class Gameplay(commands.Cog): patch_play(this_play.id, locked=False) def_team_id = this_game.away_team_id if this_play.inning_half == 'Bot' else this_game.home_team_id - def_team = db_get('teams', object_id=def_team_id) + def_team = await db_get('teams', object_id=def_team_id) d_lineup = get_one_lineup(this_game.id, team_id=this_play.pitcher.team_id, position=position.value) defender = await get_player(this_game, d_lineup) patch_play(this_play.id, defender_id=d_lineup.id, check_pos=position.value) @@ -3369,6 +3380,8 @@ class Gameplay(commands.Cog): content=None, embed=await self.get_game_state_embed(this_game, full_length=False) ) return + else: + await question.delete() patch_play(this_play.id, error=1) if error_allowed == '1 base': diff --git a/cogs/players.py b/cogs/players.py index b6d0c26..770d4ff 100644 --- a/cogs/players.py +++ b/cogs/players.py @@ -253,8 +253,8 @@ class Players(commands.Cog): logging.error(f'Still cannot access guild; trying again in 18 hours') return - all_players = db_get('players', params=[('flat', True)], timeout=25) - all_cardsets = db_get('cardsets', params=[('flat', True)]) + all_players = await db_get('players', params=[('flat', True)], timeout=25) + all_cardsets = await db_get('cardsets', params=[('flat', True)]) [self.player_list.append(x['p_name'].lower()) for x in all_players['players'] if x['p_name'].lower() not in self.player_list] @@ -351,7 +351,7 @@ class Players(commands.Cog): await ctx.send(f'No clue who that is.') return - all_players = db_get('players', params=[('name', this_player)]) + all_players = await db_get('players', params=[('name', this_player)]) all_cards = [ {'player': x, 'team': {'lname': 'Paper Dynasty', 'logo': IMAGES['logo'], 'season': PD_SEASON}} for x in all_players['players'] @@ -380,7 +380,7 @@ class Players(commands.Cog): return if cardset and cardset != 'All': - this_cardset = cardset_search(cardset, self.cardset_list) + this_cardset = await cardset_search(cardset, self.cardset_list) if this_cardset: all_params = [('name', this_player), ('cardset_id', this_cardset['id'])] else: @@ -389,7 +389,7 @@ class Players(commands.Cog): else: all_params = [('name', this_player)] - all_players = db_get('players', params=all_params) + all_players = await db_get('players', params=all_params) all_cards = [get_blank_team_card(x) for x in all_players['players']] all_cards.sort(key=lambda x: x['player']['rarity']['value'], reverse=True) @@ -410,10 +410,10 @@ class Players(commands.Cog): ephemeral = True if team_abbrev: - t_query = db_get('teams', params=[('abbrev', team_abbrev)]) + t_query = await db_get('teams', params=[('abbrev', team_abbrev)]) else: - t_query = db_get('teams', params=[('gm_id', interaction.user.id)]) - current = db_get('current') + t_query = await db_get('teams', params=[('gm_id', interaction.user.id)]) + current = await db_get('current') if t_query['count'] == 0: await interaction.response.send_message( @@ -426,11 +426,11 @@ class Players(commands.Cog): f'I\'m tallying the {team["lname"]} results now...', ephemeral=ephemeral ) - rs_query = db_get( + rs_query = await db_get( 'results', params=[('team_one_id', team['id']), ('season', current['season']), ('short_game', True)] ) - rl_query = db_get( + rl_query = await db_get( 'results', params=[('team_one_id', team['id']), ('season', current['season']), ('short_game', False)] ) @@ -480,9 +480,9 @@ class Players(commands.Cog): async def team_command(self, interaction: discord.Interaction, team_abbrev: Optional[str] = None): await interaction.response.defer() if team_abbrev: - t_query = db_get('teams', params=[('abbrev', team_abbrev)]) + t_query = await db_get('teams', params=[('abbrev', team_abbrev)]) else: - t_query = db_get('teams', params=[('gm_id', interaction.user.id)]) + t_query = await db_get('teams', params=[('gm_id', interaction.user.id)]) if t_query['count'] == 0: await interaction.edit_original_response( @@ -491,7 +491,7 @@ class Players(commands.Cog): return team = t_query['teams'][0] - embed = team_summary_embed(team, interaction) + embed = await team_summary_embed(team, interaction) await interaction.edit_original_response(content=None, embed=embed) @@ -499,7 +499,7 @@ class Players(commands.Cog): @app_commands.checks.has_any_role(PD_PLAYERS_ROLE_NAME) async def card_lookup_command(self, interaction: discord.Interaction, card_id: int): await interaction.response.defer() - c_query = db_get('cards', object_id=card_id) + c_query = await db_get('cards', object_id=card_id) if c_query: c_string = f'Card ID {card_id} is a {c_query["player"]["description"]}' if c_query['team'] is not None: @@ -522,7 +522,7 @@ class Players(commands.Cog): @commands.check(legal_channel) async def branding_command( self, ctx, team_logo_url: str = None, color: str = None, short_name: str = None, full_name: str = None): - owner_team = get_team_by_owner(ctx.author.id) + owner_team = await get_team_by_owner(ctx.author.id) if not owner_team: await ctx.send(f'Hmm...I don\'t see a team for you, yet. You can create one with `/newteam`!') return @@ -541,8 +541,8 @@ class Players(commands.Cog): await ctx.send(f'You keep thinking on it - I can\'t make updates if you don\'t provide them.') return - team = db_patch('teams', object_id=owner_team['id'], params=params) - embed = team_summary_embed(team, ctx) + team = await db_patch('teams', object_id=owner_team['id'], params=params) + embed = await team_summary_embed(team, ctx) await ctx.send(content=None, embed=embed) @@ -550,7 +550,7 @@ class Players(commands.Cog): @commands.has_any_role(PD_PLAYERS_ROLE_NAME) @commands.check(legal_channel) async def fuck_command(self, ctx, gm: Member): - t_query = db_get('teams', params=[('gm_id', gm.id)]) + t_query = await db_get('teams', params=[('gm_id', gm.id)]) if t_query['count'] == 0: await ctx.send(f'Who?') return @@ -561,7 +561,7 @@ class Players(commands.Cog): @commands.has_any_role(PD_PLAYERS_ROLE_NAME) @commands.check(legal_channel) async def random_card_command(self, ctx: commands.Context): - this_player = db_get('players/random', params=[('limit', 1)])['players'][0] + this_player = await db_get('players/random', params=[('limit', 1)])['players'][0] this_embed = await get_card_embeds( {'player': this_player, 'team': {'lname': 'Paper Dynasty', 'logo': IMAGES['logo'], 'season': PD_SEASON}} ) @@ -573,7 +573,7 @@ class Players(commands.Cog): @commands.has_any_role(PD_PLAYERS_ROLE_NAME) @commands.check(legal_channel) async def paperdex_cardset_slash(self, interaction: discord.Interaction): - team = get_team_by_owner(interaction.user.id) + team = await get_team_by_owner(interaction.user.id) if not team: await interaction.response.send_message(f'Do you even have a team? I don\'t know you.', ephemeral=True) return @@ -592,7 +592,7 @@ class Players(commands.Cog): @commands.has_any_role(PD_PLAYERS_ROLE_NAME) @commands.check(legal_channel) async def paperdex_cardset_slash(self, interaction: discord.Interaction): - team = get_team_by_owner(interaction.user.id) + team = await get_team_by_owner(interaction.user.id) if not team: await interaction.response.send_message(f'Do you even have a team? I don\'t know you.', ephemeral=True) return @@ -649,13 +649,13 @@ class Players(commands.Cog): @commands.has_any_role(PD_PLAYERS_ROLE_NAME) @commands.check(legal_channel) async def standings_command(self, ctx: commands.Context, which: Literal['week', 'season']): - current = db_get('current') + current = await db_get('current') params = [('season', current['season']), ('ranked', True)] if which == 'week': params.append(('week', current['week'])) - r_query = db_get('results', params=params) + r_query = await db_get('results', params=params) if not r_query['count']: await ctx.send(f'There are no Ranked games on record this {"week" if which == "week" else "season"}.') return @@ -699,7 +699,7 @@ class Players(commands.Cog): chunk_string = '' for index, record in enumerate(sorted_records): # logging.info(f'index: {index} / record: {record}') - team = db_get('teams', object_id=record[0]) + team = await db_get('teams', object_id=record[0]) if team: chunk_string += f'{record[1]["points"]} pt{"s" if record[1]["points"] != 1 else ""} ' \ f'({record[1]["wins"]}-{record[1]["losses"]}) - {team["sname"]} [{team["ranking"]}]\n' @@ -730,7 +730,7 @@ class Players(commands.Cog): @commands.has_any_role(PD_PLAYERS_ROLE_NAME) @commands.check(legal_channel) async def pull_roster_command(self, ctx: commands.Context, specific_roster_num: Optional[int] = None): - team = get_team_by_owner(ctx.author.id) + team = await get_team_by_owner(ctx.author.id) if not team: await ctx.send(f'Do you even have a team? I don\'t know you.') return @@ -744,7 +744,7 @@ class Players(commands.Cog): for index, roster in enumerate(roster_data): logging.debug(f'index: {index} / roster: {roster}') if (not specific_roster_num or specific_roster_num == index + 1) and roster: - this_roster = db_post( + this_roster = await db_post( 'rosters', payload={ 'team_id': team['id'], 'name': roster['name'], @@ -765,7 +765,7 @@ class Players(commands.Cog): self, interaction: discord.Interaction, event_name: Literal['Paper Sluggers'], team_abbrev: str = None): await interaction.response.defer() - e_query = db_get('events', params=[("name", event_name), ("active", True)]) + e_query = await db_get('events', params=[("name", event_name), ("active", True)]) if e_query['count'] == 0: await interaction.response.send_message(f'Hmm...looks like that event has ended already.') return @@ -776,10 +776,10 @@ class Players(commands.Cog): if team_abbrev: if 'Gauntlet-' not in team_abbrev: team_abbrev = f'Gauntlet-{team_abbrev}' - t_query = db_get('teams', params=[('abbrev', team_abbrev)]) + t_query = await db_get('teams', params=[('abbrev', team_abbrev)]) if t_query['count'] != 0: this_team = t_query['teams'][0] - r_query = db_get('gauntletruns', params=[('team_id', this_team['id']), ('is_active', True)]) + r_query = await db_get('gauntletruns', params=[('team_id', this_team['id']), ('is_active', True)]) if r_query['count'] != 0: this_run = r_query['runs'][0] @@ -794,7 +794,7 @@ class Players(commands.Cog): await interaction.edit_original_response( content=None, - embed=gauntlets.get_embed(this_run, this_event, this_team) + embed=await gauntlets.get_embed(this_run, this_event, this_team) ) @group_gauntlet.command(name='start', description='Start a new Gauntlet run') @@ -809,10 +809,10 @@ class Players(commands.Cog): return await interaction.response.defer() - main_team = get_team_by_owner(interaction.user.id) - draft_team = get_team_by_abbrev(f'Gauntlet-{main_team["abbrev"]}') + main_team = await get_team_by_owner(interaction.user.id) + draft_team = await get_team_by_abbrev(f'Gauntlet-{main_team["abbrev"]}') - e_query = db_get('events', params=[("name", event_name), ("active", True)]) + e_query = await db_get('events', params=[("name", event_name), ("active", True)]) if e_query['count'] == 0: await interaction.response.send_message(f'Hmm...looks like that event has ended already.') return @@ -821,7 +821,7 @@ class Players(commands.Cog): first_flag = draft_team is None if draft_team is not None: - r_query = db_get( + r_query = await db_get( 'gauntletruns', params=[('team_id', draft_team['id']), ('gauntlet_id', this_event['id']), ('is_active', True)] ) @@ -839,7 +839,7 @@ class Players(commands.Cog): return except Exception as e: logging.error(f'Failed to run {event_name} draft for the {main_team["sname"]}: {e}') - draft_team = db_get('teams', params=[('abbrev', f'Gauntlet-{main_team["abbrev"]}')]) + draft_team = await db_get('teams', params=[('abbrev', f'Gauntlet-{main_team["abbrev"]}')]) await gauntlets.wipe_team(draft_team, interaction) await interaction.channel.send( content=f'Shoot - it looks like we ran into an issue running the draft. I had to clear it all out ' diff --git a/db_calls.py b/db_calls.py index 8b1413c..cdfa6e3 100644 --- a/db_calls.py +++ b/db_calls.py @@ -33,8 +33,8 @@ def get_req_url(endpoint: str, api_ver: int = 1, object_id: int = None, params: return req_url -def db_get(endpoint: str, api_ver: int = 1, object_id: int = None, params: list = None, none_okay: bool = True, - timeout: int = 3): +async def db_get(endpoint: str, api_ver: int = 1, object_id: int = None, params: list = None, none_okay: bool = True, + timeout: int = 3): req_url = get_req_url(endpoint, api_ver=api_ver, object_id=object_id, params=params) log_string = f'get:\n{endpoint} id: {object_id} params: {params}' logging.info(log_string) if master_debug else logging.debug(log_string) @@ -73,7 +73,7 @@ def db_get(endpoint: str, api_ver: int = 1, object_id: int = None, params: list raise ValueError(f'DB: {resp.text}') -def db_patch(endpoint: str, object_id: int, params: list, api_ver: int = 1, timeout: int = 3): +async def db_patch(endpoint: str, object_id: int, params: list, api_ver: int = 1, timeout: int = 3): req_url = get_req_url(endpoint, api_ver=api_ver, object_id=object_id, params=params) log_string = f'patch:\n{endpoint} {params}' logging.info(log_string) if master_debug else logging.debug(log_string) @@ -104,7 +104,7 @@ def db_patch(endpoint: str, object_id: int, params: list, api_ver: int = 1, time raise ValueError(f'DB: {resp.text}') -def db_post(endpoint: str, api_ver: int = 1, payload: dict = None, timeout: int = 3): +async def db_post(endpoint: str, api_ver: int = 1, payload: dict = None, timeout: int = 3): req_url = get_req_url(endpoint, api_ver=api_ver) log_string = f'post:\n{endpoint} payload: {payload}\ntype: {type(payload)}' logging.info(log_string) if master_debug else logging.debug(log_string) @@ -135,7 +135,7 @@ def db_post(endpoint: str, api_ver: int = 1, payload: dict = None, timeout: int raise ValueError(f'DB: {resp.text}') -def db_delete(endpoint: str, object_id: int, api_ver: int = 1, timeout=3): +async def db_delete(endpoint: str, object_id: int, api_ver: int = 1, timeout=3): req_url = get_req_url(endpoint, api_ver=api_ver, object_id=object_id) log_string = f'delete:\n{endpoint} {object_id}' logging.info(log_string) if master_debug else logging.debug(log_string) @@ -166,8 +166,8 @@ def db_delete(endpoint: str, object_id: int, api_ver: int = 1, timeout=3): raise ValueError(f'DB: {resp.text}') -def get_team_by_abbrev(abbrev: str): - all_teams = db_get('teams', params=[('abbrev', abbrev)]) +async def get_team_by_abbrev(abbrev: str): + all_teams = await db_get('teams', params=[('abbrev', abbrev)]) if not all_teams or not all_teams['count']: return None @@ -175,8 +175,8 @@ def get_team_by_abbrev(abbrev: str): return all_teams['teams'][0] -def post_to_dex(player, team): - return db_post('paperdex', payload={'team_id': team['id'], 'player_id': player['id']}) +async def post_to_dex(player, team): + return await db_post('paperdex', payload={'team_id': team['id'], 'player_id': player['id']}) def team_hash(team): diff --git a/db_calls_gameplay.py b/db_calls_gameplay.py index 5d82f17..33bbcf5 100644 --- a/db_calls_gameplay.py +++ b/db_calls_gameplay.py @@ -71,7 +71,7 @@ def get_sba_team_by_owner(season, owner_id): raise ValueError(f'DB: {resp.text}') -# def pd_db_get(endpoint: str, api_ver: int = 1, object_id: int = None, params: list = None, none_okay: bool = True): +# def pd_await db_get(endpoint: str, api_ver: int = 1, object_id: int = None, params: list = None, none_okay: bool = True): # req_url = pd_get_req_url(endpoint, api_ver=api_ver, object_id=object_id, params=params) # logging.info(f'get:\n{endpoint} id: {object_id} params: {params}') # @@ -90,7 +90,7 @@ def get_sba_team_by_owner(season, owner_id): # def pd_get_one_team(team_abbrev: str): -# team = pd_db_get('teams', params=[('abbrev', team_abbrev), ('season', PD_SEASON)], none_okay=False)['teams'][0] +# team = pd_await db_get('teams', params=[('abbrev', team_abbrev), ('season', PD_SEASON)], none_okay=False)['teams'][0] # return team # # # req_url = pd_get_req_url('teams', ) @@ -106,7 +106,7 @@ def get_sba_team_by_owner(season, owner_id): # def pd_get_card_by_id(card_id: int): -# return pd_db_get('cards', object_id=card_id, none_okay=False) +# return pd_await db_get('cards', object_id=card_id, none_okay=False) class BaseModel(Model): @@ -485,11 +485,11 @@ async def get_game_team(game: StratGame, gm_id: int = None, team_abbrev: str = N f'tm_abbrev: {team_abbrev} / team_id: {team_id} / game: {game}') if game.is_pd: if gm_id: - return db_get('teams', params=[('season', PD_SEASON), ('gm_id', gm_id)])['teams'][0] + return await db_get('teams', params=[('season', PD_SEASON), ('gm_id', gm_id)])['teams'][0] elif team_id: - return db_get('teams', object_id=team_id) + return await db_get('teams', object_id=team_id) else: - return db_get('teams', params=[('season', PD_SEASON), ('abbrev', team_abbrev)])['teams'][0] + return await db_get('teams', params=[('season', PD_SEASON), ('abbrev', team_abbrev)])['teams'][0] else: if gm_id: return get_sba_team_by_owner(season=SBA_SEASON, owner_id=gm_id) @@ -758,7 +758,7 @@ def undo_subs(game: StratGame, new_play_num: int): async def get_player(game, lineup_member) -> dict: if isinstance(game, Game): if game.is_pd: - this_card = db_get(f'cards', object_id=lineup_member.card_id) + 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'] @@ -769,7 +769,7 @@ async def get_player(game, lineup_member) -> dict: 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 = db_get(f'cards', object_id=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'] diff --git a/gauntlets.py b/gauntlets.py index bc06e05..6dc89d3 100644 --- a/gauntlets.py +++ b/gauntlets.py @@ -16,29 +16,29 @@ from db_calls import db_get, db_post, db_delete, db_patch async def wipe_team(this_team, interaction: discord.Interaction, delete_team: bool = False, delete_runs: bool = False): await interaction.edit_original_response(content=f'Looking for cards...') # Delete cards - c_query = db_get('cards', params=[('team_id', this_team['id'])]) + c_query = await db_get('cards', params=[('team_id', this_team['id'])]) await interaction.edit_original_response(content=f'Found {c_query["count"]} cards; deleting cards...') for x in c_query['cards']: - db_delete('cards', object_id=x['id']) + await db_delete('cards', object_id=x['id']) # Delete packs await interaction.edit_original_response(content=f'Done deleting cards; searching for packs...') - p_query = db_get('packs', params=[('team_id', this_team['id'])]) + p_query = await db_get('packs', params=[('team_id', this_team['id'])]) await interaction.edit_original_response(content=f'Found {p_query["count"]} packs; deleting packs...') for x in p_query['packs']: - db_delete('packs', object_id=x['id']) + await db_delete('packs', object_id=x['id']) # Delete team if delete_team: await interaction.edit_original_response(content=f'Done deleting packs; now deleting team...') - db_delete('teams', object_id=this_team['id']) + await db_delete('teams', object_id=this_team['id']) await interaction.edit_original_response(content=f'Team is deleted; now finding the run...') if delete_runs: - r_query = db_get('gauntletruns', params=[('team_id', this_team['id']), ('is_active', True)]) + r_query = await db_get('gauntletruns', params=[('team_id', this_team['id']), ('is_active', True)]) await interaction.edit_original_response(content=f'Found {r_query["count"]} runs; deleting now...') for x in r_query['runs']: - db_delete('gauntletruns', object_id=x['id']) + await db_delete('gauntletruns', object_id=x['id']) def get_game_code(this_team, this_event, this_run): @@ -55,7 +55,7 @@ def is_home_team(this_team, this_event, this_run): return False -def get_opponent(this_team, this_event, this_run): +async def get_opponent(this_team, this_event, this_run): if this_event['id'] == 1: gp = games_played(this_run) if gp == 0: @@ -82,19 +82,19 @@ def get_opponent(this_team, this_event, this_run): t_id = 58 else: raise KeyError(f'Huh...I have no idea who you should be playing right now.') - return db_get('teams', object_id=t_id, none_okay=False) + return await db_get('teams', object_id=t_id, none_okay=False) else: return None -def build_lineup(this_team, this_game, this_event): +async def build_lineup(this_team, this_game, this_event): if this_event['id'] == 1: - return ai_manager.build_lineup(this_team, this_game.id, f'gauntlet-{this_event["id"]}') + return await ai_manager.build_lineup(this_team, this_game.id, f'gauntlet-{this_event["id"]}') else: raise KeyError(f'Lineups not found for Gauntlet {this_event["id"]}') -def get_starting_pitcher(this_team, this_game, this_event, this_run): +async def get_starting_pitcher(this_team, this_game, this_event, this_run): if this_event['id'] == 1: if this_team['id'] != 58: set_params = ai_manager.MINOR_CARDSET_PARAMS @@ -118,7 +118,7 @@ def get_starting_pitcher(this_team, this_game, this_event, this_run): # Pull starters sorted by current cost try: params.extend(set_params) - pitchers = db_get( + pitchers = await db_get( endpoint='players', params=params, timeout=10 @@ -140,7 +140,7 @@ def get_starting_pitcher(this_team, this_game, this_event, this_run): break pitcher_num = games_played(this_run) % 5 - card_id = ai_manager.get_or_create_card(pitchers['players'][pitcher_num], this_team) + card_id = await ai_manager.get_or_create_card(pitchers['players'][pitcher_num], this_team) return { 'game_id': this_game.id, @@ -165,7 +165,7 @@ async def run_draft(interaction: discord.Interaction, main_team, this_event, dra if draft_team is None: # Post draft team linked to main team - draft_team = db_post( + draft_team = await db_post( 'teams', payload={ 'abbrev': f'Gauntlet-{main_team["abbrev"]}', @@ -211,7 +211,7 @@ async def run_draft(interaction: discord.Interaction, main_team, this_event, dra else: view.confirm.label = 'Let\'s Go!' - intro_embed = get_embed(this_event=this_event) + intro_embed = await get_embed(this_event=this_event) intro_embed.title += ' - Are you ready?' await interaction.edit_original_response( @@ -424,7 +424,7 @@ async def run_draft(interaction: discord.Interaction, main_team, this_event, dra logging.info(f'slot_params: {slot_params}') logging.info(f'params: {params}') slot_params.extend(params) - p_query = db_get('players/random', params=slot_params) + p_query = await db_get('players/random', params=slot_params) if p_query['count'] > 0: # test_player_list = '' @@ -439,7 +439,7 @@ async def run_draft(interaction: discord.Interaction, main_team, this_event, dra if len(this_batch) < 4: logging.error(f'Pulled less than 4 players in gauntlet draft') - p_query = db_get('players/random', params=params) + p_query = await db_get('players/random', params=params) for i in p_query['players']: if i['p_name'] not in p_names and i not in this_batch: this_batch.append(i) @@ -475,7 +475,7 @@ async def run_draft(interaction: discord.Interaction, main_team, this_event, dra raise KeyError(f'I gotta be honest - I shit the bed here and wasn\'t able to get you enough players to fill ' f'a team. I have to wipe this team, but please draft again after you tell Cal his bot sucks.') - this_pack = db_post( + this_pack = await db_post( 'packs/one', payload={ 'team_id': draft_team['id'], @@ -483,13 +483,13 @@ async def run_draft(interaction: discord.Interaction, main_team, this_event, dra 'open_time': datetime.datetime.timestamp(datetime.datetime.now()) * 1000 } ) - db_post( + await db_post( 'cards', payload={'cards': [ {'player_id': x['player_id'], 'team_id': draft_team['id'], 'pack_id': this_pack['id']} for x in all_players ]} ) - db_post( + await db_post( 'gauntletruns', payload={ 'team_id': draft_team['id'], @@ -504,7 +504,7 @@ async def run_draft(interaction: discord.Interaction, main_team, this_event, dra return final_embed -def get_embed(this_run=None, this_event=None, this_team=None): +async def get_embed(this_run=None, this_event=None, this_team=None): logging.info(f'get_embed - this_run:\n{this_run}\n\nthis_event:\n{this_event}') if this_run is None and this_event is None: @@ -525,7 +525,7 @@ def get_embed(this_run=None, this_event=None, this_team=None): if this_run is not None: embed.add_field(name='Current Record', value=f'{this_run["wins"]}-{this_run["losses"]}', inline=False) - r_query = db_get('gauntletrewards', params=[('gauntlet_id', this_event['id'])]) + r_query = await db_get('gauntletrewards', params=[('gauntlet_id', this_event['id'])]) reward_string = '' for x in r_query['rewards']: if this_run is not None: @@ -547,10 +547,10 @@ def get_embed(this_run=None, this_event=None, this_team=None): embed.add_field(name='Rewards', value=reward_string) if this_team is not None: - run_query = db_get('gauntletruns', params=[('team_id', this_team['id']), ('gauntlet_id', this_event['id'])]) + run_query = await db_get('gauntletruns', params=[('team_id', this_team['id']), ('gauntlet_id', this_event['id'])]) record_name = f'{this_team["abbrev"].split("-")[1]} Record' else: - run_query = db_get('gauntletruns', params=[('gauntlet_id', this_event['id'])]) + run_query = await db_get('gauntletruns', params=[('gauntlet_id', this_event['id'])]) record_name = f'League Record' record_value = '' @@ -580,30 +580,31 @@ def get_embed(this_run=None, this_event=None, this_team=None): async def post_result(run_id: int, is_win: bool, this_team, bot, ctx): - this_run = db_get('gauntletruns', object_id=run_id) - this_event = db_get('events', object_id=this_run['gauntlet']['id']) - main_team = db_get('teams', params=[('abbrev', f'{this_team["abbrev"].replace("Gauntlet-","")}')])['teams'][0] + this_run = await db_get('gauntletruns', object_id=run_id) + this_event = await db_get('events', object_id=this_run['gauntlet']['id']) + t_query = await db_get('teams', params=[('abbrev', f'{this_team["abbrev"].replace("Gauntlet-","")}')]) + main_team = t_query['teams'][0] if is_win: - this_run = db_patch( + this_run = await db_patch( 'gauntletruns', object_id=this_run['id'], params=[('wins', this_run['wins'] + 1), ('ended', this_run['wins'] + 1 == 10)] ) - r_query = db_get( + r_query = await db_get( 'gauntletrewards', params=[('gauntlet_id', this_event['id']), ('win_num', this_run['wins']), ('loss_max', this_run['losses'])] ) reward_string = '' for x in r_query['rewards']: if x['reward']['money']: - db_post(f'teams/{main_team["id"]}/money/{x["reward"]["money"]}') + await db_post(f'teams/{main_team["id"]}/money/{x["reward"]["money"]}') reward_string += f'- {x["reward"]["money"]}₼\n' elif x['reward']['player']: # TODO: add give player code pass elif x['reward']['pack_type']: - helpers.give_packs(main_team, 1, x['reward']['pack_type']) + await helpers.give_packs(main_team, 1, x['reward']['pack_type']) reward_string += f'- 1x {x["reward"]["pack_type"]["name"]} Pack' if this_run['wins'] == 10: @@ -617,7 +618,7 @@ async def post_result(run_id: int, is_win: bool, this_team, bot, ctx): ) final_message = f'That\'s number 10! Way to go - you have completed the **{this_event["name"]} Gauntlet** ' \ f'with a record of {this_run["wins"]}-{this_run["losses"]}! ' - c_query = db_post(f'cards/wipe-team/{this_team["id"]}') + c_query = await db_post(f'cards/wipe-team/{this_team["id"]}') else: final_message = f'Big win there! Your {this_event["name"]} record is now **{this_run["wins"]}-' \ f'{this_run["losses"]}**. ' @@ -628,10 +629,10 @@ async def post_result(run_id: int, is_win: bool, this_team, bot, ctx): await ctx.send( content=final_message, - embed=get_embed(this_run) + embed=await get_embed(this_run) ) else: - this_run = db_patch( + this_run = await db_patch( 'gauntletruns', object_id=this_run['id'], params=[('losses', this_run['losses'] + 1), ('ended', this_run['losses'] + 1 == 2)] @@ -640,10 +641,10 @@ async def post_result(run_id: int, is_win: bool, this_team, bot, ctx): f'**{this_run["wins"]}-{this_run["losses"]}**. ' if this_run['losses'] == 2: l_message += 'That\'s the end of this run - better luck next time!' - c_query = db_post(f'cards/wipe-team/{this_team["id"]}') + c_query = await db_post(f'cards/wipe-team/{this_team["id"]}') await ctx.send( content=l_message, - embed=get_embed(this_run) + embed=await get_embed(this_run) ) diff --git a/helpers.py b/helpers.py index 5cdf7fa..6f5a024 100644 --- a/helpers.py +++ b/helpers.py @@ -559,12 +559,12 @@ class SelectChoicePackTeam(discord.ui.Select): ('pack_type_id', 8), ('team_id', self.owner_team['id']), ('opened', False), ('limit', 1), ('exact_match', True) ] - p_query = db_get('packs', params=params) + p_query = await db_get('packs', params=params) if p_query['count'] == 0: logging.error(f'open-packs - no packs found with params: {params}') raise ValueError(f'Unable to open packs') - this_pack = db_patch('packs', object_id=p_query['packs'][0]['id'], params=[('pack_team_id', team_id)]) + this_pack = await db_patch('packs', object_id=p_query['packs'][0]['id'], params=[('pack_team_id', team_id)]) await open_choice_pack(this_pack, self.owner_team, interaction) @@ -578,7 +578,7 @@ class SelectOpenPack(discord.ui.Select): pack_vals = self.values[0].split('-') # Get the owner's team - owner_team = get_team_by_owner(interaction.user.id) + owner_team = await get_team_by_owner(interaction.user.id) # Get the selected packs params = [('team_id', owner_team['id']), ('opened', False), ('limit', 5), ('exact_match', True)] @@ -624,7 +624,7 @@ class SelectOpenPack(discord.ui.Select): elif 'Cardset' in pack_vals: params.append(('pack_cardset_id', pack_vals[2])) - p_query = db_get('packs', params=params) + p_query = await db_get('packs', params=params) if p_query['count'] == 0: logging.error(f'open-packs - no packs found with params: {params}') raise ValueError(f'Unable to open packs') @@ -672,10 +672,13 @@ class SelectPaperdexCardset(discord.ui.Select): elif self.values[0] == '2023 Season': cardset_id = 9 - c_query = db_get('cardsets', object_id=cardset_id, none_okay=False) + c_query = await db_get('cardsets', object_id=cardset_id, none_okay=False) await interaction.response.edit_message(content=f'Okay, sifting through your cards...', view=None) - cardset_embeds = paperdex_cardset_embed(team=get_team_by_owner(interaction.user.id), this_cardset=c_query) + cardset_embeds = await paperdex_cardset_embed( + team=await get_team_by_owner(interaction.user.id), + this_cardset=c_query + ) await embed_pagination(cardset_embeds, interaction.channel, interaction.user) @@ -785,10 +788,10 @@ class SelectPaperdexTeam(discord.ui.Select): elif self.values[0] == 'Washington Nationals': team_id = 30 - t_query = db_get('teams', object_id=team_id, none_okay=False) + t_query = await db_get('teams', object_id=team_id, none_okay=False) await interaction.response.edit_message(content=f'Okay, sifting through your cards...', view=None) - team_embeds = paperdex_team_embed(team=get_team_by_owner(interaction.user.id), mlb_team=t_query) + team_embeds = await paperdex_team_embed(team=await get_team_by_owner(interaction.user.id), mlb_team=t_query) await embed_pagination(team_embeds, interaction.channel, interaction.user) @@ -853,8 +856,8 @@ class SelectBuyPacksCardset(discord.ui.Select): 'pack_type_id': self.pack_type_id, 'pack_cardset_id': cardset_id } - db_post('packs', payload={'packs': [p_model for x in range(self.quantity)]}) - db_post(f'teams/{self.team["id"]}/money/-{self.cost}') + await db_post('packs', payload={'packs': [p_model for x in range(self.quantity)]}) + await db_post(f'teams/{self.team["id"]}/money/-{self.cost}') await question.edit( content=f'{"They are" if self.quantity > 1 else "It is"} all yours! Go rip \'em with `/open-packs`', @@ -1003,8 +1006,8 @@ class SelectBuyPacksTeam(discord.ui.Select): 'pack_type_id': self.pack_type_id, 'pack_team_id': team_id } - db_post('packs', payload={'packs': [p_model for x in range(self.quantity)]}) - db_post(f'teams/{self.team["id"]}/money/-{self.cost}') + await db_post('packs', payload={'packs': [p_model for x in range(self.quantity)]}) + await db_post(f'teams/{self.team["id"]}/money/-{self.cost}') await question.edit( content=f'{"They are" if self.quantity > 1 else "It is"} all yours! Go rip \'em with `/open-packs`', @@ -1268,7 +1271,7 @@ async def get_player_photo(player): return None if resp.status_code == 200 and resp.json()['player']: if resp.json()['player'][0]['strSport'] == 'Baseball': - db_patch('players', object_id=player['player_id'], + await db_patch('players', object_id=player['player_id'], params=[('headshot', resp.json()['player'][0]['strThumb'])]) return resp.json()['player'][0]['strThumb'] return None @@ -1283,7 +1286,7 @@ async def get_player_headshot(player): soup = BeautifulSoup(resp, 'html.parser') for item in soup.find_all('img'): if 'headshot' in item['src']: - db_patch('players', object_id=player['player_id'], params=[('headshot', item['src'])]) + await db_patch('players', object_id=player['player_id'], params=[('headshot', item['src'])]) return item['src'] except: pass @@ -1433,8 +1436,8 @@ def get_team_embed(title, team=None, thumbnail: bool = True): return embed -def get_team_by_owner(owner_id: int): - team = db_get('teams', params=[('gm_id', owner_id)]) +async def get_team_by_owner(owner_id: int): + team = await db_get('teams', params=[('gm_id', owner_id)]) if not team['count']: return None @@ -1530,7 +1533,7 @@ async def get_card_embeds(card) -> list: embed.add_field(name='Player Page', value=f'{player_pages}') # all_dex = card['player']['paperdex'] - all_dex = db_get('paperdex', params=[("player_id", card["player"]["player_id"]), ('flat', True)]) + all_dex = await db_get('paperdex', params=[("player_id", card["player"]["player_id"]), ('flat', True)]) count = all_dex['count'] if card['team']['lname'] != 'Paper Dynasty': bool_list = [True for elem in all_dex['paperdex'] if elem['team'] == card['team']['id']] @@ -1549,7 +1552,7 @@ async def get_card_embeds(card) -> list: # TODO: check for dupes with the included paperdex data # if card['team']['lname'] != 'Paper Dynasty': - # team_dex = db_get('cards', params=[("player_id", card["player"]["player_id"]), ('team_id', card['team']['id'])]) + # team_dex = await db_get('cards', params=[("player_id", card["player"]["player_id"]), ('team_id', card['team']['id'])]) # count = 1 if not team_dex['count'] else team_dex['count'] # embed.add_field(name='# Dupes', value=f'{count - 1} dupe{"s" if count - 1 != 1 else ""}') @@ -1793,16 +1796,19 @@ def get_channel(ctx, name) -> Optional[discord.TextChannel]: async def get_test_pack(ctx, team): pull_notifs = [] - this_pack = db_post('packs/one', payload={ + this_pack = await db_post('packs/one', payload={ 'team_id': team['id'], 'pack_type_id': 1, 'open_time': int(datetime.datetime.timestamp(datetime.datetime.now())*1000) }) - first_three = db_get('players/random', params=[('max_rarity', 1), ('limit', 3)])['players'] - fourth = db_get('players/random', params=[('min_rarity', 1), ('max_rarity', 3), ('limit', 1)])['players'] - fifth = db_get('players/random', params=[('min_rarity', 5), ('max_rarity', 5), ('limit', 1)])['players'] + ft_query = await db_get('players/random', params=[('max_rarity', 1), ('limit', 3)]) + four_query = await db_get('players/random', params=[('min_rarity', 1), ('max_rarity', 3), ('limit', 1)]) + five_query = await db_get('players/random', params=[('min_rarity', 5), ('max_rarity', 5), ('limit', 1)]) + first_three = ft_query['players'] + fourth = four_query['players'] + fifth = five_query['players'] all_cards = [*first_three, *fourth, *fifth] - success = db_post('cards', timeout=10, payload={'cards': [{ + success = await db_post('cards', timeout=10, payload={'cards': [{ 'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in all_cards] }) if not success: @@ -1814,7 +1820,7 @@ async def get_test_pack(ctx, team): pull_notifs.append(x) for pull in pull_notifs: - db_post('notifs', payload={ + await db_post('notifs', payload={ 'created': int(datetime.datetime.timestamp(datetime.datetime.now())*1000), 'title': 'Rare Pull', 'field_name': f'{pull["description"]} ({pull["rarity"]["name"]})', @@ -2021,7 +2027,7 @@ async def roll_for_cards(all_packs: list, extra_val=None) -> list: elif all_packs[0]['pack_cardset'] is not None: params.append(('cardset_id', all_packs[0]['pack_cardset']['id'])) - pl = db_get('players/random', params=params) + pl = await db_get('players/random', params=params) if pl['count'] != counts[key]['count']: mvp_flag = counts[key]['count'] - pl['count'] @@ -2034,13 +2040,13 @@ async def roll_for_cards(all_packs: list, extra_val=None) -> list: pull_notifs.append(x) if mvp_flag: - pl = db_get('players/random', params=[('min_rarity', 5), ('limit', mvp_flag)]) + pl = await db_get('players/random', params=[('min_rarity', 5), ('limit', mvp_flag)]) for x in pl['players']: this_pack_players.append(x) all_players.append(x) - success = db_post( + success = await db_post( 'cards', payload={'cards': [{ 'player_id': x['player_id'], 'team_id': pack['team']['id'], 'pack_id': pack['id']} for x in this_pack_players] @@ -2050,14 +2056,14 @@ async def roll_for_cards(all_packs: list, extra_val=None) -> list: if not success: raise ConnectionError(f'Failed to create this pack of cards.') - db_patch('packs', object_id=pack['id'], params=[ + await db_patch('packs', object_id=pack['id'], params=[ ('open_time', int(datetime.datetime.timestamp(datetime.datetime.now())*1000)) ]) pack_ids.append(pack['id']) for pull in pull_notifs: logging.info(f'good pull: {pull}') - db_post('notifs', payload={ + await db_post('notifs', payload={ 'created': int(datetime.datetime.timestamp(datetime.datetime.now())*1000), 'title': 'Rare Pull', 'field_name': f'{pull["description"]} ({pull["rarity"]["name"]})', @@ -2068,7 +2074,7 @@ async def roll_for_cards(all_packs: list, extra_val=None) -> list: return pack_ids -def give_packs(team: dict, num_packs: int, pack_type: dict = None) -> dict: +async def give_packs(team: dict, num_packs: int, pack_type: dict = None) -> dict: """ Parameters ---------- @@ -2081,11 +2087,11 @@ def give_packs(team: dict, num_packs: int, pack_type: dict = None) -> dict: { 'count': int, 'packs': [ all team packs ] } """ pt_id = pack_type['id'] if pack_type is not None else 1 - db_post( + await db_post( 'packs', payload={'packs': [{'team_id': team['id'], 'pack_type_id': pt_id} for x in range(num_packs)]} ) - total_packs = db_get('packs', params=[ + total_packs = await db_get('packs', params=[ ('team_id', team['id']), ('opened', False) ]) @@ -2181,12 +2187,12 @@ def get_pos_abbrev(pos_name): raise KeyError(f'{pos_name} is not a recognized position name') -def cardset_search(cardset: str, cardset_list: list) -> Optional[dict]: +async def cardset_search(cardset: str, cardset_list: list) -> Optional[dict]: cardset_name = fuzzy_search(cardset, cardset_list) if not cardset_name: return None - c_query = db_get('cardsets', params=[('name', cardset_name)]) + c_query = await db_get('cardsets', params=[('name', cardset_name)]) if c_query['count'] == 0: return None return c_query['cardsets'][0] @@ -2315,14 +2321,14 @@ def get_role(ctx, role_name): return discord.utils.get(ctx.guild.roles, name=role_name) -def team_summary_embed(team, ctx, include_roster: bool = True): +async def team_summary_embed(team, ctx, include_roster: bool = True): embed = get_team_embed(f'{team["lname"]} Overview', team) embed.add_field(name='General Manager', value=team['gmname'], inline=False) embed.add_field(name='Wallet', value=f'{team["wallet"]}₼') # embed.add_field(name='Collection Value', value=team['collection_value']) - p_query = db_get('packs', params=[('team_id', team['id']), ('opened', False)]) + p_query = await db_get('packs', params=[('team_id', team['id']), ('opened', False)]) if p_query['count'] > 0: all_packs = {} for x in p_query['packs']: @@ -2339,7 +2345,7 @@ def team_summary_embed(team, ctx, include_roster: bool = True): embed.add_field(name='Unopened Packs', value=pack_string) embed.add_field(name='Team Rating', value=f'{team["ranking"]}') - r_query = db_get(f'results/team/{team["id"]}?season={PD_SEASON}') + r_query = await db_get(f'results/team/{team["id"]}?season={PD_SEASON}') if r_query: embed.add_field( name='Record', @@ -2348,7 +2354,7 @@ def team_summary_embed(team, ctx, include_roster: bool = True): ) # try: - # r_query = db_get('rosters', params=[('team_id', team['id'])]) + # r_query = await db_get('rosters', params=[('team_id', team['id'])]) # if r_query['count']: # embed.add_field(name=f'Rosters', value=f'** **', inline=False) # for roster in r_query['rosters']: @@ -2387,25 +2393,26 @@ def team_summary_embed(team, ctx, include_roster: bool = True): return embed -def give_cards_to_team(team, players: list = None, player_ids: list = None, pack_id=None): +async def give_cards_to_team(team, players: list = None, player_ids: list = None, pack_id=None): if not pack_id: - pack_id = db_post( + p_query = await db_post( 'packs/one', payload={ 'team_id': team['id'], 'pack_type_id': 4, 'open_time': datetime.datetime.timestamp(datetime.datetime.now()) * 1000} - )['id'] + ) + pack_id = p_query['id'] if not players and not player_ids: raise ValueError('One of players or player_ids must be provided to distribute cards') if players: - db_post('cards', payload={'cards': [ + await db_post('cards', payload={'cards': [ {'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': pack_id} for x in players ]}, timeout=10) elif player_ids: - db_post('cards', payload={'cards': [ + await db_post('cards', payload={'cards': [ {'player_id': x, 'team_id': team['id'], 'pack_id': pack_id} for x in player_ids ]}, timeout=10) @@ -2465,8 +2472,8 @@ def get_ratings_guide(sheets): } -def paperdex_cardset_embed(team: dict, this_cardset: dict) -> [discord.Embed]: - all_dex = db_get( +async def paperdex_cardset_embed(team: dict, this_cardset: dict) -> [discord.Embed]: + all_dex = await db_get( 'paperdex', params=[('team_id', team['id']), ('cardset_id', this_cardset['id']), ('flat', True)] ) @@ -2519,7 +2526,7 @@ def paperdex_cardset_embed(team: dict, this_cardset: dict) -> [discord.Embed]: 'total_owned': 0 } - set_players = db_get( + set_players = await db_get( 'players', params=[('cardset_id', this_cardset['id']), ('flat', True), ('inc_dex', False)], timeout=5 @@ -2578,19 +2585,19 @@ def paperdex_cardset_embed(team: dict, this_cardset: dict) -> [discord.Embed]: return display_embeds -def paperdex_team_embed(team: dict, mlb_team: dict) -> [discord.Embed]: - all_dex = db_get( +async def paperdex_team_embed(team: dict, mlb_team: dict) -> [discord.Embed]: + all_dex = await db_get( 'paperdex', params=[('team_id', team['id']), ('franchise', mlb_team['lname']), ('flat', True)] ) dex_player_list = [x['player'] for x in all_dex['paperdex']] - c_query = db_get('cardsets') + c_query = await db_get('cardsets') coll_data = {'total_owned': 0} total_players = 0 for x in c_query['cardsets']: - set_players = db_get( + set_players = await db_get( 'players', params=[('cardset_id', x['id']), ('franchise', mlb_team['lname']), ('flat', True), ('inc_dex', False)] ) @@ -2685,7 +2692,7 @@ async def open_st_pr_packs(all_packs: list, team: dict, context): all_cards = [] for p_id in pack_ids: - new_cards = db_get('cards', params=[('pack_id', p_id)]) + new_cards = await db_get('cards', params=[('pack_id', p_id)]) all_cards.extend(new_cards['cards']) if not all_cards: @@ -2811,7 +2818,7 @@ async def open_choice_pack(this_pack, team: dict, context): rarity_id = 3 else: rarity_id = 2 - pl = db_get( + pl = await db_get( 'players/random', params=[ ('cardset_id', 8), ('min_rarity', rarity_id), ('max_rarity', rarity_id), ('limit', 4) @@ -2830,7 +2837,7 @@ async def open_choice_pack(this_pack, team: dict, context): rarity_id = 3 else: rarity_id = 2 - pl = db_get( + pl = await db_get( 'players/random', params=[ ('min_rarity', rarity_id), ('max_rarity', rarity_id), ('limit', 4), ('in_packs', True), @@ -2845,7 +2852,7 @@ async def open_choice_pack(this_pack, team: dict, context): elif pack_type == 'All Star': rarity_id = 3 - pl = db_get('players/random', params=[ + pl = await db_get('players/random', params=[ ('min_rarity', rarity_id), ('max_rarity', rarity_id), ('limit', 4), ('in_packs', True) ]) @@ -2897,12 +2904,12 @@ async def open_choice_pack(this_pack, team: dict, context): await msg.edit(view=None) try: - give_cards_to_team(team, players=[players[page_num - 1]], pack_id=this_pack['id']) + await give_cards_to_team(team, players=[players[page_num - 1]], pack_id=this_pack['id']) except Exception as e: logging.error(f'failed to create cards: {e}') raise ConnectionError(f'Failed to distribute these cards.') - db_patch('packs', object_id=this_pack['id'], params=[ + await db_patch('packs', object_id=this_pack['id'], params=[ ('open_time', int(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)) ]) await tmp_msg.edit(