Add /open-packs and tweak pull rates for daily

This commit is contained in:
Cal Corum 2023-03-11 14:39:10 -06:00
parent 419a0275d9
commit ee8a332558
2 changed files with 281 additions and 1059 deletions

File diff suppressed because it is too large Load Diff

View File

@ -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)