paper-dynasty-discord/cogs/economy.py
2023-02-19 21:34:38 -06:00

2574 lines
115 KiB
Python

import helpers
from helpers import *
import logging
import os
import random
import re
import discord
import asyncio
from discord.ext import commands, tasks
from discord.ext.commands import Greedy
from discord import app_commands, Member
from typing import Optional, Literal
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 help_text import *
# date = f'{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}'
# logging.basicConfig(
# filename=f'logs/{date}.log',
# format='%(asctime)s - %(levelname)s - %(message)s',
# level=logging.WARNING
# )
# async def legal_channel(ctx):
# bad_channels = ['paper-dynasty-chat', 'pd-news-ticker']
# if ctx.message.channel.name in bad_channels:
# raise discord.ext.commands.CheckFailure(f'Slide on down to the {get_channel(ctx, "pd-bot-hole").mention} ;)')
# else:
# return True
class Economy(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.daily_message_sent = True
self.weekly_update = False
bot.tree.on_error = self.on_app_command_error
# self.pd_ticker.start()
self.notif_check.start()
# def cog_unload(self):
# self.pd_ticker.cancel()
async def cog_command_error(self, ctx, error):
await ctx.send(f'{error}\n\nRun .help <command_name> to see the command requirements')
async def on_app_command_error(self, interaction: discord.Interaction, error: discord.app_commands.AppCommandError):
await interaction.channel.send(f'{error}')
# async def slash_error(self, ctx, error):
# await ctx.send(f'{error}')
# @tasks.loop(minutes=10)
# async def pd_ticker(self):
# now = datetime.datetime.now()
# logging.info(f'Datetime: {now} / weekday: {now.weekday()}')
# guild = self.bot.get_guild(int(os.environ.get('GUILD_ID')))
# if not guild:
# return
#
# # Daily Specials Message
# if now.hour == 11 and not self.daily_message_sent:
# try:
# await helpers.send_to_channel(self.bot, 'pd-bot-hole', 'Here are the current specials:')
# await self.display_specials('pd-bot-hole')
# self.daily_message_sent = True
# except:
# await helpers.send_to_channel(self.bot, 'commissioners-office',
# 'Just tried and failed to send specials to news.')
# elif now.hour == 12 and self.daily_message_sent:
# self.daily_message_sent = False
#
# # Weekly Standings Message
# # if now.hour == 20 and not self.weekly_update:
# if now.weekday() == 0 and now.hour == 0 and not self.weekly_update:
# current = Current.get()
#
# # Send standings to Cal
# standings_embeds = self.bot.get_cog('Players').get_standings_embeds(
# current, 'week', f'Week {current.week} Standings'
# )
# await helpers.send_to_channel(
# self.bot, 'pd-news-ticker',
# content=f'Here are the final standings for week {current.week}! Cal will hand out packs in the morning.'
# )
# for x in standings_embeds:
# await helpers.send_to_channel(self.bot, 'commissioners-office', content=None, embed=x)
# await helpers.send_to_channel(self.bot, 'pd-news-ticker', content=None, embed=x)
#
# # Increment Week
# current.week += 1
# current.save()
#
# all_teams = Team.select()
# for x in all_teams:
# x.weeklyclaim = False
# x.dailyclaim = False
# x.weeklypacks = 0
# x.save()
#
# await helpers.send_to_channel(
# self.bot,
# 'commissioners-office',
# f'Flipped the week to {current.week} and updated {all_teams.count()} teams for their weekly.'
# )
# self.weekly_update = True
# elif now.weekday() != 0 and self.weekly_update:
# self.weekly_update = False
#
# db.close()
@tasks.loop(minutes=10)
async def notif_check(self):
guild = self.bot.get_guild(int(os.environ.get('GUILD_ID')))
if not guild:
logging.error(f'Cannot access guild; pausing for 15 seconds')
await asyncio.sleep(15)
guild = self.bot.get_guild(int(os.environ.get('GUILD_ID')))
if not guild:
logging.error(f'Still cannot access guild; trying again in 10 minutes')
return
# Check for notifications
all_notifs = db_get('notifs', params=[('ack', False)])
if not all_notifs:
logging.debug(f'No notifications')
return
topics = {
'Price Change': {
'channel_name': 'pd-market-watch',
'desc': 'Modified by buying and selling',
'notifs': []
},
'Rare Pull': {
'channel_name': 'pd-network-news',
'desc': 'MVP and All-Star cards pulled from packs',
'notifs': []
}
}
for line in all_notifs['notifs']:
if line['title'] in topics:
topics[line['title']]['notifs'].append(line)
logging.debug(f'topics:\n{topics}')
for topic in topics:
embed = get_team_embed(title=f'{topic}{"s" if len(topics[topic]["notifs"]) > 1 else ""}')
embed.description = topics[topic]['desc']
p_list = {}
if topics[topic]['notifs']:
for x in topics[topic]['notifs']:
if x['field_name'] not in p_list:
p_list[x['field_name']] = {
'field_name': x['field_name'],
'message': f'{x["message"]}'
}
else:
p_list[x['field_name']]['message'] += f'\n{x["message"]}'
db_patch('notifs', object_id=x['id'], params=[('ack', True)])
logging.debug(f'p_list: {p_list}')
for player in p_list:
embed.add_field(name=p_list[player]['field_name'], value=p_list[player]['message'], inline=False)
await send_to_channel(self.bot, topics[topic]['channel_name'], embed=embed)
@commands.hybrid_group(name='help-pd', help='FAQ for Paper Dynasty and the bot', aliases=['helppd'])
@commands.check(legal_channel)
async def pd_help_command(self, ctx: commands.Context):
if ctx.invoked_subcommand is None:
embed = get_team_embed(f'Paper Dynasty Help')
embed.description = 'Frequently Asked Questions'
embed.add_field(
name='What the Heck is Paper Dynasty',
value=f'Well, whipper snapper, have a seat and I\'ll tell you. We\'re running a diamond dynasty / '
f'perfect team style game with electronic card and dice baseball!\n\nGet a starter pack, play '
f'games at your leisure either solo or against another player, and collect cards from the '
f'custom 2021 player set.',
inline=False
)
embed.add_field(
name='How Do I Get Started',
value=f'Run the `.in` command - that\'s a period followed by the word "in". That\'ll get you the '
f'Paper Dynasty Players role so you can run all of the other PD commands!\n\nOnce you get your '
f'role, run `/newteam` and follow the prompts to get your starter team.',
inline=False
)
embed.add_field(
name='How Do I Play',
value='A step-by-step of how to play was written by Riles [starting here](https://discord.com/channels'
'/613880856032968834/633456305830625303/985968300272001054). '
'In addition, you can find the Rules Reference [right here](https://docs.google.com/document/d/'
'1yGZcHy9zN2MUi4hnce12dAzlFpIApbn7zR24vCkPl1o).\n\nThere are three key differences from league '
'play:\n1) Injuries: there are no injuries in Paper Dynasty!\n2) sWAR: there is no sWAR "salary '
'cap" for your team like in league play. Some events will have roster construction rules to '
'follow, though!\n3) The Universal DH is in effect; teams may forfeit the DH at their '
'discretion.',
inline=False
)
await ctx.send(
content=None,
embed=embed
)
@pd_help_command.command(name='start', help='FAQ for Paper Dynasty and the bot', aliases=['faq'])
@commands.check(legal_channel)
async def help_faq(self, ctx: commands.Context):
embed = get_team_embed(f'Paper Dynasty Help')
embed.description = 'Frequently Asked Questions'
embed.add_field(
name='What the Heck is Paper Dynasty',
value=HELP_START_WHAT,
inline=False
)
embed.add_field(
name='How Do I Get Started',
value=HELP_START_HOW,
inline=False
)
embed.add_field(
name='How Do I Play',
value=HELP_START_PLAY,
inline=False
)
embed.add_field(
name='Other Questions?',
value=f'Feel free to ask any questions down in {get_channel(ctx, "paper-dynasty-chat")} or check out '
f'the other `/help-pd` commands for the FAQs!'
)
await ctx.send(
content=None,
embed=embed
)
@pd_help_command.command(name='links', help='Helpful links for Paper Dynasty')
@commands.check(legal_channel)
async def help_links(self, ctx: commands.Context):
current = db_get('current')
embed = get_team_embed(f'Paper Dynasty Help')
embed.description = 'Resources & Links'
embed.add_field(
name='Team Sheet Template',
value=f'{get_roster_sheet({"gsheet": current["gsheet_template"]}, allow_embed=True)}'
)
embed.add_field(
name='Paper Dynasty Season 4 Guidelines',
value='https://docs.google.com/document/d/1b2_eUWaIhdGgD9DapvZrppu5famukqYKTC4wu2DyyFY/edit?usp=sharing',
inline=False
)
embed.add_field(
name='Rules Reference',
value='https://docs.google.com/document/d/1yGZcHy9zN2MUi4hnce12dAzlFpIApbn7zR24vCkPl1o',
inline=False
)
embed.add_field(
name='Changelog',
value='https://manticorum.notion.site/Paper-Dynasty-Season-4-Changelog-75b5e51ab4f246a9b6a3f69df9745d53',
inline=False
)
await ctx.send(content=None, embed=embed)
@pd_help_command.command(name='rewards', help='How to Earn Rewards in Paper Dynasty')
@commands.check(legal_channel)
async def help_rewards(self, ctx: commands.Context):
embed = get_team_embed(f'Paper Dynasty Help')
embed.description = 'How to Earn Rewards'
embed.add_field(
name='Premium Pack',
value=HELP_REWARDS_PREMIUM,
inline=False
)
embed.add_field(
name='Standard Pack',
value=HELP_REWARDS_STANDARD,
inline=False
)
embed.add_field(
name='MantiBucks ₼',
value=HELP_REWARDS_MONEY,
inline=False
)
embed.add_field(
name='Ko-fi Shop',
value=HELP_REWARDS_SHOP,
inline=False
)
await ctx.send(content=None, embed=embed)
@pd_help_command.command(name='team-sheet', help='How to Use Your Team Sheet')
@commands.check(legal_channel)
async def help_team_sheet(self, ctx: commands.Context):
embed = get_team_embed(f'Paper Dynasty Help')
embed.description = 'How to Use Your Team Sheet'
embed.add_field(
name='Your Dashboard',
value=HELP_TS_DASH,
inline=False
)
embed.add_field(
name='Roster Management',
value=HELP_TS_ROSTER,
inline=False
)
embed.add_field(
name='Marketplace',
value=HELP_TS_MARKET,
inline=False
)
embed.add_field(
name='Paper Dynasty Menu',
value=HELP_TS_MENU,
inline=False
)
embed.set_footer(
text='More details to come',
icon_url=IMAGES['logo']
)
await ctx.send(content=None, embed=embed)
@pd_help_command.command(name='gameplay', help='How to Play Paper Dynasty')
@commands.check(legal_channel)
async def help_gameplay(self, ctx: commands.Context):
embed = get_team_embed(f'Paper Dynasty Help')
embed.description = 'How to Play Paper Dynasty'
embed.add_field(
name='Game Modes',
value=HELP_GAMEMODES,
inline=False
)
embed.add_field(
name='Start a New Game',
value=HELP_NEWGAME,
inline=False,
)
embed.add_field(
name='Playing the Game',
value=HELP_PLAYGAME,
inline=False
)
embed.add_field(
name='Ending the Game',
value=f'{HELP_ENDGAME}\n'
f'- Go post highlights in {get_channel(ctx, "pd-news-ticker").mention}',
inline=False
)
await ctx.send(content=None, embed=embed)
@commands.hybrid_group(name='donation', help='Mod: Give packs for PD donations')
@commands.has_any_role(PD_PLAYERS_ROLE_NAME)
async def donation(self, ctx: commands.Context):
if ctx.invoked_subcommand is None:
await ctx.send('To buy packs, visit https://ko-fi.com/manticorum/shop and include your discord username!')
@donation.command(name='premium', help='Mod: Give premium packs', aliases=['p', 'prem'])
async def donation_premium(self, ctx: commands.Context, num_packs: int, gm: Member):
if ctx.author.id != self.bot.owner_id:
await ctx.send('Wait a second. You\'re not in charge here!')
return
team = get_team_by_owner(gm.id)
p_query = 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])
await ctx.send(f'The {team["lname"]} now have {total_packs["count"]} total packs!')
@donation.command(name='standard', help='Mod: Give standard packs', aliases=['s', 'sta'])
async def donation_standard(self, ctx: commands.Context, num_packs: int, gm: Member):
if ctx.author.id != self.bot.owner_id:
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')])
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])
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)
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(
'packs',
params=[('opened', True), ('team_id', team['id']), ('new_to_old', True), ('limit', 1)]
)
if not p_query['count']:
await ctx.send(f'I do not see any packs for you, bub.')
return
pack_name = p_query['packs'][0]['pack_type']['name']
if pack_name == 'Standard':
pack_cover = IMAGES['pack-sta']
elif pack_name == 'Premium':
pack_cover = IMAGES['pack-pre']
else:
pack_cover = None
c_query = db_get(
'cards',
params=[('pack_id', p_query['packs'][0]['id'])]
)
if not c_query['count']:
await ctx.send(f'Hmm...I didn\'t see any cards in that pack.')
return
await display_cards(c_query['cards'], team, ctx.channel, ctx.author, self.bot, pack_cover=pack_cover)
@commands.hybrid_command(name='comeonmanineedthis', help='Daily check-in for cards, currency, and packs')
@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)
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
)
return
current = 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=[
('name', 'Daily Check-in'), ('team_id', team['id']), ('created_after', midnight)
])
logging.debug(f'midnight: {midnight} / now: {int_timestamp(now)}')
logging.debug(f'daily_return: {daily}')
if daily:
await ctx.send(
f'Looks like you already checked in today - come back at midnight Central!',
ephemeral=True
)
return
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'])
])
check_count = check_ins['count'] % 5
# 2nd, 4th, and 5th check-ins
if check_count == 0 or check_count % 2 == 0:
# Every fifth check-in
if check_count == 0:
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')])
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
# Every second and fourth check-in
else:
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')])
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(
'packs',
params=[('opened', False), ('team_id', team['id']), ('new_to_old', True), ('limit', 1)]
)
if not p_query['count']:
await ctx.send(f'I do not see any packs in here. {await get_emoji(ctx, "ConfusedPsyduck")}')
return
pack_ids = await roll_for_cards(p_query['packs'], extra_val=check_count)
if not pack_ids:
await greeting.edit(
content=f'I was not able to create these cards {await get_emoji(ctx, "slight_frown")}'
)
return
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:
await greeting.edit(
content=f'I was not able to pull these cards {await get_emoji(ctx, "slight_frown")}'
)
return
await display_cards(all_cards, team, pack_channel, ctx.author, self.bot)
await refresh_sheet(team, self.bot)
return
# 1st, 3rd check-ins
else:
d_1000 = random.randint(1, 1000)
m_reward = 0
if d_1000 < 500:
m_reward = 10
elif d_1000 < 900:
m_reward = 15
elif d_1000 < 990:
m_reward = 20
else:
m_reward = 25
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)
@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
)
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'])
])
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?'
)
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
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:
await greeting.edit(f'I was not able to pull these cards {await get_emoji(ctx, "slight_frown")}')
return
# 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
else:
if page_num == len(card_embeds):
page_num = 1
else:
page_num += 1
view.value = None
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
await msg.edit(content=None, embeds=card_embeds[page_num - 1], view=view)
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()
group_buy = app_commands.Group(name='buy', description='Make a purchase from the marketplace')
@group_buy.command(name='card', description='Buy a player card from the marketplace')
@app_commands.checks.has_any_role(PD_PLAYERS)
@app_commands.describe(
player_name='Name of the player you want to purchase',
player_cardset='Optional: Name of the cardset the player is from'
)
async def buy_card_slash(
self, interaction: discord.Interaction, player_name: str, player_cardset: Optional[str] = None):
if interaction.channel.name in ['paper-dynasty-chat', 'pd-news-ticker', 'pd-network-news']:
await interaction.response.send_message(
f'Please head to down to {get_channel(interaction, "pd-bot-hole")} to run this command.',
ephemeral=True
)
return
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!'
)
player_cog = self.bot.get_cog('Players')
proper_name = fuzzy_search(player_name, player_cog.player_list)
if not proper_name:
await interaction.response.send_message(f'No clue who that is.')
return
all_params = [('name', proper_name)]
if player_cardset:
this_cardset = cardset_search(player_cardset, player_cog.cardset_list)
all_params.append(('cardset_id', this_cardset['id']))
p_query = db_get('players', params=all_params)
if p_query['count'] == 0:
await interaction.response.send_message(
f'I didn\'t find any cards for {proper_name}'
)
return
if p_query['count'] > 1:
await interaction.response.send_message(
f'I found {p_query["count"]} different cards for {proper_name}. Would you please run this again '
f'with the cardset specified?'
)
return
this_player = p_query['players'][0]
logging.debug(f'this_player: {this_player}')
c_query = db_get('cards',
params=[('player_id', this_player['player_id']), ('team_id', owner_team["id"])])
num_copies = c_query['count'] if c_query else 0
if this_player['cost'] > owner_team['wallet']:
await interaction.response.send_message(
content=None,
embeds=await get_card_embeds(get_blank_team_card(this_player))
)
await interaction.channel.send(
content=f'You currently have {num_copies} cop{"ies" if num_copies != 1 else "y"} of this card.\n\n'
f'Your Wallet: {owner_team["wallet"]}\n'
f'Card Price: {this_player["cost"]}\n'
f'After Purchase: {await get_emoji(interaction.guild, "dead", False)}\n\n'
f'You will have to save up a little more.'
)
return
view = Confirm(responders=[interaction.user])
await interaction.response.send_message(
content=None,
embeds=await get_card_embeds(get_blank_team_card(this_player))
)
question = await interaction.channel.send(
content=f'You currently have {num_copies} cop{"ies" if num_copies != 1 else "y"} of this card.\n\n'
f'Your Wallet: {owner_team["wallet"]}\n'
f'Card Price: {this_player["cost"]}\n'
f'After Purchase: {owner_team["wallet"] - this_player["cost"]}\n\n'
f'Would you like to make this purchase?',
view=view
)
await view.wait()
if not view.value:
await question.edit(
content='Saving that money. Smart.',
view=None
)
return
purchase = db_get(
f'teams/{owner_team["id"]}/buy/players',
params=[('ts', team_hash(owner_team)), ('ids', f'{this_player["player_id"]}')],
timeout=10
)
if not purchase:
await question.edit(
f'That didn\'t go through for some reason. If this happens again, go ping the shit out of Cal.',
view=None
)
return
await question.edit(content=f'It\'s all yours!', view=None)
await refresh_sheet(owner_team, self.bot)
@group_buy.command(name='pack', description='Buy a pack or 7 from the marketplace')
@app_commands.checks.has_any_role(PD_PLAYERS)
@app_commands.describe(
num_packs='Number of packs to purchase',
pack_name='Name of the pack you want (e.g. \'Standard\', \'Premium\')'
)
async def buy_pack_slash(self, interaction: discord.Interaction, num_packs: int = 1,
pack_name: Literal['Standard', 'Premium'] = None):
if interaction.channel.name in ['paper-dynasty-chat', 'pd-news-ticker', 'pd-network-news']:
await interaction.response.send_message(
f'Please head to down to {get_channel(interaction, "pd-bot-hole")} to run this command.',
ephemeral=True
)
return
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!'
)
if not pack_name:
p_query = db_get('packtypes', params=[('available', True)])
if 'count' not in p_query:
await interaction.response.send_message(
f'Welp, I couldn\'t find any packs in my database. Should probably go ping '
f'{get_cal_user(interaction).mention} about that.'
)
return
embed = get_team_embed('Packs for Purchase')
embed.description = 'Run `/buy pack <pack_name>`'
for x in p_query['packtypes']:
embed.add_field(name=f'{x["name"]} - {x["cost"]}', value=f'{x["description"]}')
await interaction.response.send_message(
content=None,
embed=embed
)
return
p_query = 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.',
ephemeral=True
)
return
pack_type = p_query['packtypes'][0]
pack_cover = IMAGES['logo']
if pack_type['name'] == 'Standard':
pack_cover = IMAGES['pack-sta']
elif pack_type['name'] == 'Premium':
pack_cover = IMAGES['pack-pre']
total_cost = pack_type['cost'] * num_packs
pack_embed = image_embed(
pack_cover,
title=f'{owner_team["lname"]}',
desc=f'{num_packs if num_packs > 1 else ""}{"x " if num_packs > 1 else ""}'
f'{pack_type["name"]} Pack{"s" if num_packs != 1 else ""}',
)
if total_cost > owner_team['wallet']:
await interaction.response.send_message(
content=None,
embed=pack_embed
)
await interaction.channel.send(
content=f'Your Wallet: {owner_team["wallet"]}\n'
f'Pack{"s" if num_packs > 1 else ""} Price: {total_cost}\n'
f'After Purchase: {await get_emoji(interaction.guild, "dead", False)}\n\n'
f'You will have to save up a little more.'
)
return
view = Confirm(responders=[interaction.user], timeout=30)
await interaction.response.send_message(
content=None,
embed=pack_embed
)
question = await interaction.channel.send(
# content=f'You currently have {num_copies} cop{"ies" if num_copies != 1 else "y"} of this card.\n\n'
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
purchase = db_get(
f'teams/{owner_team["id"]}/buy/pack/{pack_type["id"]}',
params=[('ts', team_hash(owner_team)), ('quantity', num_packs)]
)
if not purchase:
await question.edit(
f'That didn\'t go through for some reason. If this happens again, go ping the shit out of Cal.',
view=None
)
return
await question.edit(
content=f'{"They are" if num_packs > 1 else "It is"} all yours! Go rip it with `/open`',
view=None
)
@app_commands.command(name='selldupes', description='Sell all of your duplicate cards')
@app_commands.checks.has_any_role(PD_PLAYERS)
@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)
if not team:
await interaction.response.send_message(
f'I don\'t see a team for you, yet. You can sign up with the `/newteam` command!',
ephemeral=True
)
return
await interaction.response.send_message(
f'Let me flip through your cards. This could take a while if you have a ton of cards...'
)
try:
c_query = 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'
)
return
player_ids = []
dupe_ids = ''
dupe_cards = []
dupe_string = ''
for card in c_query['cards']:
logging.debug(f'card: {card}')
if card['player']['player_id'] not in player_ids:
logging.debug(f'not a dupe')
player_ids.append(card['player']['player_id'])
else:
logging.info(f'{team["abbrev"]} duplicate card: {card["id"]}')
dupe_cards.append(card)
dupe_ids += f'{card["id"]},'
dupe_string += f'{card["player"]["rarity"]["name"]} {card["player"]["p_name"]} - ' \
f'{card["player"]["cardset"]["name"]}\n'
if len(dupe_cards) == 0:
await interaction.edit_original_response(content=f'You currently have 0 duplicate cards!')
return
await interaction.edit_original_response(
content=f'You currently have {len(dupe_cards)} duplicate cards:\n\n{dupe_string}'
)
if not immediately:
view = Confirm(responders=[interaction.user])
question = await interaction.channel.send('Would you like to sell all of them?', view=view)
await view.wait()
if not view.value:
await question.edit(
content='We can leave them be for now.',
view=None
)
return
await question.edit(content=f'The sale is going through...', view=None)
# for card in dupe_cards:
sale = db_get(
f'teams/{team["id"]}/sell/cards',
params=[('ts', team_hash(team)), ('ids', dupe_ids)],
timeout=10
)
if not sale:
await interaction.channel.send(
f'That didn\'t go through for some reason. Go ping the shit out of {get_cal_user(interaction).mention}.'
)
return
await refresh_sheet(team, self.bot)
team = db_get('teams', object_id=team['id'])
await interaction.channel.send(f'Your Wallet: {team["wallet"]}')
@app_commands.command(name='newteam', description='Get your fresh team for a new season')
@app_commands.checks.has_any_role(PD_PLAYERS)
@app_commands.describe(
gm_name='The fictional name of your team\'s GM',
team_abbrev='2, 3, or 4 character abbreviation (e.g. WV, ATL, MAD)',
team_full_name='City/location and name (e.g. Baltimore Orioles)',
team_short_name='Name of team (e.g. Yankees)',
mlb_anchor_team='2 or 3 character abbreviation of your anchor MLB team (e.g. NYM, MKE)',
team_logo_url='[Optional] URL ending in .png or .jpg for your team logo',
color='[Optional] Hex color code to highlight your team'
)
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')
# Check for existing team
if owner_team and not os.environ.get('TESTING'):
await interaction.response.send_message(
f'Whoa there, bucko. I already have you down as GM of the {owner_team["sname"]}.'
)
return
# Check for duplicate team data
dupes = db_get('teams', params=[('abbrev', team_abbrev)])
if dupes['count']:
await interaction.response.send_message(
f'Yikes! {team_abbrev.upper()} is a popular abbreviation - it\'s already in use by the '
f'{dupes["teams"][0]["sname"]}. No worries, though, you can run the `/newteam` command again to get '
f'started!'
)
return
# Check for duplicate team data
dupes = db_get('teams', params=[('lname', team_full_name)])
if dupes['count']:
await interaction.response.send_message(
f'Yikes! {team_full_name.title()} is a popular name - it\'s already in use by '
f'{dupes["teams"][0]["abbrev"]}. No worries, though, you can run the `/newteam` command again to get '
f'started!'
)
return
# Get personal bot channel
hello_channel = discord.utils.get(
interaction.guild.text_channels,
name=f'hello-{interaction.user.name.lower()}'
)
if hello_channel:
op_ch = hello_channel
else:
op_ch = await helpers.create_channel(
interaction,
channel_name=f'hello-{interaction.user.name}',
category_name='Paper Dynasty Team',
everyone_read=False,
read_send_members=[interaction.user]
)
await share_channel(op_ch, interaction.guild.me)
await share_channel(op_ch, interaction.user)
try:
poke_role = get_role(interaction, 'Pokétwo')
await share_channel(op_ch, poke_role, read_only=True)
except Exception as e:
logging.error(f'unable to share sheet with Poketwo')
await interaction.response.send_message(
f'Let\'s head down to your private channel: {op_ch.mention}',
ephemeral=True
)
await op_ch.send(f'Hey there, {interaction.user.mention}! I am Paper Domo - welcome to season '
f'{current["season"]} of Paper Dynasty! We\'ve got a lot of special updates in store for this '
f'season including live cards, throwback cards, and special events.')
# Confirm user is happy with branding
embed = get_team_embed(
f'Branding Check',
{
'logo': team_logo_url if team_logo_url else None,
'color': color if color else 'a6ce39',
'season': 4
}
)
embed.add_field(name='GM Name', value=gm_name, inline=False)
embed.add_field(name='Full Team Name', value=team_full_name)
embed.add_field(name='Short Team Name', value=team_short_name)
embed.add_field(name='Team Abbrev', value=team_abbrev.upper())
view = Confirm(responders=[interaction.user])
question = await op_ch.send('Are you happy with this branding? Don\'t worry - you can update it later!',
embed=embed, view=view)
await view.wait()
if not view.value:
await question.edit(
content='~~Are you happy with this branding?~~\n\nI gotta go, but when you\'re ready to start again '
'run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the '
'command from last time and make edits.',
view=None
)
return
await question.edit(
content='Looking good, champ in the making! Let\'s get you your starter team!',
view=None
)
team_choice = None
if mlb_anchor_team.title() in ALL_MLB_TEAMS.keys():
team_choice = mlb_anchor_team.title()
else:
for x in ALL_MLB_TEAMS:
if mlb_anchor_team.upper() in ALL_MLB_TEAMS[x] or mlb_anchor_team.title() in ALL_MLB_TEAMS[x]:
team_choice = x
break
team_string = mlb_anchor_team
logging.debug(f'team_string: {team_string} / team_choice: {team_choice}')
if not team_choice:
# Get MLB anchor team
while True:
prompt = f'I don\'t recognize **{team_string}**. I try to recognize abbreviations (BAL), ' \
f'short names (Orioles), and long names ("Baltimore Orioles").\n\nWhat MLB club would you ' \
f'like to use as your anchor team?'
this_q = Question(self.bot, op_ch, prompt, 'text', 120)
team_string = await this_q.ask([interaction.user])
if not team_string:
await op_ch.send(
f'Tell you hwat. You think on it and come back I gotta go, but when you\'re ready to start again '
'run the `/newteam` command again and we can get rolling! Hint: you can copy and paste the '
'command from last time and make edits.'
)
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 not match:
await op_ch.send(f'Got it!')
team = db_post('teams', payload={
'abbrev': team_abbrev.upper(),
'sname': team_short_name,
'lname': team_full_name,
'gmid': interaction.user.id,
'gmname': gm_name,
'gsheet': 'None',
'season': current['season'],
'wallet': 100,
'color': color if color else 'a6ce39',
'logo': team_logo_url if team_logo_url else None
})
if not team:
await op_ch.send(f'Frick. {get_cal_user(interaction).mention}, can you help? I can\'t find this team.')
return
t_role = await get_or_create_role(interaction, f'{team_abbrev} - {team_full_name}')
await interaction.user.add_roles(t_role)
anchor_players = []
anchor_all_stars = db_get(
'players/random',
params=[
('min_rarity', 3), ('max_rarity', 3), ('franchise', team_choice), ('pos_exclude', 'RP'), ('limit', 1)
]
)
anchor_starters = db_get(
'players/random',
params=[
('min_rarity', 2), ('max_rarity', 2), ('franchise', team_choice), ('pos_exclude', 'RP'), ('limit', 2)
]
)
if not anchor_all_stars:
await op_ch.send(f'I am so sorry, but the {team_choice} do not have an All-Star to '
f'provide as your anchor player. Let\'s start this process over - will you please '
f'run the `/newteam` command again with a new MLB club?\nHint: you can copy and paste the '
'command from last time and make edits.')
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'])
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',
payload={'team_id': team['id'], 'pack_type_id': 2,
'open_time': datetime.datetime.timestamp(datetime.datetime.now())*1000})
roster_counts = {
'SP': 0,
'RP': 0,
'C': 0,
'1B': 0,
'2B': 0,
'3B': 0,
'SS': 0,
'LF': 0,
'CF': 0,
'RF': 0,
'DH': 0,
'All-Star': 0,
'Starter': 0,
'Reserve': 0,
'Replacement': 0,
}
def update_roster_counts(players: list):
for pl in players:
roster_counts[pl['rarity']['name']] += 1
for x in get_all_pos(pl):
roster_counts[x] += 1
logging.warning(f'Roster counts for {team["sname"]}: {roster_counts}')
# Add anchor position coverage
update_roster_counts(anchor_players)
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)])
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': [
{'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in [*team_sp, *team_rp]]
}, timeout=10)
# TODO: track reserve vs replacement and if rep < res, get rep, else get res
# Collect infielders
team_infielders = []
for pos in ['C', '1B', '2B', '3B', 'SS']:
max_rar = 1
if roster_counts['Replacement'] < roster_counts['Reserve']:
max_rar = 0
r_draw = 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': [
{'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in team_infielders]
}, timeout=10)
# Collect outfielders
team_outfielders = []
for pos in ['LF', 'CF', 'RF']:
max_rar = 1
if roster_counts['Replacement'] < roster_counts['Reserve']:
max_rar = 0
r_draw = 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': [
{'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in team_outfielders]
}, timeout=10)
async with op_ch.typing():
done_anc = await display_cards(
[{'player': x, 'team': team} for x in anchor_players], team, op_ch, interaction.user, self.bot,
cust_message=f'Let\'s take a look at your three {team_choice} anchor players.\n'
f'Press `Close Pack` to continue.',
add_roster=False
)
error_text = f'Yikes - I can\'t display the rest of your team. {get_cal_user(interaction).mention} plz halp'
if not done_anc:
await op_ch.send(error_text)
async with op_ch.typing():
done_sp = await display_cards(
[{'player': x, 'team': team} for x in team_sp], team, op_ch, interaction.user, self.bot,
cust_message=f'Here are your starting pitchers.\n'
f'Press `Close Pack` to continue.',
add_roster=False
)
if not done_sp:
await op_ch.send(error_text)
async with op_ch.typing():
done_rp = await display_cards(
[{'player': x, 'team': team} for x in team_rp], team, op_ch, interaction.user, self.bot,
cust_message=f'And now for your bullpen.\n'
f'Press `Close Pack` to continue.',
add_roster=False
)
if not done_rp:
await op_ch.send(error_text)
async with op_ch.typing():
done_inf = await display_cards(
[{'player': x, 'team': team} for x in team_infielders], team, op_ch, interaction.user, self.bot,
cust_message=f'Next let\'s take a look at your infielders.\n'
f'Press `Close Pack` to continue.',
add_roster=False
)
if not done_inf:
await op_ch.send(error_text)
async with op_ch.typing():
done_out = await display_cards(
[{'player': x, 'team': team} for x in team_outfielders], team, op_ch, interaction.user, self.bot,
cust_message=f'Now let\'s take a look at your outfielders.\n'
f'Press `Close Pack` to continue.',
add_roster=False
)
if not done_out:
await op_ch.send(error_text)
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!'
)
await op_ch.send(
f'{t_role.mention}\n\n'
f'There\'s your roster! We have one more step and you will be ready to play.\n\n{SHEET_SHARE_STEPS}\n\n'
f'{get_roster_sheet({"gsheet": current["gsheet_template"]}, allow_embed=True)}'
)
new_team_embed = 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
)
@commands.command(name='mlbteam', help='Mod: Load MLB team data')
@commands.is_owner()
async def mlb_team_command(
self, ctx: commands.Context, abbrev: str, sname: str, lname: str, gmid: int, gmname: str, gsheet: str,
logo: str, color: str, ranking: int):
# Check for duplicate team data
dupes = db_get('teams', params=[('abbrev', abbrev)])
if dupes['count']:
await ctx.send(
f'Yikes! {abbrev.upper()} is a popular abbreviation - it\'s already in use by the '
f'{dupes["teams"][0]["sname"]}. No worries, though, you can run the `/newteam` command again to get '
f'started!'
)
return
# Check for duplicate team data
dupes = db_get('teams', params=[('lname', lname)])
if dupes['count']:
await ctx.send(
f'Yikes! {lname.title()} is a popular name - it\'s already in use by '
f'{dupes["teams"][0]["abbrev"]}. No worries, though, you can run the `/newteam` command again to get '
f'started!'
)
return
current = db_get('current')
team = db_post('teams', payload={
'abbrev': abbrev.upper(),
'sname': sname,
'lname': lname,
'gmid': gmid,
'gmname': gmname,
'gsheet': gsheet,
'season': current['season'],
'wallet': 100,
'ranking': ranking,
'color': color if color else 'a6ce39',
'logo': logo if logo else None,
'is_ai': True
})
p_query = db_get('players', params=[('franchise', lname)])
this_pack = 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': [
{'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in team_players]
}, timeout=10)
embed = get_team_embed(f'{team["lname"]}', team)
await ctx.send(content=None, embed=embed)
@commands.hybrid_command(name='mlb-update', help='Distribute MLB cards to AI teams')
@commands.is_owner()
async def mlb_update_command(self, ctx: commands.Context):
ai_teams = db_get('teams', params=[('is_ai', True)])
if ai_teams['count'] == 0:
await ctx.send(f'I could not find any AI teams.')
return
total_cards = 0
total_teams = 0
for team in ai_teams['teams']:
all_players = db_get('players', params=[('franchise', team['lname'])])
new_players = []
if all_players:
for player in all_players['players']:
owned_by_team_ids = [entry['team'] for entry in player['paperdex']['paperdex']]
if team['id'] not in owned_by_team_ids:
new_players.append(player)
if new_players:
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(
'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': [
{'player_id': x['player_id'], 'team_id': team['id'], 'pack_id': this_pack['id']} for x in
new_players
]}, timeout=10)
await refresh_sheet(team, self.bot)
await ctx.send(f'All done! I added {total_cards} across {total_teams} teams.')
# @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(
self, ctx, google_sheet_url: str, team_abbrev: Optional[str], copy_rosters: Optional[bool] = True):
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!')
return
if team_abbrev and team_abbrev != team['abbrev']:
if ctx.author.id != 258104532423147520:
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)
current = 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
sheets = get_sheets(self.bot)
response = await ctx.send(f'I\'ll go grab that sheet...')
try:
new_sheet = sheets.open_by_url(google_sheet_url)
except Exception as e:
logging.error(f'Error accessing {team["abbrev"]} sheet: {e}')
current = 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)}')
return
team_data = new_sheet.worksheet_by_title('Team Data')
team_data.update_values(
crange='B1:B2',
values=[[f'{team["id"]}'], [f'\'{team_hash(team)}']]
)
if copy_rosters and team['gsheet'] != 'None':
old_sheet = sheets.open_by_key(team['gsheet'])
r_sheet = old_sheet.worksheet_by_title(f'My Rosters')
roster_ids = r_sheet.range('B3:B80')
lineups_data = r_sheet.range('H4:M26')
new_r_data, new_l_data = [], []
for row in roster_ids:
if row[0].value != '':
new_r_data.append([int(row[0].value)])
else:
new_r_data.append([None])
logging.debug(f'new_r_data: {new_r_data}')
for row in lineups_data:
logging.debug(f'row: {row}')
new_l_data.append([
row[0].value if row[0].value != '' else None,
int(row[1].value) if row[1].value != '' else None,
row[2].value if row[2].value != '' else None,
int(row[3].value) if row[3].value != '' else None,
row[4].value if row[4].value != '' else None,
int(row[5].value) if row[5].value != '' else None
])
logging.debug(f'new_l_data: {new_l_data}')
new_r_sheet = new_sheet.worksheet_by_title(f'My Rosters')
new_r_sheet.update_values(
crange='B3:B80',
values=new_r_data
)
new_r_sheet.update_values(
crange='H4:M26',
values=new_l_data
)
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)])
await refresh_sheet(team, self.bot, sheets)
await response.edit(content=f'Alright, your sheet is linked to your team - good luck this season!\n\n'
f'{HELP_SHEET_SCRIPTS}')
@commands.hybrid_command(name='refresh', help='Refresh team data in Sheets')
@commands.has_any_role(PD_PLAYERS)
async def update_team(self, ctx):
if not await legal_channel(ctx):
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)
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
await refresh_sheet(team, self.bot)
await ctx.send(random_conf_gif())
# if abbrev and self.bot.is_owner(ctx.author):
# team = Team.get_season(abbrev[0])
# else:
# 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
#
# # Get data from Sheets
# roster_data = await self.get_collection(ctx, team)
#
# # Cut any marked players
# comp_trade = True
# if len(roster_data['cut']) > 0:
# comp_trade = await self.cut_players(ctx, team, roster_data['cut'])
#
# if not comp_trade:
# return
#
# # Set new rostered list
# self.set_rostered_players(team, roster_data['rostered'])
#
# # Send current data to Sheets
# if not await self.write_collection(ctx, team, extra=len(roster_data['cut'])):
# logging.error(f'There was an issue trying to update the {team.sname} roster.')
# await helpers.pause_then_type(ctx, 'Yikes. I had an issue with Sheets. Send help.')
# else:
# await helpers.pause_then_type(ctx, 'Alrighty, your sheet is all up to date!')
# if team.logo:
# thumb = team.logo
# else:
# thumb = self.bot.get_user(team.gmid).avatar_url
# await ctx.send(content=None, embed=helpers.get_active_roster(team, thumb))
#
# db.close()
@commands.hybrid_command(name='give-card', help='Mod: Give free card to team')
# @commands.is_owner()
@commands.has_any_role("PD Gift Players")
async def give_card_command(self, ctx, player_ids: str, team_abbrev: str):
if ctx.channel.name in ['paper-dynasty-chat', 'pd-news-ticker', 'pd-network-news']:
await ctx.send(f'Please head to down to {get_channel(ctx, "pd-bot-hole")} to run this command.')
return
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)])
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(
'packs/one',
payload={
'team_id': team['id'],
'pack_type_id': 4,
'open_time': datetime.datetime.timestamp(datetime.datetime.now()) * 1000}
)
try:
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.')
await question.edit(content=f'Alrighty, now I\'ll refresh their sheet...')
await refresh_sheet(team, self.bot)
await question.edit(content=f'All done!')
await send_to_channel(
self.bot,
channel_name='commissioners-office',
content=f'Just sent {len(all_player_ids)} players to {ctx.message.author.mention}:\n{all_player_ids}'
)
@commands.command(name='cleartest', hidden=True)
@commands.is_owner()
async def clear_test_command(self, ctx):
team = get_team_by_owner(ctx.author.id)
msg = await ctx.send('Alright, let\'s go find your cards...')
all_cards = db_get(
'cards',
params=[('team_id', team['id'])]
)
if all_cards:
await msg.edit(content=f'I found {len(all_cards["cards"])} cards; deleting now...')
for x in all_cards['cards']:
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'])])
if p_query['count']:
for x in p_query['packs']:
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'])])
if p_query['count']:
for x in p_query['paperdex']:
db_delete('paperdex', object_id=x['id'])
await msg.edit(content=f'All done with paperdex. Now I\'ll wipe out your team...')
if db_delete('teams', object_id=team['id']):
await msg.edit(content=f'All done!')
@commands.command(name='packtest', hidden=True)
@commands.is_owner()
async def pack_test_command(self, ctx):
team = get_team_by_owner(ctx.author.id)
await display_cards(
await get_test_pack(ctx, team), team, ctx.channel, ctx.author, self.bot,
pack_cover=IMAGES['pack-sta'],
pack_name='Standard Pack'
)
# @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))