Merge pull request #3 from calcorum/buy-pack-update

/buy packs and /open-packs update
This commit is contained in:
Cal Corum 2023-03-11 17:58:24 -06:00 committed by GitHub
commit ac7c98f480
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 581 additions and 1087 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 SelectOpenPack(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)
@ -581,6 +632,223 @@ class SelectPaperdexTeam(discord.ui.Select):
await embed_pagination(team_embeds, interaction.channel, interaction.user)
class SelectBuyPacksCardset(discord.ui.Select):
def __init__(self, team: dict, quantity: int, pack_type_id: int, pack_embed: discord.Embed, cost: int):
options = [
discord.SelectOption(label='2022 Season'),
discord.SelectOption(label='2021 Season'),
discord.SelectOption(label='2019 Season'),
discord.SelectOption(label='2013 Season'),
discord.SelectOption(label='2012 Season')
]
self.team = team
self.quantity = quantity
self.pack_type_id = pack_type_id
self.pack_embed = pack_embed
self.cost = cost
super().__init__(placeholder='Select a Cardset', options=options)
async def callback(self, interaction: discord.Interaction):
logging.info(f'SelectBuyPacksCardset - selection: {self.values[0]}')
cardset_id = None
if self.values[0] == '2022 Season':
cardset_id = 3
elif self.values[0] == '2021 Season':
cardset_id = 1
elif self.values[0] == '2019 Season':
cardset_id = 5
elif self.values[0] == '2013 Season':
cardset_id = 6
elif self.values[0] == '2012 Season':
cardset_id = 7
self.pack_embed.description = f'{self.pack_embed.description} - {self.values[0]}'
view = Confirm(responders=[interaction.user], timeout=30)
await interaction.response.edit_message(
content=None,
embed=self.pack_embed,
view=None
)
question = await interaction.channel.send(
content=f'Your Wallet: {self.team["wallet"]}\n'
f'Pack{"s" if self.quantity > 1 else ""} Price: {self.cost}\n'
f'After Purchase: {self.team["wallet"] - self.cost}\n\n'
f'Would you like to make this purchase?',
view=view
)
await view.wait()
if not view.value:
await question.edit(
content='Saving that money. Smart.',
view=None
)
return
p_model = {
'team_id': self.team['id'],
'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 question.edit(
content=f'{"They are" if self.quantity > 1 else "It is"} all yours! Go rip \'em with `/open-packs`',
view=None
)
class SelectBuyPacksTeam(discord.ui.Select):
def __init__(
self, which: Literal['AL', 'NL'], team: dict, quantity: int, pack_type_id: int, pack_embed: discord.Embed,
cost: int):
self.which = which
self.team = team
self.quantity = quantity
self.pack_type_id = pack_type_id
self.pack_embed = pack_embed
self.cost = cost
if which == 'AL':
options = [
discord.SelectOption(label='Baltimore Orioles'),
discord.SelectOption(label='Boston Red Sox'),
discord.SelectOption(label='Chicago White Sox'),
discord.SelectOption(label='Cleveland Guardians'),
discord.SelectOption(label='Detroit Tigers'),
discord.SelectOption(label='Houston Astros'),
discord.SelectOption(label='Kansas City Royals'),
discord.SelectOption(label='Los Angeles Angels'),
discord.SelectOption(label='Minnesota Twins'),
discord.SelectOption(label='New York Yankees'),
discord.SelectOption(label='Oakland Athletics'),
discord.SelectOption(label='Seattle Mariners'),
discord.SelectOption(label='Tampa Bay Rays'),
discord.SelectOption(label='Texas Rangers'),
discord.SelectOption(label='Toronto Blue Jays')
]
else:
options = [
discord.SelectOption(label='Arizona Diamondbacks'),
discord.SelectOption(label='Atlanta Braves'),
discord.SelectOption(label='Chicago Cubs'),
discord.SelectOption(label='Cincinnati Reds'),
discord.SelectOption(label='Colorado Rockies'),
discord.SelectOption(label='Los Angeles Dodgers'),
discord.SelectOption(label='Miami Marlins'),
discord.SelectOption(label='Milwaukee Brewers'),
discord.SelectOption(label='New York Mets'),
discord.SelectOption(label='Philadelphia Phillies'),
discord.SelectOption(label='Pittsburgh Pirates'),
discord.SelectOption(label='San Diego Padres'),
discord.SelectOption(label='San Francisco Giants'),
discord.SelectOption(label='St. Louis Cardinals'),
discord.SelectOption(label='Washington Nationals')
]
super().__init__(placeholder=f'Select an {which} team', options=options)
async def callback(self, interaction: discord.Interaction):
team_id = None
if self.which == 'AL':
if self.values[0] == 'Baltimore Orioles':
team_id = 3
elif self.values[0] == 'Boston Red Sox':
team_id = 4
elif self.values[0] == 'Chicago White Sox':
team_id = 6
elif self.values[0] == 'Cleveland Guardians':
team_id = 8
elif self.values[0] == 'Detroit Tigers':
team_id = 10
elif self.values[0] == 'Houston Astros':
team_id = 11
elif self.values[0] == 'Kansas City Royals':
team_id = 12
elif self.values[0] == 'Los Angeles Angels':
team_id = 13
elif self.values[0] == 'Minnesota Twins':
team_id = 17
elif self.values[0] == 'New York Yankees':
team_id = 19
elif self.values[0] == 'Oakland Athletics':
team_id = 20
elif self.values[0] == 'Seattle Mariners':
team_id = 24
elif self.values[0] == 'Tampa Bay Rays':
team_id = 27
elif self.values[0] == 'Texas Rangers':
team_id = 28
elif self.values[0] == 'Toronto Blue Jays':
team_id = 29
else:
if self.values[0] == 'Arizona Diamondbacks':
team_id = 1
elif self.values[0] == 'Atlanta Braves':
team_id = 2
elif self.values[0] == 'Chicago Cubs':
team_id = 5
elif self.values[0] == 'Cincinnati Reds':
team_id = 7
elif self.values[0] == 'Colorado Rockies':
team_id = 9
elif self.values[0] == 'Los Angeles Dodgers':
team_id = 14
elif self.values[0] == 'Miami Marlins':
team_id = 15
elif self.values[0] == 'Milwaukee Brewers':
team_id = 16
elif self.values[0] == 'New York Mets':
team_id = 18
elif self.values[0] == 'Philadelphia Phillies':
team_id = 21
elif self.values[0] == 'Pittsburgh Pirates':
team_id = 22
elif self.values[0] == 'San Diego Padres':
team_id = 23
elif self.values[0] == 'San Francisco Giants':
team_id = 25
elif self.values[0] == 'St. Louis Cardinals':
team_id = 26
elif self.values[0] == 'Washington Nationals':
team_id = 30
self.pack_embed.description = f'{self.pack_embed.description} - {self.values[0]}'
view = Confirm(responders=[interaction.user], timeout=30)
await interaction.response.edit_message(
content=None,
embed=self.pack_embed,
view=None
)
question = await interaction.channel.send(
content=f'Your Wallet: {self.team["wallet"]}\n'
f'Pack{"s" if self.quantity > 1 else ""} Price: {self.cost}\n'
f'After Purchase: {self.team["wallet"] - self.cost}\n\n'
f'Would you like to make this purchase?',
view=view
)
await view.wait()
if not view.value:
await question.edit(
content='Saving that money. Smart.',
view=None
)
return
p_model = {
'team_id': self.team['id'],
'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 question.edit(
content=f'{"They are" if self.quantity > 1 else "It is"} all yours! Go rip \'em with `/open-packs`',
view=None
)
class SelectView(discord.ui.View):
def __init__(self, select_objects: [discord.ui.Select], timeout: float = 300.0):
super().__init__(timeout=timeout)
@ -1197,7 +1465,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 +1644,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 +1854,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"]}')
@ -1604,10 +1876,16 @@ async def roll_for_cards(all_packs: list, extra_val=None) -> list:
mvp_flag = None
if counts[key]['count'] > 0:
pl = db_get('players/random', params=[
params = [
('min_rarity', counts[key]['rarity']), ('max_rarity', counts[key]['rarity']),
('limit', counts[key]['count'])
])
]
if all_packs[0]['pack_team'] is not None:
params.append(('franchise', all_packs[0]['pack_team']['lname']))
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)
if pl['count'] != counts[key]['count']:
mvp_flag = counts[key]['count'] - pl['count']
@ -2240,3 +2518,170 @@ 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)
async def confirm_pack_purchase(interaction, owner_team, num_packs, total_cost, pack_embed):
view = Confirm(responders=[interaction.user], timeout=30)
await interaction.edit_original_response(
content=None,
embed=pack_embed
)
question = await interaction.channel.send(
content=f'Your Wallet: {owner_team["wallet"]}\n'
f'Pack{"s" if num_packs > 1 else ""} Price: {total_cost}\n'
f'After Purchase: {owner_team["wallet"] - total_cost}\n\n'
f'Would you like to make this purchase?',
view=view
)
await view.wait()
if not view.value:
await question.edit(
content='Saving that money. Smart.',
view=None
)
return None
else:
return question