async def display_player_deck_stats(self, ctx, sort_key): sort_key = sort_key.split()[0] user = ctx.message.mentions[0] if not self.bot.db.find_member(user.id, ctx.message.guild): await ctx.send(embed=embed.error( f"**{user.name}** is not a registered player")) return data = utils.get_player_match_stats(ctx, user) if not data: await ctx.send(embed=embed.error( description=f"No matches found for **{user.name}**")) return if sort_key.lower() == "usage": sorted_data = utils.sort_by_entries(data) _tables = self._make_deck_tables(sorted_data, "winloss") elif sort_key.lower() == "winrate": sorted_data = utils.sort_by_winrate(data) _tables = self._make_deck_tables(sorted_data, "winrate") else: sorted_data = utils.sort_by_winrate(data) _tables = self._make_full_player_deck_tables(sorted_data, user) for _table in _tables: await ctx.send(_table) return for _table in _tables.text: await ctx.send(_table)
async def use(self, ctx, *, deck_name: str = ""): """Set your current deck to the specified deck. The deck must be a registered deck. A list of all registered decks can be viewed with the `decks` command. If the desired deck is not being tracked, Rogue can be used as a placeholder.""" user = ctx.message.author action_description = f"`{ctx.prefix}decks`\n`{ctx.prefix}decks [color set]`" if not deck_name: emsg = embed.error(description="No deck specified.") \ .add_field(name="Actions", value=action_description) await ctx.send(embed=emsg) return if deck_name.lower() == "rogue": official_name = "Rogue" else: deck = self.bot.db.find_deck(deck_name) if not deck: emsg = embed.error(description=f"{deck_name} is not a recognized deck.") \ .add_field(name="Actions", value=action_description) await ctx.send(embed=emsg) return else: official_name = deck["name"] self.bot.db.set_deck(official_name, user, ctx.message.guild) await ctx.send(embed=embed.msg( description=f"Deck set to {official_name} for **{user.name}**"))
async def _add_deck(self, ctx, *args): """Import a deck to the database. Information about the deck is scraped from the deck list link.""" if len(args) < 2: await ctx.send(embed=embed.error( description=f'**ERROR** - Not enough args')) return if len(args) > 2: await ctx.send(embed=embed.error( description= f'**ERROR** - Too many args. Make sure to enclose deck names in quotes.' )) return deck_name = args[0] deck_link = args[1] try: deck = deck_utils.extract(deck_link) except err.DeckNotFoundError: await ctx.send(embed=embed.error( description=f'**ERROR** - Failed to fetch decklist from link')) return except err.CardNotFoundError: await ctx.send(embed=embed.error( description= f'**ERROR** - Failed to fetch commanders from Scryfall')) return color_name = color_names.NAMES[deck["color_identity"]] self.bot.db.add_deck(deck["color_identity"], color_name, deck_name, [deck_name], [cmdr['name'] for cmdr in deck["commanders"]], deck_link) await ctx.send(embed=embed.success( description=f'**SUCCESS** - Imported {deck_name} to deck database') )
async def confirm(self, ctx, *, game_id: str=""): """Validate a match result. All players, including the winner, must confirm a match. By default, this command will confirm the most recent pending match by the caller. If a game_id is specified, then the specified match will be confirmed instead. Confirmation is a two-step process to verify the caller's deck choice and then to verify that the match result is correct.""" user = ctx.message.author member = self.bot.db.find_member(user.id, ctx.message.guild) if not member["pending"]: await ctx.send(embed=embed.info(description="No pending matches to confirm")) return if not game_id: game_id = member["pending"][-1] match = self.bot.db.find_match(game_id, ctx.message.guild) if not match: await ctx.send(embed=embed.error(description=f"`{game_id}` does not exist")) return player = next((i for i in match["players"] if i["user_id"] == user.id), None) if not player: await ctx.send(embed=embed.error(description="Only participants can confirm a match")) return if not player["confirmed"]: delta = await self._get_player_confirmation(ctx, member, game_id) if delta: await ctx.send(embed=embed.match_delta(game_id, delta)) else: await ctx.send(embed=embed.error(description="You have already confirmed this match"))
async def _set_user_deck(self, ctx, *args): """Update a match by setting a user's deck to the specified deck name.""" if len(args) < 3: await ctx.send(embed=embed.error(description=f"Not enough args. See `{ctx.prefix}help update`.")) return game_ids = args[0].split(",") deck_names = args[2].split(",") if len(game_ids) != len(deck_names): await ctx.send(embed=embed.error(description="There must be the same number of decks as games specified.")) return if not ctx.message.mentions: await ctx.send(embed=embed.error(description=f"Please include the player to adjust.")) return user = ctx.message.mentions[0] nupdates = len(game_ids) for i in range(nupdates): deck = self.bot.db.find_deck(deck_names[i]) if not deck: await ctx.send(embed=embed.error( description=f"Deck name \"{deck_names[i]}\" not recognized. See `{ctx.prefix}decks` for a list of all decks.")) continue if not self.bot.db.confirm_match_for_user(game_ids[i], user.id, deck['name'], ctx.message.guild): await ctx.send(embed=embed.error( description=f"No game found for `{game_ids[i]}` with the given user as a participant." )) else: await ctx.send(embed=embed.success( title=f"Game id: {game_ids[i]}", description=f"Set deck to **{deck['name']}** for **{user.name}**" ))
async def _add_link(self, ctx, *args): """Add or update a decklist link for a deck. Names that are multiple words must be enclosed in quotes.""" if len(args) < 2: await ctx.send(embed=embed.error( description='**ERROR** - Not enough args')) return deck_name = args[0] deck_link = args[1] deck = self.bot.db.find_deck(deck_name) if not deck: await ctx.send(embed=embed.error( description='**ERROR** - Deck not found')) return try: decklist = deck_utils.extract(deck_link) except err.DeckNotFoundError: await ctx.send(embed=embed.error( description= '**ERROR** - Failed to fetch deck from the given link')) return except err.CardNotFoundError: await ctx.send(embed=embed.error( description= '**ERROR** - Failed to fetch commander from Scryfall')) return self.bot.db.add_deck_link(deck_name, deck_link) await ctx.send(embed=embed.success( description=f"**SUCCESS** - Added a link for **{deck['name']}**"))
async def game(self, ctx, *, game_id: str=""): """Get the details of a game. Details include the date it was logged, who the players were, what decks were played, who won the match, and the confirmation status of the match.""" if not game_id: await ctx.send(embed=embed.error(description="No game id specified")) return match = self.bot.db.find_match(game_id, ctx.message.guild) if not match: await ctx.send(embed=embed.error(description=f"`{game_id}` does not exist")) return winner = next((i for i in match["players"] if i["user_id"] == match["winner"]), None) date = datetime.fromtimestamp(match["timestamp"]) if match["status"] == stc.ACCEPTED: status_symbol = emojis.accepted elif match["status"] == stc.PENDING: status_symbol = emojis.pending else: status_symbol = emojis.disputed emsg = embed.msg(title=f"Game id: {game_id}") \ .add_field(name="Date (UTC)", value=date.strftime("%Y-%m-%d")) \ .add_field(name="Winner", value=winner["name"]) \ .add_field(name="Status", value=status_symbol) if match['replay_link']: emsg.add_field(name="Replay", value=match['replay_link']) emsg.description = self._make_game_table(ctx, match) await ctx.send(embed=emsg)
async def deny(self, ctx, *, game_id: str=""): """Dispute a match result. This will notify league admins that the match result requires attention. League admins may resolve the match by either accepting or removing it. If you created the match and there is an error (ie. mentioned the wrong players), then the `remove` command is more appropriate to undo the logged match and log the correct result.""" user = ctx.message.author member = self.bot.db.find_member(user.id, ctx.message.guild) if not member["pending"]: await ctx.send(embed=embed.info(description="No pending matches to deny")) return if not game_id: await ctx.send(embed=embed.error(description="You must specify a game id to dispute it")) return match = self.bot.db.find_match(game_id, ctx.message.guild) if not match: await ctx.send(embed=embed.error(description=f"`{game_id}` does not exist")) return player = next((i for i in match["players"] if i["user_id"] == user.id), None) if not player: await ctx.send(embed=embed.error(description="Only participants can deny a match")) return if match["status"] == stc.ACCEPTED: await ctx.send(embed=embed.error(description="Accepted matches cannot be denied")) elif match["status"] == stc.DISPUTED: await ctx.send(embed=embed.info(description="This match has already been marked for review")) else: self.bot.db.set_match_status(stc.DISPUTED, game_id, ctx.message.guild) self.bot.db.unconfirm_match_for_user(game_id, user.id, ctx.message.guild) admin_role = self.bot.db.get_admin_role(ctx.message.guild) mention = "" if not admin_role else admin_role.mention await ctx.send(embed=embed.msg( description=f"{mention} Match `{game_id}` has been marked as **disputed**") )
async def get_top_args(self, ctx, args): limit = utils.get_command_arg(args, "limit", DEFAULT_LIMIT) if (type(limit) is not int): await ctx.send(embed=embed.error( description="Limit should be a number.")) raise ValueError DEFAULT_THRESHOLD = self.bot.db.get_player_match_threshold( ctx.message.guild) min_games = utils.get_command_arg(args, "min", DEFAULT_THRESHOLD) if (type(min_games) is not int): await ctx.send(embed=embed.error( description="Min should be a number.")) raise ValueError return limit, min_games
async def decks(self, ctx, *, color: str = ""): """Show all registered decks, categorized by color combination. If a color combination is specified in WUBRG format, filter the results by that color combination. For example, to show only Esper decks, use WUB as the color combination (order does not matter).""" if not color: emsg = embed.msg(title="Registered Decks") colors = utils.get_all_color_combinations() for color in colors: example = self.bot.db.find_one_deck_by_color(color) if not example: continue decks = self.bot.db.find_decks_by_color(color) emsg.add_field(name=example["color_name"], value=("\n".join( [deck["name"] for deck in decks]))) if (len(emsg.fields) == 9): await ctx.send(embed=emsg) emsg = embed.msg(title="Registered Decks") if len(emsg.fields) > 0: await ctx.send(embed=emsg) else: example = self.bot.db.find_one_deck_by_color(color) if not example: await ctx.send(embed=embed.error( description= "No decks found with the specified color combination.")) else: decks = self.bot.db.find_decks_by_color(color) emsg = embed.msg( title=f"Registered {example['color_name']} Decks", description=("\n".join(deck["name"] for deck in decks))) await ctx.send(embed=emsg)
async def _games_by_players(self, ctx, *args): """Displays a list of games filtered by players. Mention all players to filter by. If no players are mentioned, filter by games containing the sender.""" mentions = ctx.message.mentions if len(mentions) > 4: await ctx.send(embed=embed.error( description="Too many players mentioned")) return if len(mentions) == 0: mentions.append(ctx.message.author) matches = self.bot.db.find_matches( {"players.user_id": { "$all": [user.id for user in mentions] }}, ctx.message.guild, limit=20) matches = list(matches) if not matches: await ctx.send(embed=embed.info( description=("No matches found containing " + ", ".join([user.name for user in mentions])))) return title = "Games Containing: " + ", ".join( [mention.name for mention in mentions]) emsgs = self._make_match_table(title, matches, winner_type="player") for emsg in emsgs: await ctx.send(embed=emsg)
async def season(self, ctx, *, season_number: int = None): """Get information about a season.""" season_info = self.bot.db.get_season(ctx.message.guild, season=season_number) if not season_info: await ctx.send(embed=embed.error( description=f"Season {season_number} does not exist.")) return emsg = embed.info(title=f"Season {season_info['season_number']}") start_date = datetime.fromtimestamp(season_info["start_time"]) emsg.add_field(name="Start Date", value=start_date.strftime("%Y-%m-%d")) if "end_time" in season_info: end_date = datetime.fromtimestamp(season_info["end_time"]) emsg.add_field(name="End Date", value=end_date.strftime("%Y-%m-%d")) awards = [ emojis.first_place, emojis.second_place, emojis.third_place ] emsg.add_field( name="Season Awards", value="\n".join([ f"`{awards[i]} - {self.bot.db.find_member(user_id, ctx.message.guild)['name']}`" for i, user_id in enumerate(season_info["season_leaders"]) ])) await ctx.send(embed=emsg)
async def add_component(self, ctx): """Add a user, match, or deck to the league.""" if ctx.invoked_subcommand is None: await ctx.send(embed=embed.error( description=f'**ERROR** - Specify a component to add')) return
async def _link(self, ctx, *args): """Add a replay link to a game. Links can later be discovered and filtered with the `replay` command.""" if len(args) < 2: await ctx.send(embed=embed.error(description="Not enough args. Please include a game id and a replay link.")) return game_id = args[0] replay_link = args[1] if not self.bot.db.update_match( {"game_id": game_id}, {"$set": {"replay_link": replay_link}}, ctx.message.guild): await ctx.send(embed=embed.error(description=f"**{game_id}** not found")) else: await ctx.send(embed=embed.success(description=f"Replay link updated for **{game_id}**"))
async def accept(self, ctx, *, game_id: str=""): """Force a match into accepted state. This should only be used if a match is known to be valid but one or more of the participants is unwilling or unavailable to confirm. This command can only be used by an admin.""" if not game_id: await ctx.send(embed=embed.error(description="No game id specified")) return match = self.bot.db.find_match(game_id, ctx.message.guild) if not match: await ctx.send(embed=embed.error(description=f"`{game_id}` does not exist")) return if match["status"] == stc.ACCEPTED: return self.bot.db.confirm_match_for_users(game_id, ctx.message.guild) delta = self.bot.db.check_match_status(game_id, ctx.message.guild) if delta: await ctx.send(embed=embed.match_delta(game_id, delta))
async def cog_unload(self, ctx, *, cog: str): """Unloads a command cog.""" try: self.bot.unload_extension(f'app.cogs.{cog}') except Exception as e: await ctx.send(embed=embed.error( description=f'**ERROR** - {type(e).__name__} - {e}')) else: await ctx.send(embed=embed.success(description='**SUCCESS**'))
async def _config_threshold(self, ctx, *args): """Set the player or deck threshold to appear on the leaderboard.""" if len(args) < 2: await ctx.send(embed=embed.error(description="Not enough args, include a threshold type and threshold value")) return if not args[1].isdigit(): await ctx.send(embed=embed.error(description="Threshold value should be a number")) return thresh_t = args[0] value = int(args[1]) if thresh_t == "player": self.bot.db.set_player_match_threshold(value, ctx.message.guild) elif thresh_t == "deck": self.bot.db.set_deck_match_threshold(value, ctx.message.guild) else: await ctx.send(embed=embed.error(description="Unrecognized threshold type.")) return await ctx.send(embed=embed.success(description=f"**SUCCESS** - {thresh_t.upper()} threshold set to {value}"))
async def remove(self, ctx, *, game_id: str=""): """Removes a match from the tracking system. This should only be used if a match is known to be invalid. Only pending matches can be rejected. This command can only be used by an admin or the player who logged the match.""" if not game_id: await ctx.send(embed=embed.error(description="No game id specified")) return match = self.bot.db.find_match(game_id, ctx.message.guild) if not match: await ctx.send(embed=embed.error(description=f"`{game_id}` does not exist")) return if match["status"] == stc.ACCEPTED: await ctx.send(embed=embed.error(description="Cannot override an accepted match")) return if not (match["winner"] == ctx.message.author.id or checks.is_admin(ctx)): await ctx.send(embed=embed.error(description="Only a league admin or the match winner can remove a match")) return self.bot.db.delete_match(game_id, ctx.message.guild) await ctx.send(embed=embed.msg(description=f"`{game_id}` has been removed"))
async def _get_deck(self, ctx, link): """Helper method for deck fetching.""" if not link: await ctx.send(embed=embed.error( description="Please include a link to the decklist to preview." )) return None try: deck = deck_utils.extract(link) except err.DeckNotFoundError: await ctx.send(embed=embed.error( description="Failed to fetch decklist from the given link.")) return None except err.CardNotFoundError: await ctx.send(embed=embed.error( description="Failed to fetch commander from Scryfall.")) return None return deck
async def _confirm_deck(self, ctx, player, game_id): if not player["deck"]: emsg = embed.error( description=(f"No deck specified for **{ctx.message.author.name}**\n" \ f"Set your deck with `{ctx.prefix}use`, then type `{ctx.prefix}confirm` again") ) await ctx.send(embed=emsg) return False emsg = embed.msg( description=f"{ctx.message.author.mention} Was **{player['deck']}** the deck you piloted?" ) bot_msg = await ctx.send(embed=emsg) if await self._has_confirmed_deck(bot_msg, ctx): return True await ctx.send(embed=embed.error( description=f"Set your deck with the `{ctx.prefix}use` command, then type `{ctx.prefix}confirm` again") ) return False
async def _add_user(self, ctx, *, user: discord.User): """Add a user to the database.""" guild = ctx.message.guild if self.bot.db.add_member(user, guild): emsg = embed.msg( description= f"Registered **{user.name}** to the {guild.name} league") else: emsg = embed.error( description=f"**{user.name}** is already registered") await ctx.send(embed=emsg)
async def compare(self, ctx, *args): """Show player performances in pods containing only the mentioned players. If only one player is mentioned, then the default is to compare that player with the caller of the command.""" mentions = ctx.message.mentions if len(mentions) < 1: await ctx.send(embed=embed.error(description="Mention a player to compare with")) return if len(mentions) == 1 and mentions[0].id == ctx.message.author.id: await ctx.send(embed=embed.error(description="Not enough players mentioned")) return if len(mentions) == 1: mentions.append(ctx.message.author) if len(mentions) > 4: await ctx.send(embed=embed.error(description="Too many players mentioned")) return matches = self.bot.db.find_matches( {"players.user_id": {"$all": [user.id for user in mentions]}}, ctx.message.guild ) matches = list(matches) total = len(matches) if not total: await ctx.send(embed=embed.info(description="No matches found containing all mentioned players")) return data = {user.name: 0 for user in mentions} for match in matches: winner = next((user.name for user in mentions if user.id == match['winner']), None) if not winner: continue if winner in data: data[winner] += 1 players = ", ".join(data.keys()) emsg = embed.info(title=f"Games Containing: {players}") emsg.add_field(name="Total Matches", inline=False, value=str(total)) for user_name in data: wins = data[user_name] losses = total - wins percent = wins/total emsg.add_field(name=user_name, inline=False, value=f"{wins}-{losses}, {percent:.1%}") await ctx.send(embed=emsg)
async def _games_by_decks(self, ctx, *, deck_names: str = ""): """Displays a list of games filtered by decks. Include a comma-separated list of decks to filter by.""" if not deck_names: await ctx.send( embed=embed.error(ctx, description="No deck name included")) return deck_name_list = deck_names.split(',') if len(deck_name_list) > 4: await ctx.send(embed=embed.error( ctx, description="Games cannot contain more than 4 decks")) return deck_names = [] for deck_name in deck_name_list: deck = self.bot.db.find_deck(deck_name) if not deck: continue deck_names.append(deck['name']) if not deck_names: await ctx.send(embed=embed.error( ctx, description="No decks found with the given deck names")) return matches = self.bot.db.find_matches( {"players.deck": { "$all": deck_names }}, ctx.message.guild, limit=20) matches = list(matches) if not matches: await ctx.send(embed=embed.info( description=("No matches found containing " + ", ".join(deck_names)))) return title = "Games Containing: " + ", ".join(deck_names) emsgs = self._make_match_table(title, matches, winner_type="deck") for emsg in emsgs: await ctx.send(embed=emsg)
async def profile(self, ctx): """Display the profile of the mentioned player if they are registered. If no player is mentioned, show your own profile.""" users = utils.get_target_users(ctx) for user in users: profile_card = self._get_profile_card(user, ctx.message.guild) if not profile_card: emsg = embed.error( description = "**{}** is not a registered player".format(user.name) ) await ctx.send(embed=emsg) continue await ctx.send(embed=profile_card)
async def preview(self, ctx, *, deck_name: str = ""): """Show a preview of a decklist. Supported deck hosts are tappedout.net and deckstats.net.""" if not deck_name: await ctx.send(embed=embed.error( description="No deck name specified.")) return deck = self.bot.db.find_deck(deck_name) if not deck: await ctx.send(embed=embed.error( description= f"Deck not found. Use `{ctx.prefix}decks` to see a list of decks." )) return if not deck['link']: await ctx.send(embed=embed.info( description=f"**{deck['name']}** does not have a decklist")) return decklist = await self._get_deck(ctx, deck['link']) if not decklist: return commanders = " & ".join( [commander['name'] for commander in decklist['commanders']]) image_uris = scryfall.get_image_uris(decklist['commanders'][0]) emsg = embed.info( title=commanders, description=f"[Link to Decklist]({deck['link']})" ) \ .set_thumbnail(url=image_uris['art_crop']) for category in decklist['decklist']: category_name = category['category'] count = sum([card['count'] for card in category['cards']]) cards = [ f"{card['count']} {card['name']}" for card in category['cards'] ] emsg.add_field(name=f"{category_name} ({count})", value="\n".join(cards)) await ctx.send(embed=emsg)
async def _add_alias(self, ctx, *args): """Add one or more aliases for a deck. Names that are a multiple words must be enclosed in quotes.""" if len(args) < 2: await ctx.send(embed=embed.error( description='**ERROR** - Not enough args')) return deck_name = args[0] aliases = args[1:] deck = self.bot.db.find_deck(deck_name) if not deck: await ctx.send(embed=embed.error( description='**ERROR** - Deck not found')) return response = self.bot.db.add_deck_aliases(deck_name, aliases) if not response: await ctx.send(embed=embed.error( description='**ERROR** - No aliases added')) else: await ctx.send(embed=embed.success( description= f'**SUCCESS** - New aliases added for **{deck["name"]}**'))
async def remove_deck(self, ctx, *args): """Remove a deck from the league.""" if len(args) < 1: await ctx.send(embed=embed.error( description=f'**ERROR** - Not enough args')) return if len(args) > 1: await ctx.send(embed=embed.error( description= f'**ERROR** - Too many args. Make sure to enclose deck names in quotes.' )) return deck_name = args[0] response = self.bot.db.remove_deck(deck_name) if not response: await ctx.send(embed=embed.error( description=f'**ERROR** - Failed to remove {deck_name}')) return await ctx.send(embed=embed.success( description=f'**SUCCESS** - Removed {deck_name} from deck database' ))
async def register(self, ctx): """Register to this guild's EDH league to participate in match tracking.""" user = ctx.message.author guild = ctx.message.guild if self.bot.db.add_member(user, guild): emsg = embed.msg( description = "Registered **{}** to the {} league".format(user.name, guild.name) ) else: emsg = embed.error( description = "**{}** is already registered".format(user.name) ) await ctx.send(embed=emsg)
async def deck(self, ctx, *, deck_name: str = ""): """Displays detail info about a registered deck.""" if not deck_name: await ctx.send(embed=embed.error( description="No deck name specified")) return deck = self.bot.db.find_deck(deck_name) if not deck: await ctx.send(embed=embed.error( description=f"{deck_name} was not found")) return matches = list( self.bot.db.find_matches({"players.deck": deck['name']}, ctx.message.guild)) match_stats = self._get_match_stats(ctx, matches, deck['name']) if matches: match_history = self._make_match_history_table( matches[:5], deck['name']) else: match_history = "`N/A`" card = scryfall.search(deck['commanders'][0]) image_uris = scryfall.get_image_uris(card) emsg = embed.info(title=f"Deck: {deck['name']}") \ .add_field(name="Commanders", value=("\n".join(deck['commanders']))) \ .add_field(name="Aliases", value=("\n".join(deck['aliases']))) \ .add_field(name="# Matches", value=match_stats['entries']) \ .add_field(name="Meta %", value=match_stats['meta']) \ .add_field(name="Wins", value=match_stats['wins']) \ .add_field(name="Losses", value=match_stats['losses']) \ .add_field(name="Win %", value=match_stats['winrate']) \ .add_field(name="95% Confidence Interval", value=match_stats['confint']) \ .add_field(name="Recent Matches", value=match_history) \ .set_thumbnail(url=image_uris['small']) await ctx.send(embed=emsg)
async def command_help(self, ctx, name): command = self.bot.get_command(name) if not command: await ctx.send(embed=embed.error(description="Command not found")) return if command.name == "help": return emsg = embed.info(title=f"Command: {command.qualified_name}") emsg.add_field(name="Usage", inline=False, value=command.usage.format(ctx.prefix)) emsg.add_field(name="Description", inline=False, value=command.help) if command.aliases: aliases = ", ".join( [f"`{ctx.prefix}{alias}`" for alias in command.aliases]) emsg.add_field(name="Aliases", inline=False, value=aliases) await ctx.send(embed=emsg)