async def _list(self, ctx): if ctx.invoked_subcommand is None: listmsg = "" guild = ctx.guild channel = ctx.channel now = datetime.datetime.utcnow() + datetime.timedelta( hours=self.bot.guild_dict[guild.id]['configure_dict']['settings']['offset']) if checks.check_raidreport(ctx) or checks.check_exraidreport(ctx): raid_dict = self.bot.guild_dict[guild.id]['configure_dict']['raid'] if raid_dict.get('listings', {}).get('enabled', False): msg = await ctx.channel.send("*Raid list command disabled when listings are provided by server*") await asyncio.sleep(10) await msg.delete() await ctx.message.delete() return region = None if self.bot.guild_dict[guild.id]['configure_dict'].get('regions', {}).get('enabled', False) \ and raid_dict.get('categories', None) == 'region': region = raid_dict.get('category_dict', {}).get(channel.id, None) listmgmt_cog = self.bot.cogs.get('ListManagement') listmsg = await listmgmt_cog.get_listing_messages('raid', channel, region) elif checks.check_raidactive(ctx): newembed = discord.Embed(colour=discord.Colour.purple(), title="Trainer Status List") blue_emoji = utils.parse_emoji(guild, self.bot.config['team_dict']['mystic']) red_emoji = utils.parse_emoji(guild, self.bot.config['team_dict']['valor']) yellow_emoji = utils.parse_emoji(guild, self.bot.config['team_dict']['instinct']) team_emojis = {'instinct': yellow_emoji, 'mystic': blue_emoji, 'valor': red_emoji, 'unknown': "❔"} team_list = ["mystic", "valor", "instinct", "unknown"] status_list = ["maybe", "coming", "here"] trainer_dict = copy.deepcopy(self.bot.guild_dict[guild.id]['raidchannel_dict'][channel.id]['trainer_dict']) status_dict = {'maybe': {'total': 0, 'trainers': {}}, 'coming': {'total': 0, 'trainers': {}}, 'here': {'total': 0, 'trainers': {}}, 'lobby': {'total': 0, 'trainers': {}}} for trainer in trainer_dict: for status in status_list: if trainer_dict[trainer]['status'][status]: status_dict[status]['trainers'][trainer] = {'mystic': 0, 'valor': 0, 'instinct': 0, 'unknown': 0} for team in team_list: if trainer_dict[trainer]['party'][team] > 0: status_dict[status]['trainers'][trainer][team] = trainer_dict[trainer]['party'][ team] status_dict[status]['total'] += trainer_dict[trainer]['party'][team] for status in status_list: embed_value = None if status_dict[status]['total'] > 0: embed_value = u"\u200B" for trainer in status_dict[status]['trainers']: member = channel.guild.get_member(trainer) if member is not None: embed_value += f"{member.display_name} " for team in status_dict[status]['trainers'][trainer]: embed_value += team_emojis[team] * status_dict[status]['trainers'][trainer][team] embed_value += "\n" if embed_value is not None: newembed.add_field(name=f'**{status.capitalize()}**', value=embed_value, inline=True) if len(newembed.fields) < 1: newembed.description = "No one has RSVPd for this raid yet." await channel.send(embed=newembed) else: raise checks.errors.CityRaidChannelCheckFail()
def _get_team_count_str(self, ctx, ex_raid_dict): team_counts = {"instinct": 0, "mystic": 0, "valor": 0, "unknown": 0} trainer_dict = ex_raid_dict.setdefault('trainer_dict', {}) for trainer in trainer_dict: party = trainer_dict[trainer].get('party', {}) for team in ["mystic", "valor", "instinct", "unknown"]: team_counts[team] += party.get(team, 0) red_emoji = utils.parse_emoji(ctx.channel.guild, self.bot.config['team_dict']['valor']) yellow_emoji = utils.parse_emoji( ctx.channel.guild, self.bot.config['team_dict']['instinct']) blue_emoji = utils.parse_emoji(ctx.channel.guild, self.bot.config['team_dict']['mystic']) grey_emoji = '❔' return f"{yellow_emoji} : {team_counts['instinct']} - {blue_emoji} : {team_counts['mystic']} " \ f"- {red_emoji} : {team_counts['valor']} - {grey_emoji} : {team_counts['unknown']} "
async def starting(self, ctx, team: str = ''): """Signal that a raid is starting. **Usage**: `!starting/s [team]` Sends a message notifying all trainers who are at the raid and clears the waiting list. Starts a 2 minute lobby countdown during which time trainers can join this lobby using `!lobby`. Users who are waiting for a second group must reannounce with `!here`.""" guild_dict = self.bot.guild_dict channel = ctx.channel guild = ctx.guild ctx_startinglist = [] team_list = [] ctx.team_names = ["mystic", "valor", "instinct", "unknown"] team = team if team and team.lower() in ctx.team_names else "all" ctx.trainer_dict = copy.deepcopy(guild_dict[ guild.id]['raidchannel_dict'][channel.id]['trainer_dict']) regions = guild_dict[guild.id]['raidchannel_dict'][ channel.id]['regions'] if guild_dict[guild.id]['raidchannel_dict'][channel.id].get( 'type', None) == 'egg': if guild_dict[guild.id]['raidchannel_dict'][channel.id][ 'exp'] - 60 < datetime.datetime.now().timestamp(): starting_str = "Please tell me which raid boss has hatched before starting your lobby." else: starting_str = "How can you start when the egg hasn't hatched!?" await channel.send(starting_str) return if guild_dict[guild.id]['raidchannel_dict'][channel.id].get( 'lobby', False): starting_str = "Please wait for the group in the lobby to enter the raid." await channel.send(starting_str) return trainer_joined = False for trainer in ctx.trainer_dict: count = ctx.trainer_dict[trainer]['count'] user = guild.get_member(trainer) if team in ctx.team_names: if ctx.trainer_dict[trainer]['party'][team]: team_list.append(user.id) teamcount = ctx.trainer_dict[trainer]['party'][team] herecount = ctx.trainer_dict[trainer]['status']['here'] lobbycount = ctx.trainer_dict[trainer]['status']['lobby'] if ctx.trainer_dict[trainer]['status']['here'] and ( user.id in team_list): ctx.trainer_dict[trainer]['status'] = { 'maybe': 0, 'coming': 0, 'here': herecount - teamcount, 'lobby': lobbycount + teamcount } trainer_joined = True ctx_startinglist.append(user.mention) else: if ctx.trainer_dict[trainer]['status']['here'] and ( user.id in team_list or team == "all"): ctx.trainer_dict[trainer]['status'] = { 'maybe': 0, 'coming': 0, 'here': 0, 'lobby': count } trainer_joined = True ctx_startinglist.append(user.mention) if trainer_joined: joined = guild_dict[guild.id].setdefault('trainers', {}).setdefault(regions[0], {})\ .setdefault(trainer, {}).setdefault('joined', 0) + 1 guild_dict[guild.id]['trainers'][ regions[0]][trainer]['joined'] = joined if len(ctx_startinglist) == 0: starting_str = "How can you start when there's no one waiting at this raid!?" await channel.send(starting_str) return guild_dict[guild.id]['raidchannel_dict'][ channel.id]['trainer_dict'] = ctx.trainer_dict starttime = guild_dict[guild.id]['raidchannel_dict'][channel.id].get( 'starttime', None) if starttime: timestr = ' to start at **{}** '.format( starttime.strftime('%I:%M %p (%H:%M)')) guild_dict[guild.id]['raidchannel_dict'][ channel.id]['starttime'] = None else: timestr = ' ' starting_str = 'Starting - The group that was waiting{timestr}is starting the raid! ' \ 'Trainers {trainer_list}, if you are not in this group and are waiting for the next group, ' \ 'please respond with {here_emoji} or **!here**. If you need to ask those that just started ' \ 'to back out of their lobby, use **!backout**'\ .format(timestr=timestr, trainer_list=', '.join(ctx_startinglist), here_emoji=utils.parse_emoji(guild, self.bot.config['here_id'])) guild_dict[guild.id]['raidchannel_dict'][channel.id]['lobby'] = { "exp": time.time() + 120, "team": team } if starttime: starting_str += '\n\nThe start time has also been cleared, new groups can set a new start time with' \ ' **!starttime HH:MM AM/PM** (You can also omit AM/PM and use 24-hour time!).' report_channel = self.bot.get_channel(guild_dict[ guild.id]['raidchannel_dict'][channel.id]['reportcity']) raidmsg = await channel.fetch_message(guild_dict[ guild.id]['raidchannel_dict'][channel.id]['raidmessage']) reportmsg = await report_channel.fetch_message(guild_dict[ guild.id]['raidchannel_dict'][channel.id]['raidreport']) embed = raidmsg.embeds[0] embed_indices = await embed_utils.get_embed_field_indices(embed) embed.set_field_at(embed_indices["next"], name="**Next Group**", value="Set with **!starttime**", inline=True) try: await raidmsg.edit(content=raidmsg.content, embed=embed) except discord.errors.NotFound: pass try: await reportmsg.edit(content=reportmsg.content, embed=embed) except discord.errors.NotFound: pass await channel.send(starting_str) action_time = round(ctx.message.created_at.timestamp()) ctx.bot.loop.create_task(self.lobby_countdown(ctx, team, action_time)) regions = guild_dict[channel.guild.id]['raidchannel_dict'][ channel.id].get('regions', None) if regions: listmgmt_cog = self.bot.cogs.get('ListManagement') await listmgmt_cog.update_listing_channels(channel.guild, 'raid', edit=True, regions=regions) raid_cog = self.bot.cogs.get('RaidCommands') await raid_cog.add_db_raid_action(channel, "lobby start", action_time)
async def _setup_profile(self, ctx, file, u): team_role_names = [r.lower() for r in self.bot.team_color_map.keys()] for team in team_role_names: temp_role = discord.utils.get(ctx.guild.roles, name=team) if temp_role: # and the user has this role, if temp_role in ctx.author.roles: await ctx.message.delete() err_msg = f"{ctx.author.mention} your team is already set. Ask for help if you need to change it." \ "\nIf you would like to update your profile, use `!set profile`" await ctx.channel.send(embed=discord.Embed( colour=discord.Colour.red(), description=err_msg)) image_utils.cleanup_file(file, f"screenshots/profile") try: data = json.loads('{"image_url": "' + u + '"}') image_info = await self.bot.make_request(data, 'profile') scan_team = image_info['team'] level = image_info['level'] trainer_name = image_info['trainer_name'] xp = image_info['xp'] except Exception as e: self.bot.logger.info( f"Request to image processing server failed with error: {e}") try: scan_team, level, trainer_name, xp = await image_scan.scan_profile( file) except AttributeError: scan_team = None if not scan_team: return await ctx.channel.send(embed=discord.Embed( colour=discord.Colour.red(), description= "No team color identified. Please try a different image.")) team_role = discord.utils.get(ctx.guild.roles, name=scan_team) if team_role is not None: await ctx.author.add_roles(team_role) trainer_dict = self.bot.guild_dict[ctx.guild.id].setdefault('trainers', {}) \ .setdefault('info', {}).setdefault(ctx.author.id, {}) name_prompt = await ctx.send( f"{ctx.author.mention} Is this your trainer name: **{trainer_name}** ?" "\nReply with **Y**es if correct, or your actual trainer name if not." ) try: response_msg = await self.bot.wait_for( 'message', timeout=30, check=(lambda reply: reply.author == ctx.message.author)) except asyncio.TimeoutError: response_msg = None if response_msg: response = response_msg.clean_content.lower() if response == 'y' or response == 'yes': pass else: trainer_name = response trainer_names = self.bot.guild_dict[ctx.guild.id].setdefault( 'trainer_names', {}) trainer_names[trainer_name] = ctx.author.id trainer_dict['trainername'] = trainer_name await self._delete_with_pause([name_prompt, response_msg]) level_prompt = await ctx.send( f"{ctx.author.mention} Are you level **{level}**?" " Your level plus the XP displayed will determine your total XP." "\nReply with **Y**es if correct, or your actual level if not.") try: response_msg = await self.bot.wait_for( 'message', timeout=30, check=(lambda reply: reply.author == ctx.message.author)) except asyncio.TimeoutError: response_msg = None if response_msg: response = response_msg.clean_content.lower() if response == 'y' or response == 'yes': pass else: level = response await self._delete_with_pause([level_prompt, response_msg]) if xp and level: try: level = int(level) xp = int(xp) level_xp = level_xp_map[level] xp = xp + level_xp trainer_dict['xp'] = xp except ValueError: pass elif level == '40': trainer_dict['xp'] = level_xp_map[40] quickbadge_cog = self.bot.cogs.get('QuickBadge') await quickbadge_cog.set_fourty(ctx) fourty_prompt = await ctx.send( f"{ctx.author.mention} You have been verified as a level 40 Trainer. \n" "Reply with your **Total XP** or with **N**o to skip.") try: response_msg = await self.bot.wait_for( 'message', timeout=60, check=(lambda reply: reply.author == ctx.message.author)) except asyncio.TimeoutError: response_msg = None if response_msg: response = response_msg.clean_content.lower() if response == 'n' or response == 'no': pass else: trainer_dict['xp'] = response await self._delete_with_pause([fourty_prompt, response_msg]) friend_prompt = await ctx.send( f"{ctx.author.mention} Would you like to add your Friend Code to your profile?\n" "Reply with your **Friend Code** or with **N**o to skip.") try: response_msg = await self.bot.wait_for( 'message', timeout=60, check=(lambda reply: reply.author == ctx.message.author)) except asyncio.TimeoutError: response_msg = None if response_msg: response = response_msg.clean_content.lower() if response == 'n' or response == 'no': pass else: trainer_dict['code'] = response await self._delete_with_pause([friend_prompt, response_msg]) team_role = discord.utils.get(ctx.guild.roles, name=scan_team) if team_role is not None: await ctx.author.add_roles(team_role) team_emoji = utils.parse_emoji(ctx.channel.guild, self.bot.config['team_dict'][scan_team]) await ctx.invoke(self.bot.get_command('profile'), user=ctx.author) await ctx.channel.send( f"{ctx.author.mention} your team has been set to **{scan_team}** {team_emoji}!" "\nIf you would like to make changes or update your profile use `!set profile`" ) image_utils.cleanup_file(file, f"screenshots/profile")
async def team(self, ctx, *, content): """Set your team role. Usage: !team <team name> The team roles have to be created manually beforehand by the server administrator.""" guild = ctx.guild toprole = guild.me.top_role.name position = guild.me.top_role.position team_msg = ' or '.join([ '**!team {0}**'.format(team) for team in self.bot.config['team_dict'].keys() ]) high_roles = [] guild_roles = [] lowercase_roles = [] harmony = None for role in guild.roles: if (role.name.lower() in self.bot.config['team_dict']) and (role.name not in guild_roles): guild_roles.append(role.name) lowercase_roles = [element.lower() for element in guild_roles] for team in self.bot.config['team_dict'].keys(): if team.lower() not in lowercase_roles: try: temp_role = await guild.create_role(name=team.lower(), hoist=False, mentionable=True) guild_roles.append(team.lower()) except discord.errors.HTTPException: await ctx.channel.send('Maximum guild roles reached.') return if temp_role.position > position: high_roles.append(temp_role.name) if high_roles: await ctx.channel.send( 'My roles are ranked lower than the following team roles: ' '**{higher_roles_list}**\nPlease get an admin to move my roles above them!' .format(higher_roles_list=', '.join(high_roles))) return role = None team_split = content.lower().split() entered_team = team_split[0] entered_team = ''.join([i for i in entered_team if i.isalpha()]) if entered_team in lowercase_roles: index = lowercase_roles.index(entered_team) role = discord.utils.get(guild.roles, name=guild_roles[index]) if 'harmony' in lowercase_roles: index = lowercase_roles.index('harmony') harmony = discord.utils.get(guild.roles, name=guild_roles[index]) # Check if user already belongs to a team role by # getting the role objects of all teams in team_dict and # checking if the message author has any of them. for team in guild_roles: for team in guild_roles: temp_role = discord.utils.get(guild.roles, name=team) if temp_role: # and the user has this role, if (temp_role in ctx.author.roles) and (harmony not in ctx.author.roles): # then report that a role is already assigned await ctx.channel.send('You already have a team role!') return if role and (role.name.lower() == 'harmony') and (harmony in ctx.author.roles): # then report that a role is already assigned await ctx.channel.send('You are already in Team Harmony!') return # If the role isn't valid, something is misconfigured, so fire a warning. else: await ctx.channel.send( '{team_role} is not configured as a role on this server. ' 'Please contact an admin for assistance.'.format( team_role=team)) return # Check if team is one of the three defined in the team_dict if entered_team not in self.bot.config['team_dict'].keys(): await ctx.channel.send( '"{entered_team}" isn\'t a valid team! Try {available_teams}'. format(entered_team=entered_team, available_teams=team_msg)) return # Check if the role is configured on the server elif role is None: await ctx.channel.send( 'The "{entered_team}" role isn\'t configured on this server! Contact an admin!' .format(entered_team=entered_team)) else: try: if harmony and (harmony in ctx.author.roles): await ctx.author.remove_roles(harmony) await ctx.author.add_roles(role) await ctx.channel.send( 'Added {member} to Team {team_name}! {team_emoji}'.format( member=ctx.author.mention, team_name=role.name.capitalize(), team_emoji=utils.parse_emoji( guild, self.bot.config['team_dict'][entered_team]))) await ctx.author.send( "Now that you've set your team, " "head to <#538883360953729025> to set up your desired regions" ) except discord.Forbidden: await ctx.channel.send("I can't add roles!")