From ee8a332558da2641712226b17f8fb62ee88a254a Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Sat, 11 Mar 2023 14:39:10 -0600 Subject: [PATCH] Add /open-packs and tweak pull rates for daily --- cogs/economy.py | 1120 +++-------------------------------------------- helpers.py | 220 +++++++++- 2 files changed, 281 insertions(+), 1059 deletions(-) diff --git a/cogs/economy.py b/cogs/economy.py index 941cbb4..47c0b7d 100644 --- a/cogs/economy.py +++ b/cogs/economy.py @@ -490,7 +490,7 @@ class Economy(commands.Cog): await ctx.send(f'I do not see any packs in here. {await get_emoji(ctx, "ConfusedPsyduck")}') return - pack_ids = await roll_for_cards(p_query['packs'], extra_val=check_count) + pack_ids = await roll_for_cards(p_query['packs'], extra_val=check_ins['count']) if not pack_ids: await greeting.edit( content=f'I was not able to create these cards {await get_emoji(ctx, "slight_frown")}' @@ -529,879 +529,92 @@ class Economy(commands.Cog): team = 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"]}₼!') - @commands.hybrid_command(name='open', help='Rip a pack or 7') - @app_commands.describe(pack_type='Name of the pack you\'d like to open (e.g. Standard or Premium)') - @commands.has_any_role(PD_PLAYERS) + @app_commands.command(name='open-packs', description='Open packs from your inventory') + @app_commands.checks.has_any_role(PD_PLAYERS) @commands.check(legal_channel) - async def open_slash( - self, ctx, pack_type: Literal['Standard', 'Premium', 'MVP'], quantity: Literal[1, 2, 3, 4, 5, 6, 7]): - team = 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!', - ephemeral=True + async def open_packs_slash(self, interaction: discord.Interaction): + owner_team = 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('packtypes', params=[('name', pack_type)]) - if not p_query['count']: - await ctx.send(f'I did not find any {pack_type} packs for you.') - return - this_pack_type = p_query['packtypes'][0] - - if this_pack_type['name'] in ['Premium', 'MVP']: - pack_cover = IMAGES['pack-pre'] - elif this_pack_type['name'] == 'Standard': - pack_cover = IMAGES['pack-sta'] - else: - pack_cover = None - - pack_query = db_get('packs', params=[ - ('team_id', team['id']), ('limit', quantity), ('opened', False), ('pack_type_id', this_pack_type['id']) + p_query = db_get('packs', params=[ + ('team_id', owner_team['id']), ('opened', False) ]) - if not pack_query['count']: - content = f'Looks like you are clean out of {this_pack_type["name"]} packs, friendo.' - if pack_type in ['Standard', 'Premium']: - content += 'You can earn them by playing PD games or by donating to the league.' - await ctx.send(content) - return - all_packs = pack_query['packs'] - - greeting = await ctx.send(f'Alright, let me get that pack ready for you...') - - # Get the opening channel - pack_channel = get_channel(ctx, 'pack-openings') - if not pack_channel: - await ctx.send( - content=f'Yikes - I cannot find the pack-openings channel. {get_cal_user(ctx).mention} - halp?' + if p_query['count'] == 0: + await interaction.response.send_message( + f'Looks like you are clean out of packs, friendo. You can earn them by playing PD games or by ' + f'donating to the league.' ) return - if pack_type in ['Standard', 'Premium']: - # Try to open the pack - # Get the cards from the opened pack - pack_ids = await roll_for_cards(all_packs) - if not pack_ids: - await greeting.edit( - content=f'I was not able to create these cards {await get_emoji(ctx, "slight_frown")}' - ) - return + # Group packs by type and customization (e.g. Standard, Standard-Orioles, Standard-2012, Premium) + p_count = 0 + p_data = { + 'Standard': [], + 'Premium': [], + 'Daily': [], + 'MVP': [] + } + for pack in p_query['packs']: + p_group = None + if pack['pack_team'] is None and pack['pack_cardset'] is None: + if pack['pack_type']['name'] == 'Standard': + p_group = 'Standard' + elif pack['pack_type']['name'] == 'Premium': + p_group = 'Premium' + elif pack['pack_type']['name'] == 'MVP': + p_group = 'MVP' - all_cards = [] - for p_id in pack_ids: - new_cards = db_get('cards', params=[('pack_id', p_id)]) - all_cards.extend(new_cards['cards']) + elif pack['pack_team'] is not None: + if pack['pack_type']['name'] == 'Standard': + p_group = f'Standard-Team-{pack["pack_team"]["id"]}-{pack["pack_team"]["sname"]}' + elif pack['pack_type']['name'] == 'Premium': + p_group = f'Premium-Team-{pack["pack_team"]["id"]}-{pack["pack_team"]["sname"]}' - if not all_cards: - await greeting.edit(f'I was not able to pull these cards {await get_emoji(ctx, "slight_frown")}') - return + elif pack['pack_cardset'] is not None: + if pack['pack_type']['name'] == 'Standard': + p_group = f'Standard-Cardset-{pack["pack_cardset"]["id"]}-{pack["pack_cardset"]["name"]}' + elif pack['pack_type']['name'] == 'Premium': + p_group = f'Premium-Cardset-{pack["pack_cardset"]["id"]}-{pack["pack_cardset"]["name"]}' - # Present cards to opening channel - await ctx.send(content=f'Let\'s head down to {pack_channel.mention}!') - async with pack_channel.typing(): - is_done = await display_cards(all_cards, team, pack_channel, ctx.author, self.bot, pack_cover=pack_cover) - - else: - # Get 4 MVP cards - rarity_id = 5 - if pack_type == 'HoF': - rarity_id = 8 - elif pack_type == 'All-Star': - rarity_id = 3 - - pl = db_get('players/random', params=[ - ('min_rarity', rarity_id), ('max_rarity', rarity_id), ('limit', 4) - ]) - if pl['count']: - players = pl['players'] - else: - raise ConnectionError(f'Could not create MVP pack') - - # Display them with pagination, prev/next/select - card_embeds = [ - await get_card_embeds( - {'player': x, 'team': {'lname': 'Paper Dynasty', 'season': PD_SEASON, 'logo': IMAGES['logo']}} - ) for x in players - ] - logging.info(f'card embeds: {card_embeds}') - page_num = 0 - - view = Pagination([ctx.author], timeout=30) - view.left_button.disabled = True - view.left_button.label = f'Prev: -/{len(card_embeds)}' - view.cancel_button.label = f'Take This Card' - view.cancel_button.style = discord.ButtonStyle.success - view.cancel_button.disabled = True - view.right_button.label = f'Next: 1/{len(card_embeds)}' - - # React to selection - await ctx.send(f'Let\'s head down to {pack_channel.mention}!') - msg = await pack_channel.send( - content=None, - embed=image_embed(pack_cover, title=f'{team["lname"]}', desc=f'MVP Pack - Choose 1 of 4 {pack_type}s!'), - view=view - ) - tmp_msg = await pack_channel.send(content=f'@here we\'ve got an MVP!') - - while True: - await view.wait() - - if view.value: - if view.value == 'cancel': - await msg.edit(view=None) - - try: - give_cards_to_team(team, players=[players[page_num - 1]], pack_id=all_packs[0]['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=all_packs[0]['id'], params=[ - ('open_time', int(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)) - ]) - await tmp_msg.edit( - content=f'{players[page_num - 1]["p_name"]} has been added to the ' - f'**{team["sname"]}** binder!' - ) - await refresh_sheet(team, self.bot) - break - if view.value == 'left': - page_num -= 1 if page_num > 1 else len(card_embeds) - if view.value == 'right': - page_num += 1 if page_num < len(card_embeds) else 1 + if p_group is not None: + p_count += 1 + if p_group not in p_data: + p_data[p_group] = pack else: - if page_num == len(card_embeds): - page_num = 1 - else: - page_num += 1 + p_data[p_group].append(pack) - view.value = None + if p_count == 0: + await interaction.response.send_message( + f'Looks like you are clean out of packs, friendo. You can earn them by playing PD games or by ' + f'donating to the league.' + ) + return - view = Pagination([ctx.author], timeout=30) - view.left_button.label = f'Prev: {page_num - 1}/{len(card_embeds)}' - view.cancel_button.label = f'Take This Card' - view.cancel_button.style = discord.ButtonStyle.success - view.right_button.label = f'Next: {page_num + 1}/{len(card_embeds)}' - if page_num == 1: - view.left_button.label = f'Prev: -/{len(card_embeds)}' - view.left_button.disabled = True - elif page_num == len(card_embeds): - view.right_button.label = f'Next: -/{len(card_embeds)}' - view.right_button.disabled = True + # Display options and ask which group to open + embed = get_team_embed(f'Unopened Packs', team=owner_team) + embed.description = owner_team['lname'] + select_options = [] + for key in p_data: + if len(p_data[key]) > 0: + pretty_name = None + # Not a specific pack + if '-' not in key: + pretty_name = key + elif 'Team' in key: + pretty_name = f'{key.split("-")[0]} - {key.split("-")[3]}' + elif 'Cardset' in key: + pretty_name = f'{key.split("-")[0]} - {key.split("-")[3]}' - await msg.edit(content=None, embeds=card_embeds[page_num - 1], view=view) + if pretty_name is not None: + embed.add_field(name=pretty_name, value=f'Qty: {len(p_data[key])}') + select_options.append(discord.SelectOption(label=pretty_name, value=key)) - await refresh_sheet(team, self.bot) - - # @commands.command(name='newteam', aliases=['newseason'], help='New players get your team') - # @commands.has_any_role('Paper Dynasty Players') - # async def starter_team(self, ctx): - # owner_team = Team.get_by_owner(ctx.author.id) - # last_team = Team.get_by_owner(ctx.author.id, Current.get().season - 1) - # current = Current.get() - # get_cards = True - # - # # Check for existing team - # if owner_team: - # await ctx.send(f'Whoa there, bucko. I already have you down as GM of the {owner_team.sname}.') - # return - # - # # Get personal bot channel - # hello_channel = discord.utils.get(ctx.guild.text_channels, name=f'hello-{ctx.author.name}'.lower()) - # if hello_channel: - # op_ch = hello_channel - # else: - # op_ch = await helpers.create_channel_old( - # ctx, - # f'hello-{ctx.author.name}', - # 'Paper Dynasty Team', - # everyone_read=False, - # allowed_members=[ctx.author] - # ) - # - # async def timed_delete(): - # await op_ch.send('Welp, I have to go. If you want to try setting up your team again, hit me up.') - # # await asyncio.sleep(60) - # # await op_ch.delete() - # - # async def create_roster_sheet(team): - # await helpers.pause_then_type( - # op_ch, 'I am going to go create your roster sheet. This will take a few seconds.') - # async with op_ch.typing(): - # sheets = pygsheets.authorize(service_file='storage/paper-dynasty-service-creds.json') - # this_sheet = sheets.drive.copy_file( - # '1Z-g3M_rSnRdr-xjXP0YqxMhnOIGsaUK_2v5M3fUODH8', - # f'{team.lname} Roster Sheet', - # '163QSgtsduyFf67A0IWBFvAwYIpHMz_cD') - # - # return this_sheet - # - # await op_ch.send(f'Hey there, {ctx.author.mention}! I am Paper Domo and I am going to walk you through team ' - # f'creation. I have a series of questions for you about you and your team. Please do not ' - # f'include any special characters in your name or I get a headache and I will take it ' - # f'out on you.') - # await asyncio.sleep(5) - # reuse_team = None - # old_team = None - # logo_url = None - # team_role = None - # reset_packs = 0 - # rollover_standard = 0 - # rollover_premium = 0 - # reset_team = False - # - # # Returning GM - # if last_team: - # prompt = f'Hol up, I know you. You managed the {last_team.sname} last season! Do you want to ' \ - # f'keep this same branding?' - # reuse_q = Question(self.bot, op_ch, prompt, 'yesno', 30) - # reuse_team = await reuse_q.ask([ctx.author]) - # - # if reuse_team is None: - # await op_ch.send('You think on it. I\'ll probably still be here when you decide.') - # return - # - # old_team = Team( - # abbrev=last_team.abbrev, sname=last_team.sname, lname=last_team.lname, - # gmid=ctx.author.id, gmname=last_team.gmname, gsheet=last_team.gsheet, weeklyclaim=False, - # team_value=last_team.team_value, collection_value=last_team.collection_value, - # dailyclaim=False, weeklypacks=0, season=current.season - 1, - # logo=last_team.logo if last_team.logo else None - # ) - # - # # Get unopened packs - # tp_query = (Pack - # .select() - # .where((Pack.team == last_team) & (Pack.card1.is_null()))) - # prem_query = Pack.select().where( - # (Pack.team == last_team) & (Pack.card1.is_null()) & ( - # Pack.pack_type == PackType.get(PackType.name == 'Premium')) - # ) - # rollover_standard = tp_query.count() - prem_query.count() - # rollover_premium = prem_query.count() - # reset_packs += round((last_team.collection_value * 1.0) / 4.5) - # - # reset_prompt = f'Would you like to reset your collection? I will grant you 1 Standard pack for ' \ - # f'every 4.5 CV your team has. You will keep any unopened packs you already have. ' \ - # f'For the {last_team.sname}, that would be {reset_packs} ' \ - # f'pack{"s" if reset_packs > 1 else ""}.' - # reset_q = Question(self.bot, op_ch, reset_prompt, 'yesno', 15) - # reset_team = await reset_q.ask([ctx.author]) - # if reset_team is None: - # await ctx.send('This is a big moment for you. Why don\'t you think on it and get back to me once ' - # 'you\'re ready.') - # return - # - # # Get team branding - # if not reuse_team: - # # They have an old team, but want to rebrand or they did not have a team last year - # # Get GM name - # await op_ch.send('Alrighty, let\'s get you started with your new branding!') - # prompt = f'First, what is your GM name?' - # this_q = Question(self.bot, op_ch, prompt, 'text', 45) - # gm_name = await this_q.ask([ctx.author]) - # - # if not gm_name: - # await timed_delete() - # return - # else: - # gm_name = re.sub(r'\W +', '', gm_name) - # - # # Get team abbreviation - # while True: - # this_q.prompt = f'Alrighty, {gm_name}, what would you like your team\'s 2 or 3 letter abbreviation to be?' - # abbrev = await this_q.ask([ctx.author]) - # - # if not abbrev: - # await timed_delete() - # return - # elif len(abbrev) < 5: - # abbrev = re.sub(r'\W +', '', abbrev) - # if len(abbrev) > 0: - # if not Team.get_season(abbrev): - # abbrev = abbrev.upper() - # break - # else: - # await op_ch.send(f'Oof, {abbrev} is actually already taken.') - # else: - # await op_ch.send( - # 'Once I pulled out special characters, there was nothing left of your abbrev.') - # - # await op_ch.send('Please try again.') - # await asyncio.sleep(1) - # - # # Get team long name - # while True: - # this_q.prompt = f'Got it! What is the full name of {abbrev}? ' \ - # f'Something like Milwaukee Brewers or Baltimore Orioles. (Max of 40 characters)' - # team_lname = await this_q.ask([ctx.author]) - # - # if not team_lname: - # await timed_delete() - # return - # elif len(team_lname) <= 40: - # team_lname = re.sub(r'\W +', '', team_lname) - # if len(team_lname) > 0: - # break - # - # await op_ch.send('Let\'s try that again. Follow the rules this time.') - # await asyncio.sleep(1) - # - # # Get team short name - # while True: - # this_q.prompt = f'Well that is a mouthful. What would {abbrev}\'s short name be? ' \ - # f'Something like Black Bears, Angels, or Crabbers. (Max of 20 characters)' - # team_sname = await this_q.ask([ctx.author]) - # - # if not team_sname: - # await timed_delete() - # return - # elif len(team_sname) <= 20: - # team_sname = re.sub(r'\W +', '', team_sname) - # if len(team_sname) > 0: - # break - # - # await op_ch.send('Let\'s try that again. Follow the rules this time.') - # await asyncio.sleep(1) - # - # # Get team logo - # logo_prompt = f'Do you want to add a team logo? No worries if you don\'t have one now, ' \ - # f'this can be added later.' - # logo_q = Question(self.bot, op_ch, logo_prompt, 'yesno', 15) - # resp = await logo_q.ask([ctx.author]) - # - # if resp: - # while True: - # this_q.prompt = 'Please enter the URL to your logo. If it is an image in discord, right-click and ' \ - # 'click Copy Link and paste that here.' - # logo = await this_q.ask([ctx.author]) - # - # if logo is None: - # await op_ch.send('Let\'s come back to the logo another time.') - # break - # elif ' ' in logo: - # await op_ch.send('Yikes. I am just looking for the URL of your image. It can come from ' - # 'anywhere, but would look something like: `www.website.com/images/path.jpg`') - # else: - # logo_url = logo - # break - # - # if not reset_team: - # # Do not reset team - # owner_team = last_team - # owner_team.season = current.season - # - # if not reuse_team: - # old_team.save() - # owner_team.abbrev = abbrev - # owner_team.sname = team_sname - # owner_team.lname = team_lname - # if logo_url: - # owner_team.logo = logo_url - # team_roster_sheet = await create_roster_sheet(owner_team) - # owner_team.gsheet = team_roster_sheet['id'] - # - # owner_team.save() - # - # team_role = await helpers.get_or_create_role(ctx, owner_team.lname) - # await self.write_collection(op_ch, owner_team) - # await op_ch.send('Alright then you are all set, hoss!') - # get_cards = False - # else: - # if not reuse_team: - # owner_team = Team( - # abbrev=abbrev, sname=team_sname, lname=team_lname, gmid=ctx.author.id, gmname=gm_name - # ) - # if logo_url: - # owner_team.logo = logo_url - # else: - # owner_team = Team( - # abbrev=last_team.abbrev, sname=last_team.sname, lname=last_team.lname, gmid=ctx.author.id, - # gmname=last_team.gmname - # ) - # - # # New GM - # if not last_team: - # # Get GM name - # await op_ch.send('Alrighty, let\'s get you started with your new branding!') - # prompt = f'First, what is your GM name?' - # this_q = Question(self.bot, op_ch, prompt, 'text', 45) - # gm_name = await this_q.ask([ctx.author]) - # - # if not gm_name: - # await timed_delete() - # return - # else: - # gm_name = re.sub(r'\W +', '', gm_name) - # - # # Get team abbreviation - # while True: - # this_q.prompt = f'Alrighty, {gm_name}, what would you like your team\'s 2 or 3 letter abbreviation to be?' - # abbrev = await this_q.ask([ctx.author]) - # - # if not abbrev: - # await timed_delete() - # return - # elif len(abbrev) < 5: - # abbrev = re.sub(r'\W +', '', abbrev) - # if len(abbrev) > 0: - # if not Team.get_season(abbrev): - # abbrev = abbrev.upper() - # break - # else: - # await op_ch.send(f'Oof, {abbrev} is actually already taken.') - # else: - # await op_ch.send( - # 'Once I pulled out special characters, there was nothing left of your abbrev.') - # - # await op_ch.send('Please try again.') - # await asyncio.sleep(1) - # - # # Get team long name - # while True: - # this_q.prompt = f'Got it! What is the full name of {abbrev}? ' \ - # f'Something like Milwaukee Brewers or Baltimore Orioles. (Max of 40 characters)' - # team_lname = await this_q.ask([ctx.author]) - # - # if not team_lname: - # await timed_delete() - # return - # elif len(team_lname) <= 40: - # team_lname = re.sub(r'\W +', '', team_lname) - # if len(team_lname) > 0: - # break - # - # await op_ch.send('Let\'s try that again. Follow the rules this time.') - # await asyncio.sleep(1) - # - # # Get team short name - # while True: - # this_q.prompt = f'Well that is a mouthful. What would {abbrev}\'s short name be? ' \ - # f'Something like Black Bears, Angels, or Crabbers. (Max of 20 characters)' - # team_sname = await this_q.ask([ctx.author]) - # - # if not team_sname: - # await timed_delete() - # return - # elif len(team_sname) <= 20: - # team_sname = re.sub(r'\W +', '', team_sname) - # if len(team_sname) > 0: - # break - # - # await op_ch.send('Let\'s try that again. Follow the rules this time.') - # await asyncio.sleep(1) - # - # # Get team logo - # logo_prompt = f'Do you want to add a team logo? No worries if you don\'t have one now, ' \ - # f'this can be added later.' - # logo_q = Question(self.bot, op_ch, logo_prompt, 'yesno', 15) - # resp = await logo_q.ask([ctx.author]) - # - # if resp: - # while True: - # this_q.prompt = 'Please enter the URL to your logo. If it is an image in discord, right-click and ' \ - # 'click Copy Link and paste that here.' - # logo = this_q.ask([ctx.author]) - # - # if logo is None: - # await op_ch.send('Let\'s come back to the logo another time.') - # break - # elif ' ' in logo: - # await op_ch.send('Yikes. I am just looking for the URL of your image. It can come from ' - # 'anywhere, but would look something like: `www.website.com/images/path.jpg`') - # else: - # logo_url = logo - # break - # - # owner_team = Team( - # abbrev=abbrev, sname=team_sname, lname=team_lname, gmid=ctx.author.id, gmname=gm_name - # ) - # team_roster_sheet = await create_roster_sheet(owner_team) - # owner_team.gsheet = team_roster_sheet['id'] - # - # if get_cards: - # # Get MLB anchor team - # while True: - # prompt = f'Noice. I\'ve got you down as the {owner_team.sname}. Let\'s get you a starter team. ' \ - # f'What MLB club would you like to use as your anchor? Something like MKE, Orioles, or ' \ - # f'Texas Rangers.' - # this_q = Question(self.bot, op_ch, prompt, 'text', 45) - # team_string = await this_q.ask([ctx.author]) - # - # if not team_string: - # await timed_delete() - # return - # - # if team_string.title() in all_mlb_teams.keys(): - # team_choice = team_string.title() - # break - # else: - # match = False - # for x in all_mlb_teams: - # if team_string.upper() in all_mlb_teams[x] or team_string.title() in all_mlb_teams[x]: - # team_choice = x - # match = True - # break - # if match: - # break - # - # await op_ch.send(f'Ope. I don\'t recognize **{team_string}**. I try to recognize abbreviations (BAL), ' - # f'short names (Orioles), and long names ("Baltimore Orioles").') - # - # logging.warning(f'{ctx.author.name} has selected {team_choice}') - # - # team_allstars = Player.select().join(Rarity) \ - # .where((Player.franchise == team_choice) & - # (Player.rarity == Rarity.get(Rarity.name == 'All-Star')) & - # (Player.primary != 'RP')) \ - # .order_by(fn.Random()) - # team_starters = Player.select().join(Rarity) \ - # .where((Player.franchise == team_choice) & - # (Player.rarity == Rarity.get(Rarity.name == 'Starter')) & - # (Player.primary != 'RP')) \ - # .order_by(fn.Random()) - # - # logging.info(f'AS count: {team_allstars.count()}\nSta count: {team_starters.count()}') - # - # # Get anchor players - # roster_counts = { - # 'SP': 0, - # 'RP': 0, - # 'C': 0, - # '1B': 0, - # '2B': 0, - # '3B': 0, - # 'SS': 0, - # 'LF': 0, - # 'CF': 0, - # 'RF': 0, - # 'DH': 0, - # 'Reserve': 0, - # 'Replacement': 0, - # } - # roster_list = [] - # anchor_starters = '' - # if team_allstars.count() > 0: - # # Get anchor team All-Star - # anchor_allstar = None - # for x in team_allstars: - # anchor_allstar = x - # roster_list.append(x) - # roster_counts[x.primary] += 1 - # break - # logging.info(f'Anchor: {anchor_allstar}') - # - # # Get two starters - # starter_pool = Player.select().join(Rarity) \ - # .where(Player.rarity == Player.rarity == Rarity.get(Rarity.name == 'Starter')) \ - # .order_by(fn.Random()).limit(8) - # count = 0 - # for x in starter_pool: - # if roster_counts[x.primary] == 0: - # roster_list.append(x) - # roster_counts[x.primary] += 1 - # anchor_starters += f'{x}\n' - # logging.info(f'Anchor starter: {x}') - # count += 1 - # if count > 1: - # break - # elif team_starters.count() > 1: - # # Get two starters - # logging.info(f'anchor pool: {team_starters}') - # for x in team_starters: - # if roster_counts[x.primary] == 0: - # roster_list.append(x) - # roster_counts[x.primary] += 1 - # logging.info(f'Anchor starter: {x}') - # anchor_starters += f'{x}\n' - # if len(roster_list) >= 2: - # break - # - # # Get anchor All-Star - # anchor_allstar = Player.select().join(Rarity) \ - # .where((Player.rarity == Player.rarity == Rarity.get(Rarity.name == 'All-Star')) & - # (Player.primary != "RP") & - # (Player.primary != "CP")) \ - # .order_by(fn.Random()).limit(5) - # for x in anchor_allstar: - # if roster_counts[x.primary] == 0: - # anchor_allstar = x - # roster_list.append(x) - # roster_counts[x.primary] += 1 - # logging.info(f'Anchor All-Star: {x}') - # break - # else: - # await op_ch.send(f'It pains me to say this, but the {team_choice} don\'t have an All-Star nor do they ' - # f'have two starters to seed your team. Please select another team.') - # return - # logging.info(f'Post anchor roster comp: {roster_counts}') - # - # embed = discord.Embed(title=f'{team_choice} Anchors') - # embed.add_field(name='All-Star', value=f'{anchor_allstar}', inline=False) - # embed.add_field(name='Starters', - # value=anchor_starters, inline=False) - # embed.set_image(url=f'{anchor_allstar.url}') - # await op_ch.send(content=f'{ctx.author.mention}', embed=embed) - # - # # Get 5 SP - # random_sp = (Player - # .select() - # .join(Rarity) - # .where((Player.primary == 'SP') & - # ((Player.rarity == Rarity.get(Rarity.name == 'Replacement')) | - # (Player.rarity == Rarity.get(Rarity.name == 'Reserve')))) - # .order_by(fn.Random()) - # .limit(15)) - # count = 0 - # for x in random_sp: - # if x not in roster_list: - # roster_list.append(x) - # roster_counts[x.primary] += 1 - # roster_counts[x.rarity.name] += 1 - # count += 1 - # if count > 5: - # break - # - # # Get 5 RP - # random_rp = (Player - # .select() - # .join(Rarity) - # .where(((Player.primary == 'RP') | (Player.primary == 'CP')) & - # ((Player.rarity == Rarity.get(Rarity.name == 'Replacement')) | - # (Player.rarity == Rarity.get(Rarity.name == 'Reserve')))) - # .order_by(fn.Random()) - # .limit(15)) - # count = 0 - # for x in random_rp: - # if x not in roster_list: - # roster_list.append(x) - # roster_counts[x.primary] += 1 - # roster_counts[x.rarity.name] += 1 - # count += 1 - # if count > 5: - # break - # - # # Ensure all positions have two players - # for pos in roster_counts.keys(): - # logging.info(f'Starting {pos}') - # if pos == 'DH' or pos == 'Reserve' or pos == 'Replacement': - # pass - # else: - # logging.info(f'{pos} Count: {roster_counts[pos]}') - # while roster_counts[pos] < 2: - # random_draw = (Player - # .select() - # .where((Player.primary == pos) & - # ((Player.rarity == Rarity.get(Rarity.name == 'Replacement')) | - # (Player.rarity == Rarity.get(Rarity.name == 'Reserve')))) - # .order_by(fn.Random()) - # .limit(15)) - # logging.info(f'Replacement count: {roster_counts["Replacement"]}') - # if roster_counts['Replacement'] >= 15: - # for x in random_draw: - # if x.rarity.name == 'Reserve': - # roster_list.append(x) - # roster_counts[x.rarity.name] += 1 - # roster_counts[pos] += 1 - # break - # elif roster_counts['Reserve'] >= 12: - # for x in random_draw: - # if x.rarity.name == 'Replacement': - # roster_list.append(x) - # roster_counts[x.rarity.name] += 1 - # roster_counts[pos] += 1 - # break - # elif roster_counts['Reserve'] < 12 and roster_counts['Replacement'] < 15: - # roster_list.append(random_draw[0]) - # roster_counts[random_draw[0].rarity.name] += 1 - # roster_counts[pos] += 1 - # logging.info(f'Adding {pos}: {roster_list[-1]}') - # logging.info(f'{pos} Count: {roster_counts[pos]}') - # - # logging.info(f'roster_count: {roster_counts}') - # if roster_counts['Reserve'] + roster_counts['Replacement'] < 27: - # random_draw = (Player - # .select() - # .where((Player.rarity == Rarity.get(Rarity.name == 'Replacement')) | - # (Player.rarity == Rarity.get(Rarity.name == 'Reserve'))) - # .order_by(fn.Random()) - # .limit(15)) - # for x in random_draw: - # if x not in roster_list: - # roster_list.append(x) - # roster_counts[x.rarity.name] += 1 - # roster_counts[x.primary] += 1 - # if roster_counts['Reserve'] + roster_counts['Replacement'] >= 27: - # break - # - # logging.info('Building roster list') - # team_cards = [] - # for x in roster_list: - # team_cards.append({ - # 'player': x, - # 'team': owner_team, - # }) - # - # # Create team and starter cards - # logging.info('Create team roster sheet') - # team_roster_sheet = await create_roster_sheet(owner_team) - # - # logging.info('Final owner_team updates') - # owner_team.gsheet = team_roster_sheet['id'] - # owner_team.team_value = 17 - # owner_team.collection_value = 17 - # owner_team.weeklyclaim = False - # owner_team.dailyclaim = False - # owner_team.weeklypacks = 0 - # owner_team.season = current.season - # owner_team.save() - # logging.info('Save all of the cards') - # with db.atomic(): - # try: - # for batch in chunked(team_cards, 20): - # Card.insert_many(batch).execute() - # except Exception as e: - # error = f'**INSERT ERROR (cards):** {type(e).__name__} - {e}' - # logging.error(error) - # await op_ch.send(f'Jinkies, guys. I\'ve got an ugly error:\n\n{e}') - # return - # - # # Create default roster - # try: - # current_roster = helpers.get_sorted_collection(owner_team) - # roster_query = Roster.replace( - # team=owner_team, - # season=Current.get_by_id(1).season, - # card1=current_roster[0], - # card2=current_roster[1], - # card3=current_roster[2], - # card4=current_roster[3], - # card5=current_roster[4], - # card6=current_roster[5], - # card7=current_roster[6], - # card8=current_roster[7], - # card9=current_roster[8], - # card10=current_roster[9], - # card11=current_roster[10], - # card12=current_roster[11], - # card13=current_roster[12], - # card14=current_roster[13], - # card15=current_roster[14], - # card16=current_roster[15], - # card17=current_roster[16], - # card18=current_roster[17], - # card19=current_roster[18], - # card20=current_roster[19], - # card21=current_roster[20], - # card22=current_roster[21], - # card23=current_roster[22], - # card24=current_roster[23], - # card25=current_roster[24], - # card26=current_roster[25], - # ) - # roster_query.execute() - # except Exception as e: - # error = f'**INSERT ERROR (rosters):** {type(e).__name__} - {e}' - # logging.error(error) - # await op_ch.send(f'Jinkies, guys. I\'ve got an ugly error:\n\n{e}') - # return - # - # # Create team role - # team_role = await ctx.guild.create_role(name=f'{owner_team.lname}', mentionable=True) - # await ctx.author.add_roles(team_role, atomic=True) - # - # # Present starting roster - # sp_list = [] - # rp_list = [] - # if_list = [] - # of_list = [] - # - # for x in roster_list: - # if x.primary == 'SP': - # sp_list.append(x) - # elif x.primary == 'RP': - # rp_list.append(x) - # elif x.primary == 'C' or x.primary == '1B' or x.primary == '2B' or x.primary == '3B' or x.primary == 'SS': - # if_list.append(x) - # elif x.primary == 'LF' or x.primary == 'CF' or x.primary == 'RF' or x.primary == 'DH': - # of_list.append(x) - # sp_list.sort(key=lambda x: x.wara) - # rp_list.sort(key=lambda x: x.wara) - # if_list.sort(key=lambda x: x.wara) - # of_list.sort(key=lambda x: x.wara) - # - # # Give ballparks - # default_park = Player.get(Player.cardset == '2018', Player.name == 'Atlanta Ballpark') - # random_park = Player.select().where( - # (Player.rarity == Rarity.get(Rarity.name == 'Replacement')) & (Player.primary == 'Park') & - # (Player.name != 'Atlanta Ballpark') - # ).order_by(fn.Random())[0] - # - # park_card = Card( - # player=default_park, - # team=owner_team - # ) - # park_card.save() - # park_card1 = Card( - # player=random_park, - # team=owner_team - # ) - # park_card1.save() - # db.close() - # - # await op_ch.send('**First up, you start with two ballparks:**') - # for x in [park_card, park_card1]: - # await self.present_player(ctx, op_ch, x) - # async with op_ch.typing(): - # await asyncio.sleep(3) - # - # await helpers.pause_then_type(op_ch, '**Now for your roster! Here are your starting pitchers:**') - # for x in sp_list: - # await self.present_player(ctx, op_ch, Card.get(Card.player == x)) - # async with op_ch.typing(): - # await asyncio.sleep(8) - # - # await op_ch.send('**Next we\'ve got your bullpen:**') - # for x in rp_list: - # await self.present_player(ctx, op_ch, Card.get(Card.player == x)) - # async with op_ch.typing(): - # await asyncio.sleep(8) - # - # await op_ch.send('**Here are your infielders:**') - # for x in if_list: - # await self.present_player(ctx, op_ch, Card.get(Card.player == x)) - # async with op_ch.typing(): - # await asyncio.sleep(8) - # - # await op_ch.send('**Finally, here are your outfielders:**') - # for x in of_list: - # await self.present_player(ctx, op_ch, Card.get(Card.player == x)) - # async with op_ch.typing(): - # await asyncio.sleep(8) - # - # logging.info(f'roster_count: {roster_counts}') - # - # async with op_ch.typing(): - # await self.write_collection(op_ch, owner_team, 0) - # - # embed = helpers.get_active_roster(owner_team, f'{self.bot.get_user(owner_team.gmid).avatar_url}') - # await helpers.send_to_news(ctx, f'A new challenger approaches...', embed) - # - # if reset_team: - # self.give_pack(owner_team, rollover_standard, 'Standard') - # self.give_pack(owner_team, rollover_premium, 'Premium') - # self.give_pack(owner_team, reset_packs, 'Standard') - # await op_ch.send(f'Here is your roster sheet: {helpers.get_roster_sheet_legacy(owner_team)}') - # await helpers.pause_then_type(op_ch, f'{team_role.mention} \nThis is your personal bot channel. ' - # f'Good luck this season!') - # if owner_team.logo: - # thumb = owner_team.logo - # else: - # thumb = self.bot.get_user(owner_team.gmid).avatar_url - # await op_ch.send(content=None, embed=helpers.get_active_roster(owner_team, thumb)) - # - # helpers.collection_to_paperdex(owner_team) - # db.close() + view = SelectView(select_objects=[SelectPackChoice(select_options)], timeout=15) + await interaction.response.send_message(embed=embed, view=view) group_buy = app_commands.Group(name='buy', description='Make a purchase from the marketplace') @@ -2154,21 +1367,6 @@ class Economy(commands.Cog): await ctx.send(f'All done! I added {total_cards} across {total_teams} teams.') - # @app_commands.command(name='sharepd', description='Have your Paper Dynasty team sheet shared with you') - # @app_commands.checks.has_any_role(PD_PLAYERS) - # async def share_sheet_slash(self, interaction: discord.Interaction): - # team = get_team_by_owner(interaction.user.id) - # if not team: - # await interaction.user.send_message( - # f'You...do I know you? I don\'t think I do. Go on and git.', - # ephemeral=True - # ) - # return - # - # await interaction.response.send_modal( - # Email(title='Google Sheets Email Address', timeout=30, custom_id=team['id']) - # ) - @commands.hybrid_command(name='newsheet', help='Link a new team sheet with your team') @commands.has_any_role(PD_PLAYERS) async def share_sheet_command( @@ -2392,182 +1590,6 @@ class Economy(commands.Cog): pack_name='Standard Pack' ) - # @commands.command(name='deleteteam', help='Remove your team from the league', hidden=True) - # @commands.is_owner() - # async def delete_team(self, ctx): - # team = Team.get_by_owner(ctx.author.id) - # if not team: - # await ctx.send('Now you wait just a second. You don\'t have a team!') - # return - # - # await ctx.send('Are you sure you want to delete your team and full collection?\n\nType \'YES\' to confirm.') - # - # def confirmation_check(mes): - # return mes.author == ctx.author and mes.content.upper() == 'YES' - # - # try: - # confirm_resp = await self.bot.wait_for('message', check=confirmation_check, timeout=10.0) - # roster = Roster.delete().where(Roster.team == team) - # all_packs = Pack.delete().where(Pack.team == team) - # all_cards = Card.delete().where(Card.team == team) - # - # roster.execute() - # all_packs.execute() - # all_cards.execute() - # team.delete_instance() - # - # await helpers.pause_then_type(ctx, 'All done. It\'s like you were never here.') - # except TimeoutError: - # return - # - # db.close() - - # @commands.command(name='addmlbteams', help='Create MLB teams and roster sheets', hidden=True) - # @commands.is_owner() - # async def add_mlb_teams(self, ctx: commands.Context): - # current = db_get('current') - # - # all_teams = [ - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # {'lname': asdfasdf, 'sname': asdfasdf, 'color': asdfasdf, 'abbrev': asdf, 'logo': asdfasdf}, - # # 'Arizona Diamondbacks': ['ARI', 'Diamondbacks'], - # # 'Atlanta Braves': ['ATL', 'MLN', 'Braves'], - # # 'Baltimore Orioles': ['BAL', 'Orioles'], - # # 'Boston Red Sox': ['BOS', 'Red Sox'], - # # 'Chicago Cubs': ['CHC', 'Cubs'], - # # 'Chicago White Sox': ['CHW', 'White Sox'], - # # 'Cincinnati Reds': ['CIN', 'Reds'], - # # 'Cleveland Indians': ['CLE', 'Indians'], - # # 'Colorado Rockies': ['COL', 'Rockies'], - # # 'Detroit Tigers': ['DET', 'Tigers'], - # # 'Houston Astros': ['HOU', 'Astros'], - # # 'Kansas City Royals': ['KCR', 'Royals'], - # # 'Los Angeles Angels': ['LAA', 'CAL', 'Angels'], - # # 'Los Angeles Dodgers': ['LAD', 'Dodgers'], - # # 'Miami Marlins': ['MIA', 'Marlins'], - # # 'Milwaukee Brewers': ['MIL', 'MKE', 'Brewers'], - # # 'Minnesota Twins': ['MIN', 'Twins'], - # # 'New York Mets': ['NYM', 'Mets'], - # # 'New York Yankees': ['NYY', 'Yankees'], - # # 'Oakland Athletics': ['OAK', 'Athletics'], - # # 'Philadelphia Phillies': ['PHI', 'Phillies'], - # # 'Pittsburgh Pirates': ['PIT', 'Pirates'], - # # 'San Diego Padres': ['SDP', 'Padres'], - # # 'Seattle Mariners': ['SEA', 'Mariners'], - # # 'San Francisco Giants': ['SFG', 'Giants'], - # # 'St Louis Cardinals': ['STL', 'Cardinals'], - # # 'Tampa Bay Rays': ['TBR', 'Rays'], - # # 'Texas Rangers': ['TEX', 'Senators', 'Rangers'], - # # 'Toronto Blue Jays': ['TOR', 'Jays'], - # # 'Washington Nationals': ['WSN', 'WAS', 'Nationals'], - # ] - # - # for team in all_teams: - # async with ctx.typing(): - # this_sheet = create_team_sheet(team, current, self.bot) - # - # try: - # new_team = db_post('teams', payload={ - # 'abbrev': team['abbrev'], - # 'sname': team['sname'], - # 'lname': team['lname'], - # 'gmid': 69420, - # 'gmname': team['sname'], - # 'gsheet': this_sheet['id'], - # 'season': current['season'], - # 'wallet': 100, - # 'color': team['color'], - # 'logo': team['logo'], - # }) - # # TODO: Create cards for team players - # except ValueError as e: - # await ctx.send(f'Oh man, I wasn\'t able to create the {team["sname"]}.') - # return - - # @commands.command(name='redeem', help='Redeem a special deal') - # @commands.has_any_role('Paper Dynasty Players') - # async def redeem_special_command(self, ctx, special_id): - # if not await legal_channel(ctx): - # await ctx.send('Slide on down to the pd-bot-hole ;)') - # return - # - # team = Team.get_by_owner(ctx.author.id) - # if not team: - # await ctx.send('Now you wait just a second. You don\'t have a team!') - # return - # - # try: - # this_special = Special.get_by_id(special_id) - # except: - # await ctx.send('I don\'t see a special with that ID available right now.') - # return - # - # await ctx.send(content=None, embed=helpers.get_special_embed(this_special)) - # await ctx.send('Please type \'YES\' to confirm:') - # - # def confirmation(mes): - # logging.error(f'Content: {mes.content} / Author: {mes.author} / Match?: {mes.author == ctx.author}') - # return mes.author == ctx.author and mes.content.upper() == 'YES' - # - # try: - # resp = await self.bot.wait_for('message', check=confirmation, timeout=10.0) - # except TimeoutError: - # await ctx.send('Maybe next time :)') - # return - # except Exception as e: - # await ctx.send(f'Uhh...do you know what this means?\n\n{e}') - # return - # - # # Manual stuff down here to run redemptions - # # TODO: Automate this - # - # if 'Weekly Standings' in this_special.name and team.dailyclaim: - # await ctx.send('Congrats! You have an All-Star coming your way. Let\'s see who we\'ve got...') - # this_player = Player.get_random_or_none(Rarity.get_or_none(Rarity.name == 'All-Star')) - # new_card = Card(player=this_player, team=team) - # new_card.save() - # - # team.dailyclaim = 0 - # team.save() - # - # await self.present_player(ctx, ctx, new_card) - # await helpers.send_to_news( - # ctx, - # f'The {team.sname} just got {this_player.cardset} {this_player.name} ' - # f'for their week {Current.get().week - 1} standings win!', - # None - # ) - # - # db.close() - async def setup(bot): await bot.add_cog(Economy(bot)) diff --git a/helpers.py b/helpers.py index 78ae4ba..f60fdcb 100644 --- a/helpers.py +++ b/helpers.py @@ -436,6 +436,54 @@ class Pagination(discord.ui.View): self.stop() +class SelectPackChoice(discord.ui.Select): + def __init__(self, options: list): + super().__init__(placeholder='Select a Pack Type', options=options) + + async def callback(self, interaction: discord.Interaction): + logging.info(f'SelectPackChoice - selection: {self.values[0]}') + pack_vals = self.values[0].split('-') + + # Get the owner's team + owner_team = get_team_by_owner(interaction.user.id) + + # Get the selected packs + params = [('team_id', owner_team['id']), ('opened', False), ('limit', 5)] + + open_type = 'standard' + if 'Standard' in pack_vals: + open_type = 'standard' + params.append(('pack_type_id', 1)) + elif 'Premium' in pack_vals: + open_type = 'standard' + params.append(('pack_type_id', 3)) + elif 'Daily' in pack_vals: + params.append(('pack_type_id', 4)) + elif 'MVP' in pack_vals: + open_type = 'choice' + params.append(('pack_type_id', 5)) + else: + raise KeyError(f'Cannot identify pack details: {pack_vals}') + + if 'Team' in pack_vals: + params.append(('pack_team_id', pack_vals[2])) + elif 'Cardset' in pack_vals: + params.append(('pack_cardset_id', pack_vals[2])) + + p_query = 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') + + await interaction.response.edit_message(view=None) + + # Open the packs + if open_type == 'standard': + await open_st_pr_packs(p_query['packs'], owner_team, interaction) + elif open_type == 'choice': + await open_choice_pack(p_query['packs'][0], owner_team, interaction) + + class SelectPaperdexCardset(discord.ui.Select): def __init__(self): options = [ @@ -443,7 +491,8 @@ class SelectPaperdexCardset(discord.ui.Select): discord.SelectOption(label='2022 Promos'), discord.SelectOption(label='2021 Season'), discord.SelectOption(label='2019 Season'), - discord.SelectOption(label='2013 Season') + discord.SelectOption(label='2013 Season'), + discord.SelectOption(label='2012 Season') ] super().__init__(placeholder='Select a Cardset', options=options) @@ -460,6 +509,8 @@ class SelectPaperdexCardset(discord.ui.Select): cardset_id = 5 elif self.values[0] == '2013 Season': cardset_id = 6 + elif self.values[0] == '2012 Season': + cardset_id = 7 c_query = db_get('cardsets', object_id=cardset_id, none_okay=False) await interaction.response.edit_message(content=f'Okay, sifting through your cards...', view=None) @@ -1197,7 +1248,7 @@ def is_shiny(card): async def display_cards( - cards: list, team: dict, channel, user, bot, pack_cover: str = None, cust_message: str = None, + cards: list, team: dict, channel, user, bot=None, pack_cover: str = None, cust_message: str = None, add_roster: bool = True, pack_name: str = None) -> bool: cards.sort(key=lambda x: x['player']['rarity']['value']) card_embeds = [await get_card_embeds(x) for x in cards] @@ -1376,7 +1427,7 @@ async def bad_channel(ctx): return False -def get_channel(ctx, name): +def get_channel(ctx, name) -> Optional[discord.TextChannel]: channel = discord.utils.get( ctx.guild.text_channels, name=name @@ -1586,15 +1637,19 @@ async def roll_for_cards(all_packs: list, extra_val=None) -> list: elif pack['pack_type']['name'] == 'Check-In Player': logging.info(f'Building Check-In Pack // extra_val (type): {extra_val} {type(extra_val)}') # Single Card - d_1000 = random.randint(1, 1000) + mod = 0 + if isinstance(extra_val, int): + mod = extra_val + d_1000 = random.randint(1, 1000 + mod) - if not extra_val or not isinstance(extra_val, int): + if d_1000 >= 1100: + counts['All']['count'] += 1 + elif d_1000 >= 1000: + counts['Sta']['count'] += 1 + elif d_1000 >= 500: + counts['Res']['count'] += 1 + else: counts['Rep']['count'] += 1 - elif extra_val < 999: - if d_1000 <= 500: - counts['Rep']['count'] += 1 - else: - counts['Res']['count'] += 1 else: raise TypeError(f'Pack type not recognized: {pack["pack_type"]["name"]}') @@ -2240,3 +2295,148 @@ def paperdex_team_embed(team: dict, mlb_team: dict) -> [discord.Embed]: display_embeds.append(coll_data[cardset_id]['embeds'][0]) return display_embeds + + +def get_pack_cover(pack): + if pack['pack_type']['name'] in ['Premium', 'MVP']: + return IMAGES['pack-pre'] + elif pack['pack_type']['name'] == 'Standard': + return IMAGES['pack-sta'] + else: + return None + + +async def open_st_pr_packs(all_packs: list, team: dict, context): + pack_channel = get_channel(context, 'pack-openings') + pack_cover = get_pack_cover(all_packs[0]) + + if pack_cover is None: + pack_channel = context.channel + + if not pack_channel: + raise ValueError(f'I cannot find the pack-openings channel. {get_cal_user(context).mention} - halp?') + + pack_ids = await roll_for_cards(all_packs) + if not pack_ids: + logging.error(f'open_packs - unable to roll_for_cards for packs: {all_packs}') + raise ValueError(f'I was not able to unpack these cards') + + all_cards = [] + for p_id in pack_ids: + new_cards = db_get('cards', params=[('pack_id', p_id)]) + all_cards.extend(new_cards['cards']) + + if not all_cards: + logging.error(f'open_packs - unable to get cards for packs: {pack_ids}') + raise ValueError(f'I was not able to display these cards') + + # Present cards to opening channel + if type(context) == commands.Context: + author = context.author + else: + author = context.user + + await context.channel.send(content=f'Let\'s head down to {pack_channel.mention}!') + await display_cards(all_cards, team, pack_channel, author, pack_cover=pack_cover) + + +async def open_choice_pack(this_pack, team: dict, context): + pack_channel = get_channel(context, 'pack-openings') + pack_cover = get_pack_cover(this_pack) + pack_type = this_pack['pack_type']['name'] + + # Get 4 MVP cards + rarity_id = 5 + if pack_type == 'HoF': + rarity_id = 8 + elif pack_type == 'All-Star': + rarity_id = 3 + + pl = db_get('players/random', params=[ + ('min_rarity', rarity_id), ('max_rarity', rarity_id), ('limit', 4) + ]) + if pl['count']: + players = pl['players'] + else: + raise ConnectionError(f'Could not create MVP pack') + + if type(context) == commands.Context: + author = context.author + else: + author = context.user + + # Display them with pagination, prev/next/select + card_embeds = [ + await get_card_embeds( + {'player': x, 'team': {'lname': 'Paper Dynasty', 'season': PD_SEASON, 'logo': IMAGES['logo']}} + ) for x in players + ] + logging.info(f'card embeds: {card_embeds}') + page_num = 0 + + view = Pagination([author], timeout=30) + view.left_button.disabled = True + view.left_button.label = f'Prev: -/{len(card_embeds)}' + view.cancel_button.label = f'Take This Card' + view.cancel_button.style = discord.ButtonStyle.success + view.cancel_button.disabled = True + view.right_button.label = f'Next: 1/{len(card_embeds)}' + + # React to selection + await context.channel.send(f'Let\'s head down to {pack_channel.mention}!') + msg = await pack_channel.send( + content=None, + embed=image_embed(pack_cover, title=f'{team["lname"]}', desc=f'{pack_type} Pack - Choose 1 of 4 {pack_type}s!'), + view=view + ) + tmp_msg = await pack_channel.send(content=f'@here we\'ve got an MVP!') + + while True: + await view.wait() + + if view.value: + if view.value == 'cancel': + await msg.edit(view=None) + + try: + 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=[ + ('open_time', int(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)) + ]) + await tmp_msg.edit( + content=f'{players[page_num - 1]["p_name"]} has been added to the ' + f'**{team["sname"]}** binder!' + ) + break + if view.value == 'left': + page_num -= 1 if page_num > 1 else len(card_embeds) + if view.value == 'right': + page_num += 1 if page_num < len(card_embeds) else 1 + else: + if page_num == len(card_embeds): + page_num = 1 + else: + page_num += 1 + + view.value = None + + view = Pagination([author], timeout=30) + view.left_button.label = f'Prev: {page_num - 1}/{len(card_embeds)}' + view.cancel_button.label = f'Take This Card' + view.cancel_button.style = discord.ButtonStyle.success + view.right_button.label = f'Next: {page_num + 1}/{len(card_embeds)}' + if page_num == 1: + view.left_button.label = f'Prev: -/{len(card_embeds)}' + view.left_button.disabled = True + elif page_num == len(card_embeds): + view.right_button.label = f'Next: -/{len(card_embeds)}' + view.right_button.disabled = True + + await msg.edit(content=None, embeds=card_embeds[page_num - 1], view=view) + + +