async def _prefix(self, ctx, *, new_prefix: str = None): """Get and set server prefix. Use the argument 'reset' to reset the guild prefix to default. """ if not ctx.guild: if new_prefix: embed = utils.make_embed(msg_type='error', title="Prefix cannot be set in DMs.") return await ctx.send(embed=embed) embed = utils.make_embed(msg_type='info', title="Prefix is {}".format(prefix)) return await ctx.send(embed=embed) if not new_prefix: guild_prefix = ctx.bot.prefixes.get(ctx.guild.id) prefix = guild_prefix or ctx.bot.default_prefix embed = utils.make_embed(msg_type='info', title="Prefix is {}".format(prefix)) return await ctx.send(embed=embed) if await checks.check_is_admin(ctx): await db.execute_sql( "INSERT OR REPLACE INTO prefixes(guild_id, prefix)" "VALUES(?, ?)", (ctx.guild.id, new_prefix)) ctx.bot.prefixes[ctx.guild.id] = new_prefix embed = utils.make_embed( msg_type='info', title="Prefix set to {}".format(new_prefix)) return await ctx.send(embed=embed) embed = utils.make_embed(msg_type='error', title="Prefix can only be set by admins.") return await ctx.send(embed=embed)
async def channelperms(self, ctx): """Gets bot permissions for the current channel.""" chan_perms = ctx.channel.permissions_for(ctx.guild.me) req_perms = ctx.bot.req_perms perms_compare = chan_perms >= req_perms core_dir = ctx.bot.core_dir data_dir = os.path.join(core_dir, '..', 'data') data_file = 'permissions.json' msg = "Channel Permissions: {}\n".format(chan_perms.value) msg += "Met Minimum Permissions: {}\n\n".format(str(perms_compare)) with open(os.path.join(data_dir, data_file), "r") as perm_json: perm_dict = json.load(perm_json) for perm, bitshift in perm_dict.items(): if bool((req_perms.value >> bitshift) & 1): if bool((chan_perms.value >> bitshift) & 1): msg += ":white_small_square: {}\n".format(perm) else: msg += ":black_small_square: {}\n".format(perm) try: if chan_perms.embed_links: embed = utils.make_embed(msg_type='info', title='Channel Permissions', content=msg) await ctx.send(embed=embed) else: await ctx.send(msg) except discord.errors.Forbidden: embed = utils.make_embed(msg_type='info', title='Channel Permissions', content=msg) await ctx.author.send(embed=embed)
async def reload_em(self, ctx): """Reload Extension Manager.""" bot = ctx.bot try: bot.unload_extension('ultron.core.extension_manager') bot.load_extension('ultron.core.extension_manager') embed = utils.make_embed(msg_type='success', title='Extension Manager reloaded.') await ctx.send(embed=embed) except Exception as e: msg = "{}: {}".format(type(e).__name__, e) embed = utils.make_embed(msg_type='error', title='Error loading Extension Manager', content=msg) await ctx.send(embed=embed)
async def _nickname(self, ctx, *, nickname: str): """Sets bot nickname""" try: await ctx.guild.me.edit(nick=nickname) except discord.Forbidden: embed = utils.make_embed( msg_type='success', title="Failed to set nickname", content=("I'm missing permissions to change my nickname. " "Use **{}get guildperms** to check permissions." "").format(ctx.prefix)) await ctx.send(embed=embed) else: embed = utils.make_embed(msg_type='success', title="Nickname set.") await ctx.send(embed=embed)
async def _username(self, ctx, *, username: str): """Sets bot username""" try: await ctx.bot.user.edit(username=username) except discord.HTTPException: embed = utils.make_embed( msg_type='error', title="Failed to change name", content=("Remember that you can only do it up to 2 times an " "hour. Use nicknames if you need frequent changes. " "**{}set nickname**").format(ctx.prefix)) await ctx.send(embed=embed) else: embed = utils.make_embed(msg_type='success', title="Username set.") await ctx.send(embed=embed)
async def post_operation(self, operation, very_soon): if very_soon: title = 'Fleet Starting In Less Than 5 Minutes' elif very_soon is None: title = 'New Fleet Posted' else: title = 'Fleet Starting In Less Than 30 Minutes' doctrine = 'N/A' if len(operation['Doctrines']) > 0: doctrine = operation['Doctrines'] embed = make_embed( title=title, title_url='https://fleet-up.com/Operation#{}'.format( operation['Id'])) embed.set_footer(icon_url=self.bot.user.avatar_url, text="Provided Via Ultron Bot & Fleet-Up") embed.set_thumbnail( url="https://fleet-up.com/Content/Images/logo_title.png") embed.add_field( name="Fleet Information", value='Fleet Name: {}\nFleet Time: {} EVE\nPlanned Doctrines: {}\n' 'Form-Up Location: {} {}\nOrganizer: {}\n\nDetails: {}'.format( operation['Subject'], operation['StartString'], doctrine, operation['Location'], operation['LocationInfo'], operation['Organizer'], operation['Details'])) dest = self.bot.get_channel(int(self.config.fleetUp['channel_id'])) await dest.send(embed=embed)
async def charinfo(self, ctx, *, characters: str): """Shows you information about unicode characters. Only up to 25 characters at a time. """ if len(characters) > 25: return await ctx.send( 'Too many characters ({}/25)'.format(len(characters))) charlist = [] rawlist = [] for char in characters: digit = '{0:x}'.format(ord(char)) url = "http://www.fileformat.info/info/unicode/char/{}".format( digit) name = "[{}]({})".format(unicodedata.name(char, ''), url) u_code = '\\U{0:>08}'.format(digit) if len(str(digit)) <= 4: u_code = '\\u{0:>04}'.format(digit) charlist.append( ' '.join(['`{}`:'.format(u_code.ljust(10)), name, '-', char])) rawlist.append(u_code) embed = utils.make_embed( msg_type='info', title='Character Info', content='\n'.join(charlist)) if len(characters) > 1: embed.add_field( name='Raw', value="`{}`".format(''.join(rawlist)), inline=False) await ctx.send(embed=embed)
async def _rpg_top(self, ctx): """Get the top RPG players""" sql = ''' SELECT * FROM eve_rpg_players WHERE `player_id` = (?) ''' values = (ctx.message.author.id,) result = await db.select_var(sql, values) sql = ''' SELECT * FROM eve_rpg_players ORDER BY `level` DESC LIMIT 10 ''' top_levels = await db.select(sql) top_levels_array = [] for levels in top_levels: top_levels_user = self.bot.get_user(int(levels[2])) top_levels_array.append('{} - Level {}'.format(top_levels_user.display_name, levels[5])) levels_list = '\n'.join(top_levels_array) sql = ''' SELECT * FROM eve_rpg_players ORDER BY `kills` DESC LIMIT 10 ''' top_killers = await db.select(sql) top_killers_array = [] for killers in top_killers: top_killer_user = self.bot.get_user(int(killers[2])) top_killers_array.append('{} - {} Kills'.format(top_killer_user.display_name, killers[3])) killers_list = '\n'.join(top_killers_array) if result is None: return await ctx.author.send('**Error** - No player found. You must be part of the game to view this') else: embed = make_embed(guild=ctx.guild) embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via Ultron Bot") embed.add_field(name="Level Leaderboard", value=levels_list, inline=False) embed.add_field(name="Kills Leaderboard", value=killers_list, inline=False) await ctx.channel.send(embed=embed)
async def _game(self, ctx, *, game: str): """Sets bot game status""" status = ctx.me.status game = discord.Game(name=game) await ctx.bot.change_presence(status=status, game=game) embed = utils.make_embed(msg_type='success', title='Game set.') await ctx.send(embed=embed)
async def _rpg_stats(self, ctx): """Get your RPG Stats""" sql = ''' SELECT * FROM eve_rpg_players WHERE `player_id` = (?) ''' values = (ctx.message.author.id,) result = await db.select_var(sql, values) sql = ''' SELECT * FROM eve_rpg_players ORDER BY `level` DESC LIMIT 1 ''' top_level = await db.select(sql) top_level_user = self.bot.get_user(int(top_level[0][2])) sql = ''' SELECT * FROM eve_rpg_players ORDER BY `kills` DESC LIMIT 1 ''' top_killer = await db.select(sql) top_killer_user = self.bot.get_user(int(top_killer[0][2])) if result is None: return await ctx.author.send('**Error** - No player found.') else: ship_attack, ship_defense, ship_maneuverability, ship_tracking = await self.ship_attributes(result) item_attack, item_defense, item_maneuverability, item_tracking = await self.item_attributes(result) ship_stats = ' {}/{}/{}/{}'.format(ship_attack, ship_defense, ship_maneuverability, ship_tracking) item_stats = ' {}/{}/{}/{}'.format(item_attack, item_defense, item_maneuverability, item_tracking) embed = make_embed(guild=ctx.guild) embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via Ultron Bot") embed.add_field(name="Stats", value='\n Level: {}\nXP: {}/100\nShip : {}\nAttack/Defense/Maneuverability/Tracking: {}\n' 'Items: {}\nItem Bonuses (Already applied to ship): {}\nKills: {}\nLosses: {}'.format( result[0][5], result[0][6], result[0][7], ship_stats, result[0][8], item_stats, result[0][3], result[0][4])) embed.add_field(name="Top Players", value='\n Top Level: {} (Level {})\nMost Kills: {} ({} Kills)'.format( top_level_user.display_name, top_level[0][5], top_killer_user.display_name, top_killer[0][3]), inline=False) await ctx.channel.send(embed=embed)
async def report_upcoming(self, ctx, system_data, fight_type, defender_name): constellation_data = await self.bot.esi_data.constellation_info( system_data['constellation_id']) constellation_name = constellation_data['name'] region_id = constellation_data['region_id'] region_data = await self.bot.esi_data.region_info(region_id) region_name = region_data['name'] zkill_link = "https://zkillboard.com/system/{}".format( system_data['system_id']) dotlan_link = "http://evemaps.dotlan.net/system/{}".format( system_data['name'].replace(' ', '_')) constellation_dotlan = "http://evemaps.dotlan.net/map/{}/{}".format( region_name.replace(' ', '_'), constellation_name.replace(' ', '_')) title = 'Upcoming Sov Battle In: {}'.format(system_data['name']) embed = make_embed( msg_type='info', title=title, title_url=dotlan_link, content= '[ZKill]({}) / [{}]({}) / [Constellation: {}]({})\nDo this command again once ' 'the battle has begun to receive live updates.'.format( zkill_link, system_data['name'], dotlan_link, constellation_name, constellation_dotlan)) embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via ultron Bot") embed.add_field(name="Upcoming Sov Battle", value='Defender:\nFight Type:') embed.add_field(name="-", value='{}\n{}'.format(defender_name, fight_type), inline=True) await ctx.channel.send(embed=embed)
async def report_ended(self, system_data, tracked_fight_type, winner, channel_id): fight_type_raw = tracked_fight_type fight_type = fight_type_raw.replace('_', ' ').title() constellation_data = await self.bot.esi_data.constellation_info( system_data['constellation_id']) constellation_name = constellation_data['name'] region_id = constellation_data['region_id'] region_data = await self.bot.esi_data.region_info(region_id) region_name = region_data['name'] zkill_link = "https://zkillboard.com/system/{}".format( system_data['system_id']) dotlan_link = "http://evemaps.dotlan.net/system/{}".format( system_data['name'].replace(' ', '_')) constellation_dotlan = "http://evemaps.dotlan.net/map/{}/{}".format( region_name.replace(' ', '_'), constellation_name.replace(' ', '_')) title = 'Sov Battle In {} has ended.'.format(system_data['name']) embed = make_embed( msg_type='info', title=title, title_url=dotlan_link, content= '[ZKill]({}) / [{}]({}) / [Constellation: {}]({})\n\nThe {} fight has ended with' ' the {} claiming victory.'.format(zkill_link, system_data['name'], dotlan_link, constellation_name, constellation_dotlan, fight_type, winner)) embed.set_footer(icon_url=self.bot.user.avatar_url, text="Provided Via ultron Bot") channel = self.bot.get_channel(channel_id) try: await channel.send(embed=embed) except: return None
async def _status(self, ctx): """Shows the current status of TQ.""" # Spam Check global status, player_count self.logger.info('EveStatus - {} requested server info.'.format( str(ctx.message.author))) data = await ctx.bot.esi_data.server_info() try: if data.get('start_time'): status = 'Online' player_count = data.get('players') except Exception: status = 'Offline' player_count = 'N/A' embed = make_embed(guild=ctx.guild) embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via Ultron Bot") embed.set_thumbnail( url="https://image.eveonline.com/Alliance/434243723_64.png") embed.add_field(name="Status", value="Server State:\nPlayer Count:", inline=True) embed.add_field(name="-", value="{}\n{}".format(status, player_count), inline=True) dest = ctx.author if ctx.bot.config.dm_only else ctx await dest.send(embed=embed) if ctx.bot.config.delete_commands: await ctx.message.delete()
async def status(self, ctx, *, status: str): """Sets bot status Available statuses: online idle dnd """ statuses = { "online": discord.Status.online, "idle": discord.Status.idle, "dnd": discord.Status.dnd, "invisible": discord.Status.invisible } game = ctx.me.game try: status = statuses[status.lower()] except KeyError: await ctx.bot.send_cmd_help(ctx) else: await ctx.bot.change_presence(status=status, game=game) embed = utils.make_embed( msg_type='success', title="Status changed to {}.".format(status)) await ctx.send(embed=embed)
async def _break(self, ctx): """Simulates a sudden disconnection.""" embed = utils.make_embed(msg_type='warning', title='Faking a crash...') try: await ctx.send(embed=embed) except discord.HTTPException: pass await ctx.bot.logout()
async def _avatar(self, ctx, *, avatar_url: str): """Sets bot avatar""" session = aiohttp.ClientSession() async with session.get(avatar_url) as req: data = await req.read() await session.close() try: await ctx.bot.user.edit(avatar=data) except discord.HTTPException: embed = utils.make_embed( msg_type='error', title="Failed to set avatar", content=("Remember that you can only do it up to 2 " "times an hour. URL must be a direct link to " "a JPG / PNG.")) await ctx.send(embed=embed) else: embed = utils.make_embed(msg_type='success', title="Avatar set.") await ctx.send(embed=embed)
async def _restart(self, ctx): """Restarts the bot""" embed = utils.make_embed(title='Restarting.', msg_colour='red', icon="https://i.imgur.com/uBYS8DR.png") try: await ctx.send(embed=embed) except discord.HTTPException: pass await ctx.bot.shutdown(restart=True)
async def _shutdown(self, ctx): """Shuts down the bot""" embed = utils.make_embed(title='Shutting down.', msg_colour='red', icon="https://i.imgur.com/uBYS8DR.png") try: await ctx.send(embed=embed) except discord.HTTPException: pass await ctx.bot.shutdown()
async def runas(self, ctx, member: discord.Member, *, new_cmd): """Run a command as a different member.""" if await ctx.bot.is_owner(member): embed = utils.make_embed( msg_type='error', title='No, you may not run as owner.') return await ctx.send(embed=embed) ctx.message.content = new_cmd ctx.message.author = member await ctx.bot.process_commands(ctx.message)
async def _uptime(self, ctx): """Shows bot uptime""" uptime_str = ctx.bot.uptime_str embed = utils.make_embed(title='Uptime', content=uptime_str, msg_colour='blue', icon="https://i.imgur.com/82Cqf1x.png") try: await ctx.send(embed=embed) except discord.errors.Forbidden: await ctx.send("Uptime: {}".format(uptime_str))
async def _range(self, ctx): """Provides Jump Range. '!range system SHIP' Gives you the JDC/JF 5 range for a ship by default. '!range system SHIP 4' This is also possible to declare a JDC besides 5.""" self.logger.info('JumpRange - {} requested a jump range map.'.format(str(ctx.message.author))) try: system = ctx.message.content.split(' ')[1].title() if '-' in system: system = system.upper() else: system = system.title() ship = ctx.message.content.split(' ')[2].title() except Exception: dest = ctx.author if ctx.bot.config.dm_only else ctx return await dest.send('**ERROR:** Do !help range for more info') search = 'solar_system' system_id = await ctx.bot.esi_data.esi_search(system, search) if system_id is None: dest = ctx.author if ctx.bot.config.dm_only else ctx self.logger.info('JumpPlanner ERROR - {} could not be found'.format(system)) return await dest.send('**ERROR:** No system found with the name {}'.format(system)) if system_id is False: dest = ctx.author if ctx.bot.config.dm_only else ctx self.logger.info('JumpPlanner ERROR - {} could not be found'.format(system)) return await dest.send('**ERROR:** Multiple systems found matching {}, please be more specific'. format(system)) system_info = await ctx.bot.esi_data.system_info(system_id['solar_system'][0]) system = system_info['name'] try: jdc = ctx.message.content.split(' ')[3] if len(jdc) > 1: dest = ctx.author if ctx.bot.config.dm_only else ctx return await dest.send('**ERROR:** Improper JDC skill level'.format(system)) except Exception: jdc = 5 item_id = await ctx.bot.esi_data.item_id(ship) accepted_ship_groups = [898, 659, 485, 547, 902, 30, 1538] ship_info = await ctx.bot.esi_data.item_info(item_id) ship_group_id = ship_info['group_id'] if ship_group_id not in accepted_ship_groups: dest = ctx.author if ctx.bot.config.dm_only else ctx self.logger.info('JumpRange ERROR - {} is not a Jump Capable Ship'.format(ship)) return await dest.send('**ERROR:** No Jump Capable Ship Found With The Name {}'.format(ship)) url = 'http://evemaps.dotlan.net/range/{},{}/{}'.format(ship, jdc, system) embed = make_embed(guild=ctx.guild) embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via Ultron Bot + Dotlan") embed.add_field(name="Jump range for a {} from {} with JDC {}".format(ship, system, jdc), value=url) dest = ctx.author if ctx.bot.config.dm_only else ctx await dest.send(embed=embed) if ctx.bot.config.delete_commands: await ctx.message.delete()
async def yt(self, ctx, *, url): """Streams from a URL `!yt https://www.youtube.com/watch?v=RubBzkZzpUA` to stream audio `!skip` Votes to skip a song, requires 3 votes. `!pause` Pauses the current song. `!play` Resumes the current paused song. `!stop` to stop the current song and remove the bot from the voice channel. `!volume 0-100` to set the volume percentage.""" global dest if ctx.author.id in self.skipped_user: return await dest.send( 'You just got skipped, let someone else pick something') if ctx.author.voice: if ctx.voice_client is None: await ctx.author.voice.channel.connect() if ctx.author.voice.channel != ctx.voice_client.channel and not ctx.voice_client.is_playing( ): await ctx.author.voice.channel.move_to() if ctx.voice_client.is_playing(): dest = ctx.author if ctx.bot.config.dm_only else ctx return await dest.send( '{} is already playing a song. You can do !skip to vote to skip this song.' .format(self.current_provider)) if ctx.author.voice.channel != ctx.voice_client.channel: await ctx.author.voice.channel.move_to() player = await YTDLSource.from_url(url, loop=self.bot.loop) ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None) embed = make_embed( msg_type='info', title='Now playing: {}'.format(player.title), content="Requested By: {}\n[Direct Link]({})".format( ctx.author.name, player.url)) embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via Ultron Bot") dest = ctx.author if ctx.bot.config.dm_only else ctx self.voice = ctx.voice_client await dest.send(embed=embed) if ctx.guild is not None and ctx.channel.permissions_for( ctx.guild.me).manage_messages: await ctx.message.delete() self.current_provider.clear() self.skipped_user.clear() self.skip_votes.clear() self.current_provider.add(ctx.author.id) else: return await ctx.send( "ERROR: You need to be in a voice channel to do that.")
async def _bot_invite(self, ctx, plain_url: bool = False): """Shows bot invite url""" invite_url = ctx.bot.invite_url if plain_url: await ctx.send("Invite URL: <{}>".format(invite_url)) return else: embed = utils.make_embed( title='Click to invite me to your server!', title_url=invite_url, msg_colour='blue', icon="https://i.imgur.com/DtPWJPG.png") try: await ctx.send(embed=embed) except discord.errors.Forbidden: await ctx.send("Invite URL: <{}>".format(invite_url))
async def _about(self, ctx): """Shows info about Ultron""" memory = memory_usage() memory_format = '{0:,.2f}'.format(memory['rss'] / 1024) bot = ctx.bot author_repo = "https://github.com/shibdib" bot_repo = author_repo + "/Ultron" server_url = "https://discord.gg/ZWmzTP3" owner = "Ingame: Mr Twinkie" uptime_str = bot.uptime_str invite_str = ("[Click to invite me to your server!]({})" "").format(bot.invite_url) about = ( "I'm a Python based Discord bot to help organise and coordinate EVE Online " "communities!\n\n" "To learn about what I do either use the `!help` command, or " "contact J0HN SHEPPARD for support!" "").format(bot_repo=bot_repo, server_invite=server_url) member_count = 0 server_count = 0 for guild in bot.guilds: server_count += 1 member_count += len(guild.members) embed = utils.make_embed(msg_type='info', title="About Ultron", content=about) embed.set_thumbnail(url=bot.user.avatar_url_as(format='png')) embed.add_field(name="Creator", value=owner) embed.add_field(name="Uptime", value=uptime_str) embed.add_field(name="Servers", value=server_count) embed.add_field(name="Members", value=member_count) embed.add_field(name="Commands Used", value=bot.command_count) embed.add_field(name="Messages Read", value=bot.message_count) embed.add_field(name="Current Memory Usage", value='{} MB'.format(memory_format)) embed.add_field(name="Invite Link", value=invite_str, inline=False) footer_txt = ("For support, contact J0HN SHEPPARD") embed.set_footer(text=footer_txt) try: await ctx.send(embed=embed) except discord.HTTPException: await ctx.send("I need the `Embed links` permission to send this")
async def purge(self, ctx, msg_number: int = 10): """Delete a number of messages from the channel. Default is 10. Max 100.""" if ctx.guild.id == 202724765218242560: return if msg_number > 100: embed = utils.make_embed( msg_type='info', title="ERROR", content="No more than 100 messages can be purged at a time.", guild=ctx.guild) await ctx.send(embed=embed) return deleted = await ctx.channel.purge(limit=msg_number) result_msg = await ctx.send('Deleted {} message{}'.format( len(deleted), "s" if len(deleted) > 1 else "")) await asyncio.sleep(3) await result_msg.delete()
async def _time(self, ctx): """Shows the time in a range of timezones.""" self.logger.info('EveTime - {} requested time info.'.format(str(ctx.message.author))) tz_field = [] time_field = [] for display, zone in self.TIMEZONES.items(): tz_field.append("**{}**".format(display)) time_field.append(datetime.now(pytz.timezone(zone)).strftime('%H:%M')) embed = make_embed(guild=ctx.guild) embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via Ultron Bot") embed.add_field(name="Time Zones", value='\n'.join(tz_field), inline=True) embed.add_field(name="Time", value='\n'.join(time_field), inline=True) dest = ctx.author if ctx.bot.config.dm_only else ctx await dest.send(embed=embed) if ctx.bot.config.delete_commands: await ctx.message.delete()
async def _guilds(self, ctx): """List the guild names""" server_count = 0 bot = ctx.bot guilds = [] for guild in bot.guilds: server_count += 1 guilds.append(guild.name) guild_list = '\n'.join(guilds) split_string = lambda x, n: [x[i:i + n] for i in range(0, len(x), n)] guild_list = split_string(guild_list, 1024) for split_list in guild_list: embed = utils.make_embed(msg_type='info', title="Ultron Server Info") embed.set_thumbnail(url=bot.user.avatar_url_as(format='png')) embed.add_field(name="Server Count", value=server_count) embed.add_field(name="Servers", value=split_list, inline=False) await ctx.send(embed=embed)
async def _fleets(self, ctx): data = await self.request_data(self.config) if data is not None: upcoming = False embed = make_embed(title='Upcoming Fleets', title_url='https://fleet-up.com/') embed.set_footer(icon_url=self.bot.user.avatar_url, text="Provided Via Ultron Bot & Fleet-Up") embed.set_thumbnail( url="https://fleet-up.com/Content/Images/logo_title.png") for operation in data: current_eve = int( datetime.now(pytz.timezone('UTC')).timestamp()) fleet_time = int( re.findall(r'\d+', operation['Start'])[0][:-3]) seconds_from_now = fleet_time - current_eve if seconds_from_now > 0: upcoming = True doctrine = 'N/A' horizontal_rule = '' if len(data) > 1: horizontal_rule = '\n\n-------' if len(operation['Doctrines']) > 0: doctrine = operation['Doctrines'] embed.add_field( name="Fleet Information", value='Fleet Name: {}\nFleet Time: {} EVE\n' 'Planned Doctrines: {}\nForm-Up Location: {} {}\n' 'Organizer: {}\n\nDetails: {}{}'.format( operation['Subject'], operation['StartString'], doctrine, operation['Location'], operation['LocationInfo'], operation['Organizer'], operation['Details'], horizontal_rule), inline=False) if upcoming: dest = ctx.author if ctx.bot.config.dm_only else ctx await dest.send(embed=embed) if ctx.bot.config.delete_commands: await ctx.message.delete()
async def _group(self, ctx): """Shows corp and alliance information. Do '!group name'""" global alliance_name, most_active_system, corp_description, most_active_system, corp_description, most_active_system if len(ctx.message.content.split()) == 1: dest = ctx.author if ctx.bot.config.dm_only else ctx return await dest.send('**ERROR:** Use **!help group** for more info.') group_name = ctx.message.content.split(' ', 1)[1] self.logger.info('GroupLookup - {} requested group info for the group {}'.format(str(ctx.message.author), group_name)) corp_data = None alliance_data = None corp_id = None alliance_id = None corp = 'corporation' corp_ids = await ctx.bot.esi_data.esi_search(group_name, corp) if corp_ids is not None and 'corporation' in corp_ids: if len(corp_ids['corporation']) > 1: for corporation_id in corp_ids['corporation']: group_data = await ctx.bot.esi_data.corporation_info(corporation_id) if group_data['name'].lower().strip() == group_name.lower().strip(): corp_id = corporation_id corp_data = await ctx.bot.esi_data.corporation_info(corp_id) break elif len(corp_ids['corporation']) == 1: corp_id = corp_ids['corporation'][0] corp_data = await ctx.bot.esi_data.corporation_info(corp_id) alliance = 'alliance' alliance_ids = await ctx.bot.esi_data.esi_search(group_name, alliance) if alliance_ids is not None and 'alliance' in alliance_ids: if len(alliance_ids['alliance']) > 1: for ally_id in alliance_ids['alliance']: group_data = await ctx.bot.esi_data.alliance_info(ally_id) if group_data['name'].lower().strip() == group_name.lower().strip(): alliance_id = ally_id alliance_data = await ctx.bot.esi_data.alliance_info(alliance_id) break elif len(alliance_ids['alliance']) == 1: alliance_id = alliance_ids['alliance'][0] alliance_data = await ctx.bot.esi_data.alliance_info(alliance_id) # Check if a corp and alliance were both found if corp_data is not None and alliance_data is not None: if corp_data['name'].lower().strip() == group_name.lower().strip(): alliance_data = None elif alliance_data['name'].lower().strip() == group_name.lower().strip(): corp_data = None else: dest = ctx.author if ctx.bot.config.dm_only else ctx self.logger.info('GroupLookup ERROR - {} could not be found'.format(group_name)) return await dest.send('**ERROR:** Multiple Groups Found With Names Similiar To {}'.format(group_name)) if corp_data is not None: group = 'corporation' group_id = corp_id group_data = corp_data zkill_stats = await self.zkill_stats(group_id, 'corporationID') raw_corp_description = group_data['description'] new_lines = re.sub('<br\s*?>', '\n', raw_corp_description) tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)') corp_description = tag_re.sub('', new_lines) try: alliance_id = group_data['alliance_id'] alliance_info = await ctx.bot.esi_data.alliance_info(alliance_id) alliance_name = alliance_info['name'] alliance = True except Exception: alliance = False zkill_link = 'https://zkillboard.com/corporation/{}/'.format(group_id) eve_who = 'https://evewho.com/corp/{}'.format(urllib.parse.quote(group_name)) dotlan = 'http://evemaps.dotlan.net/corporation/{}'.format(urllib.parse.quote(group_name)) logo = 'https://imageserver.eveonline.com/Corporation/{}_64.png'.format(group_id) elif alliance_data is not None: group = 'alliance' group_id = alliance_id group_data = alliance_data zkill_stats = await self.zkill_stats(group_id, 'allianceID') zkill_link = 'https://zkillboard.com/alliance/{}/'.format(group_id) eve_who = 'https://evewho.com/alli/{}'.format(urllib.parse.quote(group_name)) dotlan = 'http://evemaps.dotlan.net/alliance/{}'.format(urllib.parse.quote(group_name)) logo = 'https://imageserver.eveonline.com/Alliance/{}_64.png'.format(group_id) else: dest = ctx.author if ctx.bot.config.dm_only else ctx self.logger.info('GroupLookup ERROR - {} could not be found'.format(group_name)) return await dest.send('**ERROR:** No Group Found With The Name {}'.format(group_name)) if zkill_stats: total_kills = '{0:}'.format(zkill_stats['allTimeSum']) danger_ratio = zkill_stats['dangerRatio'] gang_ratio = zkill_stats['gangRatio'] solo_kills = '{0:}'.format(zkill_stats['soloKills']) if zkill_stats['hasSupers']: try: super_count = len(zkill_stats['supers']['supercarriers']['data']) except Exception: super_count = 'N/A' try: titan_count = len(zkill_stats['supers']['titans']['data']) except Exception: titan_count = 'N/A' else: super_count = 'N/A' titan_count = 'N/A' for top in zkill_stats['topLists']: try: if top['type'] == 'solarSystem': most_active_system = top['values'][0]['solarSystemName'] except Exception: most_active_system = 'N/A' else: total_kills = 'N/A' danger_ratio = 'N/A' gang_ratio = 'N/A' solo_kills = 'N/A' super_count = 'N/A' titan_count = 'N/A' most_active_system = 'N/A' embed = make_embed(guild=ctx.guild, title=group_name, content='[ZKill]({}) / [EveWho]({}) / [Dotlan]({})'.format(zkill_link, eve_who, dotlan)) embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via Ultron Bot") embed.set_thumbnail( url=logo) if group == 'corporation' and alliance: embed.add_field(name="General Info", value='Name:\nTicker:\nMember Count:\nAlliance:', inline=True) embed.add_field(name="-", value='{}\n{}\n{}\n{}'.format(group_data['name'], group_data['ticker'], group_data['member_count'], alliance_name), inline=True) embed.add_field(name="PVP Info", value='Threat Rating:\nGang Ratio:\nSolo Kills:\nTotal Kills:' '\nKnown Super Count:\nKnown Titan Count:\nMost Active System:', inline=True) embed.add_field(name="-", value='{}%\n{}%\n{}\n{}\n{}\n{}\n{}'.format(danger_ratio, gang_ratio, solo_kills, total_kills, super_count, titan_count, most_active_system), inline=True) if len(corp_description) > 1: embed.add_field(name="Description", value=corp_description[:1023]) elif group == 'corporation' and not alliance: embed.add_field(name="General Info", value='Name:\nTicker:\nMember Count:', inline=True) embed.add_field(name="-", value='{}\n{}\n{}'.format(group_data['name'], group_data['ticker'], group_data['member_count']), inline=True) embed.add_field(name="PVP Info", value='Threat Rating:\nGang Ratio:\nSolo Kills:\nTotal Kills:' '\nKnown Super Count:\nKnown Titan Count:\nMost Active System:', inline=True) embed.add_field(name="-", value='{}%\n{}%\n{}\n{}\n{}\n{}\n{}'.format(danger_ratio, gang_ratio, solo_kills, total_kills, super_count, titan_count, most_active_system), inline=True) if len(corp_description) > 1: embed.add_field(name="Description", value=corp_description[:1023]) elif group == 'alliance': embed.add_field(name="General Info", value='Name:\nTicker:', inline=True) embed.add_field(name="-", value='{}\n{}'.format(group_data['name'], group_data['ticker']), inline=True) embed.add_field(name="PVP Info", value='Threat Rating:\nGang Ratio:\nSolo Kills:\nTotal Kills:\nKnown ' 'Super Count:\nKnown Titan Count:\nMost Active System:', inline=True) embed.add_field(name="-", value='{}%\n{}%\n{}\n{}\n{}\n{}\n{}'.format(danger_ratio, gang_ratio, solo_kills, total_kills, super_count, titan_count, most_active_system), inline=True) dest = ctx.author if ctx.bot.config.dm_only else ctx await dest.send(embed=embed) if ctx.bot.config.delete_commands: await ctx.message.delete()
async def report_current(self, system_data, fight_type, defender_name, defender_score, attacker_score, ctx=None, channel_id=None, winning=None): defender_score = '{}%'.format(defender_score * 100) attacker_score = '{}%'.format(attacker_score * 100) constellation_data = await self.bot.esi_data.constellation_info( system_data['constellation_id']) constellation_name = constellation_data['name'] region_id = constellation_data['region_id'] region_data = await self.bot.esi_data.region_info(region_id) region_name = region_data['name'] zkill_link = "https://zkillboard.com/system/{}".format( system_data['system_id']) dotlan_link = "http://evemaps.dotlan.net/system/{}".format( system_data['name'].replace(' ', '_')) constellation_dotlan = "http://evemaps.dotlan.net/map/{}/{}".format( region_name.replace(' ', '_'), constellation_name.replace(' ', '_')) title = 'Active Sov Battle Reported In: {}'.format(system_data['name']) content = '[ZKill]({}) / [{}]({}) / [Constellation: {}]({})\nBot is tracking this battle.'. \ format(zkill_link, system_data['name'], dotlan_link, constellation_name, constellation_dotlan) embed_type = 'info' if winning == 1: defender_score = '{} :arrow_up:'.format(defender_score) attacker_score = '{}'.format(attacker_score) title = 'Update For {}'.format(system_data['name']) content = '[ZKill]({}) / [{}]({}) / [Constellation: {}]({})\nThe Defender is making progress.'. \ format(zkill_link, system_data['name'], dotlan_link, constellation_name, constellation_dotlan) embed_type = 'success' elif winning == 2: defender_score = '{}'.format(defender_score) attacker_score = '{} :arrow_up:'.format(attacker_score) title = 'Update For {}'.format(system_data['name']) content = '[ZKill]({}) / [{}]({}) / [Constellation: {}]({})\nThe Attacker is making progress.'. \ format(zkill_link, system_data['name'], dotlan_link, constellation_name, constellation_dotlan) embed_type = 'error' embed = make_embed(msg_type=embed_type, title=title, title_url=dotlan_link, content=content) embed.set_footer(icon_url=self.bot.user.avatar_url, text="Provided Via ultron Bot") embed.add_field(name="Active Sov Battle", value='Defender:\nFight Type:' '\nDefender Score:\nAttacker Score:') embed.add_field(name="-", value='{}\n{}\n{}\n{}'.format(defender_name, fight_type, defender_score, attacker_score), inline=True) try: if channel_id is None: await ctx.channel.send(embed=embed) else: channel = self.bot.get_channel(channel_id) await channel.send(embed=embed) except: return None