async def timer(self, ctx): """ Gets the Next Timer! :param ctx: :return: """ next_timer = Timer.objects.filter( corp_timer=False, eve_time__gte=datetime.datetime.utcnow().replace( tzinfo=timezone.utc)).first() time_until = pendulum.now(tz="UTC").diff_for_humans( next_timer.eve_time, absolute=True) embed = Embed(title="Next Timer") embed.description = next_timer.details if next_timer.objective == "Friendly": embed.colour = Color.blue() elif next_timer.objective == "Hostile": embed.colour = Color.red() else: embed.colour = Color.white() try: embed.set_footer(text="Added By {0}".format( next_timer.eve_character.character_name)) except Exception as e: logger.error(e) pass embed.add_field(name="Structure:", value=next_timer.structure) embed.add_field(name="Location:", value="{0} - {1}".format(next_timer.system, next_timer.planet_moon)) embed.add_field(name="Eve Time:", value=next_timer.eve_time.strftime("%Y-%m-%d %H:%M"), inline=False) return await ctx.send(embed=embed)
async def form(message, params, **options): values = " ".join(params).strip() values = values.split(FORM_SEPARATOR) if len(values) > 10: return log((["b", "w"], "too many arguments")) title = values[0] form_options = [option for option in values[1:] if option] if not title: return log((["b", "w"], "not enough arguments")) embed_message = Embed() embed_message.description = f"📊 **{title}**\n\n" embed_message.colour = discord.Colour.from_rgb(77, 119, 215) embed_message.set_footer(text=f"by {message.author}") if not form_options: message_form = await message.channel.send(embed=embed_message) for emoji in ["✅", "❌"]: await message_form.add_reaction(emoji) return ziped_options = list(zip(FORM_EMOJIS, form_options)) for number, desc in ziped_options: embed_message.description += f"{number} {desc}\n" message_form = await message.channel.send(embed=embed_message) for number in range(len(form_options)): await message_form.add_reaction(FORM_EMOJIS[number])
async def list_role(self, ctx): """ list roles from a channel. """ if ctx.message.author.id not in app_settings.get_admins( ): # https://media1.tenor.com/images/1796f0fa0b4b07e51687fad26a2ce735/tenor.gif return await ctx.message.add_reaction(chr(0x1F44E)) await ctx.message.channel.trigger_typing() input_string = ctx.message.content[11:] channel_name = get(ctx.guild.channels, name=input_string) roles = {} if channel_name: for role in channel_name.overwrites: roles[role.name] = {} overides = channel_name.overwrites_for(role) for _name, _value in overides: if _value is not None: roles[role.name][_name] = _value pass embed = Embed(title=f"'{channel_name.name}' Channel Roles") embed.colour = Color.blue() message = "" for key, role in roles.items(): _msg = f"\n`{key}` Role:\n" for r, v in role.items(): _msg += f"{r}: {v}\n" message += _msg embed.description = message return await ctx.send(embed=embed)
async def kinsy(self, ctx): """ Returns the Kinsy Video """ await ctx.trigger_typing() embed = Embed(title="JUST JUMP IN!!") embed.set_thumbnail( url= "https://images.evetech.net/characters/1630472146/portrait?size=128" ) embed.colour = Color.blue() embed.description = "Just Jump In And WARP TO ME!!" url = get_site_url() embed.add_field( name="The Link", value= "https://cdn.discordapp.com/attachments/685827175626440735/949349523774398565/My_Movie.mp4" .format(url, url), inline=False) return await ctx.send(embed=embed)
async def auth(self, ctx): """ Returns a link to the AllianceAuth Install Used by many other Bots and is a common command that users will attempt to run. """ await ctx.trigger_typing() embed = Embed(title="AllianceAuth") embed.set_thumbnail( url= "https://assets.gitlab-static.net/uploads/-/system/project/avatar/6840712/Alliance_auth.png?width=128" ) embed.colour = Color.blue() embed.description = "All Authentication functions for this Discord server are handled through our Alliance Auth install" regex = r"^(.+)\/d.+" matches = re.finditer(regex, settings.DISCORD_CALLBACK_URL, re.MULTILINE) for m in matches: url = m.groups() embed.add_field(name="Auth Link", value="[{}]({})".format(url[0], url[0]), inline=False) return await ctx.send(embed=embed)
async def list_role(self, ctx): """ list roles from a channel. """ await ctx.message.channel.trigger_typing() input_string = ctx.message.content[11:] channel_name = get(ctx.guild.channels, name=input_string) roles = {} if channel_name: for role in channel_name.overwrites: roles[role.name] = {} overides = channel_name.overwrites_for(role) for _name, _value in overides: if _value is not None: roles[role.name][_name] = _value pass embed = Embed(title=f"'{channel_name.name}' Channel Roles") embed.colour = Color.blue() message = "" for key, role in roles.items(): _msg = f"\n`{key}` Role:\n" for r, v in role.items(): _msg += f"{r}: {v}\n" message += _msg embed.description = message return await ctx.send(embed=embed)
async def sg_audit(self, ctx): """ Smart Group Audit of a user Input: [group name]|[main_character] """ if ctx.message.channel.id not in settings.ADMIN_DISCORD_BOT_CHANNELS: return await ctx.message.add_reaction(chr(0x1F44E)) input_name = ctx.message.content[10:].split("|") embed = Embed( title="{group} Audit: {character_name}".format( character_name=input_name[1], group=input_name[0]) ) try: char = EveCharacter.objects.get(character_name=input_name[1]) group = Group.objects.get(name=input_name[0]) try: main = char.character_ownership.user checks = group.smartgroup.run_check_on_user(main) embed.colour = Color.blue() for c in checks: msg = c.get("message") if not msg: msg = "Pass: {}".format(c.get("check")) embed.add_field( name="{} (Pass: {})".format(c.get("filter").filter_object.description, c.get("check")), value=msg, inline=False ) return await ctx.send(embed=embed) except ObjectDoesNotExist as e: return await ctx.send("Member or Group issues") except EveCharacter.DoesNotExist: embed.colour = Color.red() embed.description = ( "Character **{character_name}** does not exist in our Auth system" ).format(character_name=input_name[1]) return await ctx.send(embed=embed)
async def lookup(self, ctx): """ Gets Auth data about a character Input: a Eve Character Name """ input_name = ctx.message.content[8:] char = EveCharacter.objects.get(character_name=input_name) main = char.character_ownership.user.profile.main_character state = char.character_ownership.user.profile.state.name groups = char.character_ownership.user.groups.all().values_list( 'name', flat=True) try: discord = "<@{}>".format(char.character_ownership.user.discord.uid) except: discord = "unknown" alts = char.character_ownership.user.character_ownerships.all( ).select_related('character', 'zkill').values_list( 'character__character_name', 'character__corporation_ticker', 'character__character_id', 'character__corporation_id', 'character__zkill__zk_12m', 'character__zkill__zk_3m') zk12 = 0 zk3 = 0 for alt in alts: if alt[4]: zk12 += alt[4] zk3 += alt[5] embed = Embed(title="Character Lookup") embed.colour = Color.blue() embed.description = "**{0}** is linked to **{1} [{2}]** (State: {3})".format( char, main, main.corporation_ticker, state) alt_list = [ "[{}](https://evewho.com/character/{}) *[ [{}](https://evewho.com/corporation/{}) ]*" .format(a[0], a[2], a[1], a[3]) for a in alts ] for idx, names in enumerate( [alt_list[i:i + 6] for i in range(0, len(alt_list), 6)]): if idx < 21: embed.add_field(name="Linked Characters {}".format(idx + 1), value=", ".join(names), inline=False) else: embed.add_field( name= "Linked Characters {} **( Discord Limited There are More )**" .format(idx), value=", ".join(names), inline=False) break embed.add_field(name="Groups", value=", ".join(groups), inline=False) embed.add_field(name="12m Kills", value=zk12, inline=True) embed.add_field(name="3m Kills", value=zk3, inline=True) embed.add_field(name="Discord Link", value=discord, inline=False) return await ctx.send(embed=embed)
async def changelog(self, ctx: Context): em = Embed(title="Administration: Bot Changelog", description="No description set.") file = None em.colour = 0x00ff00 if ctx.message.attachments: for i in ctx.message.attachments: if i.filename == f"changelog.txt": file = i break if not file: em.description = f"Enter `{self.bot.command_prefix}help updates` to view the changelog.\n" \ f"**Attach a file named \"changelog.txt\".**" em.colour = 0xff0000 elif file: await file.save(f"{self.bot.cwd}/changelog.txt") em.description = f"Changelog file set." em.colour = 0x00ff00 await ctx.send(embed=em)
async def send_board(self, channel: TextChannel) -> Message: """Prepare game Embed and update message""" session = self.session(channel) em = Embed( title= f"{session.p1.chip}{session.p1.name} {Emoji.vs} {session.p2.name}{session.p2.chip}", description=f"\n" f"{Emoji.one}{Emoji.two}{Emoji.three}{Emoji.four}{Emoji.five}{Emoji.six}{Emoji.seven}\n" f"{session.draw_board}") if session.state == State.init: em.description = f"New game! Turn: 1\n" \ f"{em.description}\n" \ f"\n" \ f"{session.current_player.mention}'s turn: {session.current_player.chip}" em.colour = session.colour return await self.init_game_message(channel, session, em) elif session.state == State.active: em.description = f"Turn: {(session.turn + 2) // 2}\n" \ f"{em.description}\n" \ f"\n" \ f"{session.current_player.mention}'s turn: {session.current_player.chip}" em.colour = session.colour elif session.state == State.draw: self.sessions.pop(channel.id) em.description = f"Game ended in a Draw.\n" \ f"{em.description}" em.colour = Colour.dark_grey() await session.msg.clear_reactions() elif session.state == State.forfeit: self.sessions.pop(channel.id) em.description = f"Game Over. {session.current_player.name} Forfeits.\n" \ f"{em.description}" em.colour = Colour.dark_grey() await session.msg.clear_reactions() elif session.state == State.timeout: self.sessions.pop(channel.id) em.description = f"Time Out. {session.current_player.name} Forfeits.\n" \ f"{em.description}" em.colour = Colour.dark_grey() await session.msg.clear_reactions() elif session.state == State.won: self.sessions.pop(channel.id) em.description = f"Game Over!\n{session.current_player.name} wins! {Emoji.tada}\n" \ f"{em.description}" em.colour = 0xFDFF00 await session.msg.clear_reactions() # TODO: check I can edit the message (retrievable), if not, init message return await session.msg.edit(embed=em)
async def jumpbridges(self, ctx): """ List all known Jumpbridges's """ embed = Embed(title=f"Known Jump Bridges") embed.colour = Color.blue() embed.description = "These do not auto populate. Please advise admins of ommisions/errors!\n\n" jbs = MapJumpBridge.objects.all().select_related( 'from_solar_system', 'to_solar_system', 'owner') for jb in jbs: embed.description += f"`{jb.from_solar_system.name}` > `{jb.to_solar_system}` [{jb.owner.name}]\n" return await ctx.send(embed=embed)
async def get_help_embed(command, msg_content, author): raw_args = await utils.get_args(command, msg_content) args = raw_args['args'] num_args = len(args) embed = Embed() embed.colour = author.colour if num_args not in (1, 2) and not raw_args['help']: usage = HelpManager.get_help(command._aliases[0])['usage'].replace('{prefix}', conf['prefix']) embed.add_field(name="Usage:", value=usage, inline=False) return embed elif raw_args['help']: name = msg_content.split()[0][1:] lang = 'en' else: name = args[0] lang = args[1] if num_args == 2 else 'en' entry = HelpManager.get_help(name, lang=lang) if not entry: if name in CommandRegistrar.instance().command_table.keys(): embed.title = f":octagonal_sign: There is no '{lang}' translation for '{name}'. :octagonal_sign:" else: embed.title = ":octagonal_sign: That doesnt seem to be a valid command. :octagonal_sign:" print("C**t...") return embed usage = entry['usage'].replace('{prefix}', conf['prefix']) description = entry['description'] command_table = CommandRegistrar.instance().commands command = command_table[name] embed.title = f"**{name}**" embed.description = f"aliases: {', '.join(command.aliases)}" embed.set_thumbnail(url='https://i.imgur.com/MXkFjJj.png') embed.add_field(name="Usage:", value=usage, inline=False) embed.add_field(name="Description:", value=description, inline=False) embed.set_thumbnail(url='https://i.imgur.com/MXkFjJj.png') embed.set_footer(text=f"Requested by {author.name}#{author.discriminator}", icon_url=author.avatar_url) return embed
def ping_embed(package, message, paginate): 'Formats and generates the embed for the ping' embed = Embed() currentmsg = paginate.pages_yielded totalmsgs = currentmsg + paginate.pages_left if currentmsg == 1: embed.title = package['sender'] embed.set_author(name=package['description']) embed.description = message embed.set_thumbnail(url=package['logo_url']) if totalmsgs > 1: embed.set_footer( text='Message {}/{}'.format(currentmsg, totalmsgs)) embed.timestamp = datetime.utcnow() embed.colour = package['embed_colour'] return embed
async def route(self, ctx): """ Find route in eve with JB's """ input_names = ctx.message.content[7:].split(":") start = MapSystem.objects.get(name=input_names[0]) end = MapSystem.objects.get(name=input_names[1]) message = routes.route(start.system_id, end.system_id) dotlan_url = "https://evemaps.dotlan.net/route/{}".format( message.get("dotlan")) embed = Embed(title=f"{start.name} to {end.name}") embed.colour = Color.blue() embed.description = "Shortest Route is: {} Jumps\n\n{}".format( message.get("length"), message.get("path_message")) embed.add_field(name="Dotlan", value=f"[Route Link]({dotlan_url})") return await ctx.send(embed=embed)
async def about(self, ctx): """ All about the bot """ await ctx.trigger_typing() embed = Embed(title="AuthBot: The Authening") embed.set_thumbnail( url= "https://cdn.discordapp.com/icons/713666554629455892/a4c362c2037b239f2c3ef4aeeda9375a.png?size=128" ) embed.colour = Color.blue() embed.description = "This is a multi-de-functional discord bot tailored specifically for miller cunts." regex = r"^(.+)\/d.+" matches = re.finditer(regex, settings.DISCORD_CALLBACK_URL, re.MULTILINE) for m in matches: url = m.groups() embed.set_footer( text="Lovingly developed for V0LTA.™ by Miller Thwots") embed.add_field(name="Number of Servers:", value=len(self.bot.guilds), inline=True) embed.add_field(name="Unwilling Monitorees:", value=len(self.bot.users), inline=True) embed.add_field(name="Auth Link", value="[{}]({})".format(url[0], url[0]), inline=False) embed.add_field(name="Version", value="{}@{}".format(__version__, __branch__), inline=False) # embed.add_field( # name="Creator", value="<@318309023478972417>", inline=False # ) return await ctx.send(embed=embed)
async def about(self, ctx): """ All about the bot """ await ctx.trigger_typing() embed = Embed(title="AuthBot: The Authening") embed.set_thumbnail( url= "https://cdn.discordapp.com/icons/516758158748811264/ae3991584b0f800b181c936cfc707880.webp?size=128" ) embed.colour = Color.blue() embed.description = "This is a multi-de-functional discord bot tailored specifically for Alliance Auth Shenanigans." regex = r"^(.+)\/d.+" matches = re.finditer(regex, settings.DISCORD_CALLBACK_URL, re.MULTILINE) for m in matches: url = m.groups() embed.set_footer( text="Lovingly developed for Init.™ by AaronRin and ArielKable") embed.add_field(name="Number of Servers:", value=len(self.bot.guilds), inline=True) embed.add_field(name="Unwilling Monitorees:", value=len(self.bot.users), inline=True) embed.add_field(name="Auth Link", value="[{}]({})".format(url[0], url[0]), inline=False) embed.add_field(name="Version", value="{}@{}".format(__version__, __branch__), inline=False) # embed.add_field( # name="Creator", value="<@318309023478972417>", inline=False # ) return await ctx.send(embed=embed)
async def altcorp(self, ctx): """ Gets Auth data about an altcorp Input: a Eve Character Name """ if ctx.message.channel.id not in settings.ADMIN_DISCORD_BOT_CHANNELS: return await ctx.message.add_reaction(chr(0x1F44E)) input_name = ctx.message.content[9:] chars = EveCharacter.objects.filter(corporation_name=input_name) own_ids = [settings.DISCORD_BOT_MEMBER_ALLIANCES] alts_in_corp = [] for c in chars: if c.alliance_id not in own_ids: alts_in_corp.append(c) mains = {} for a in alts_in_corp: try: main = a.character_ownership.user.profile.main_character if main.character_id not in mains: mains[main.character_id] = [main, 0] mains[main.character_id][1] += 1 alt_corp_id = a.corporation_id except Exception as e: logger.error(e) pass output = [] base_string = "[{}]({}) [ [{}]({}) ] has {} alt{}" for k, m in mains.items(): output.append( base_string.format(m[0], evewho.character_url(m[0].character_id), m[0].corporation_ticker, evewho.corporation_url(m[0].corporation_id), m[1], "s" if m[1] > 1 else "")) for strings in [output[i:i + 10] for i in range(0, len(output), 10)]: embed = Embed(title=input_name) embed.colour = Color.blue() embed.description = "\n".join(strings) await ctx.send(embed=embed)
async def auth_slash(self, ctx): """ Returns a link to the AllianceAuth Install Used by many other Bots and is a common command that users will attempt to run. """ embed = Embed(title="AllianceAuth") embed.set_thumbnail( url= "https://assets.gitlab-static.net/uploads/-/system/project/avatar/6840712/Alliance_auth.png?width=128" ) embed.colour = Color.blue() embed.description = "All Authentication functions for this Discord server are handled through our Alliance Auth install" url = get_site_url() embed.add_field(name="Auth Link", value="[{}]({})".format(url, url), inline=False) return await ctx.respond(embed=embed)
async def lowadm( self, ctx, adm: Option(float, description="Optional ADM Level to flag under.", required=False)): """ Systems with low ADMs. """ if not adm: adm = app_settings.get_low_adm() # @commands.command(pass_context=True) # @message_in_channels(settings.SOV_DISCORD_BOT_CHANNELS) if ctx.channel.id not in settings.SOV_DISCORD_BOT_CHANNELS: return await ctx.respond( f"You do not have permission to use this command here.", ephemeral=True) await ctx.defer() own_ids = settings.DISCORD_BOT_SOV_STRUCTURE_OWNER_IDS include_regions = settings.DISCORD_BOT_ADM_REGIONS include_systems = settings.DISCORD_BOT_ADM_SYSTEMS include_constel = settings.DISCORD_BOT_ADM_CONSTELLATIONS sov_structures = providers.esi.client.Sovereignty.get_sovereignty_structures( ).result() names = {} for s in sov_structures: if s.get('alliance_id') in own_ids: if s.get('vulnerability_occupancy_level'): if s.get('vulnerability_occupancy_level') < adm: names[s.get('solar_system_id')] = { "system_name": s.get('solar_system_id'), "adm": s.get('vulnerability_occupancy_level') } if len(names) == 0: await ctx.respond(f"All above {adm} :ok_hand:") return True systems = [k for k, v in names.items()] constelations = {} for n in systems: system = providers.esi.client.Universe.get_universe_systems_system_id( system_id=n).result() names[n]["system_name"] = system.get("name") names[n]["system_id"] = system.get("system_id") names[n]["constellation_id"] = system.get("constellation_id") if system.get("constellation_id") not in constelations: constelations[system.get("constellation_id")] = {} for c, v in constelations.items(): const = providers.esi.client.Universe.get_universe_constellations_constellation_id( constellation_id=c).result() region = providers.esi.client.Universe.get_universe_regions_region_id( region_id=const.get("region_id")).result() v["region_id"] = const.get("region_id") v["region_name"] = region.get("name") v["constellation_name"] = const.get("name") out_array = {} for k, v in names.items(): out_array[k] = {**v, **constelations[v["constellation_id"]]} output = {} base_str = "**{}** ADM:{}" urls = {} for k, h in sorted(out_array.items(), key=lambda e: e[1]['adm']): show = False if h['region_id'] in include_regions: show = True elif h['constellation_id'] in include_constel: show = True elif h['system_id'] in include_systems: show = True if show: if h['region_name'] not in output: output[h['region_name']] = [] output[h['region_name']].append( base_str.format(h['system_name'], h['adm'])) if h['region_name'].replace(" ", "_") not in urls: urls[h['region_name'].replace(" ", "_")] = [] urls[h['region_name'].replace(" ", "_")].append( h['system_name'].replace(" ", "_")) url = "https://evemaps.dotlan.net/map/{}/{}#adm" if len(output) > 0: embed = Embed(title="Low ADMs!") embed.set_thumbnail( url= "https://avatars3.githubusercontent.com/u/39349660?s=200&v=4") embed.colour = Color.red() embed.description = f"Showing systems with ADMs below {adm}. Due to an ESI bug this data might only update once a day at around 2200-2300 Eve Time. **YMMY**\n[For more info please see this issue](https://github.com/esi/esi-issues/issues/1092)" await ctx.respond(embed=embed) for k, v in output.items(): n = 25 chunks = [ list(v[i * n:(i + 1) * n]) for i in range((len(v) + n - 1) // n) ] for chunk in chunks: await ctx.send("__{}__\n{}".format(k, "\n".join(chunk))) _urls = [] for r, s in urls.items(): _urls.append(url.format(r, ",".join(s))) await ctx.send("\n\n".join(_urls)) else: await ctx.respond(f"No Systems with ADM below {adm}!") return True
async def time(self, ctx): """ Returns EVE Time """ fmt_utc = "%H:%M:%S (UTC)\n%A %d. %b %Y" fmt = "%H:%M:%S (UTC %z)\n%A %d. %b %Y" url = None await ctx.trigger_typing() embed = Embed(title="Time") embed.colour = Color.green() embed.add_field( name="EVE Time", value=datetime.utcnow().strftime(fmt_utc), inline=False, ) if timezones_active(): from timezones.models import Timezones url = get_site_url() + "/timezones/" configured_timezones = Timezones.objects.filter(is_enabled=True) # get configured timezones from module setting if configured_timezones.count() > 0: for configured_timezone in configured_timezones: embed.add_field( name=configured_timezone.panel_name, value=(datetime.utcnow().astimezone( pytz.timezone(configured_timezone.timezone. timezone_name)).strftime(fmt)), inline=True, ) # get default timezones from module else: from timezones import __version__ as timezones_version from packaging import version if version.parse(timezones_version) >= version.parse("1.3.1"): from timezones.constants import AA_TIMEZONE_DEFAULT_PANELS configured_timezones = AA_TIMEZONE_DEFAULT_PANELS for configured_timezone in configured_timezones: embed.add_field( name=configured_timezone["panel_name"], value=(datetime.utcnow().astimezone( pytz.timezone( configured_timezone["timezone"] ["timezone_name"])).strftime(fmt)), inline=True, ) # add url to the timezones module if url is not None: embed.add_field( name="Timezones Conversion", value=url, inline=False, ) return await ctx.send(embed=embed)
async def send_embed_message( ctx: Optional[Context], *, title: str, description: Optional[str], colour=Config.EMBED_COLOUR, icon_url=IconUrls.POMBOMB, fields: list = None, footer: str = None, image: str = None, thumbnail: str = None, private_message: bool = False, _func: Callable = None, ) -> Message: """Send an embedded message using the context. @param ctx Either the context with which to send the response, or None when a coroutine is specified via _func. @param colour Colour to line the left side of the embed. @param private_messaage Whether or not to send this emabed as a DM to the user; does not apply when ctx is None. @param _func Coroutine describing how to send the embed. All other parameters: ┌───────────────────────────────────────┐ │┌─────┐ │ ││icon │ Title ┌──────┐ │ │└─────┘ │thumb-│ │ ├───────────────────────── │nail │ │ │ │ │ │ │ Description └──────┘ │ │ │ │ │ │┌──────────────┐┌──────────────┐ │ ││ ││ │ │ ││ Field ││ Field │ │ ││ (inline) ││ (inline) │ │ ││ ││ │ │ ││ ││ │ │ │└──────────────┘└──────────────┘ │ │ │ │ ┌──────────────────────────────────┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ Image │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └──────────────────────────────────┘ │ │Footer │ └───────────────────────────────────────┘ @return The message object that was sent. """ # In discord.py==1.7.x there is a defect which handles None as a string. # This a workaround and can likely be removed later. description = description or EmptyEmbed message = Embed( description=description, colour=colour, ) if icon_url: message.set_author( name=title, icon_url=icon_url, ) else: message.title=title message.description=description message.colour=colour if fields: for field in fields: name, value, inline = field message.add_field(name=name, value=value, inline=inline) for content, setter, kwarg in ( (image, message.set_image, "url"), (footer, message.set_footer, "text"), (thumbnail, message.set_thumbnail, "url"), ): if content: setter(**{kwarg: content}) if ctx is None: coro = _func else: coro = ctx.author.send if private_message else ctx.send # Allow the TypeError to bubble up when both ctx and _func are None. return await coro(embed=message)
async def lowadm(self, ctx): """ Timers for region/constelation/system/alliance """ if ctx.message.channel.id not in settings.ADM_DISCORD_BOT_CHANNELS: return await ctx.message.add_reaction(chr(0x1F44E)) await ctx.trigger_typing() own_ids = settings.DISCORD_BOT_SOV_STRUCTURE_OWNER_IDS include_regions = settings.DISCORD_BOT_ADM_REGIONS include_systems = settings.DISCORD_BOT_ADM_SYSTEMS include_constel = settings.DISCORD_BOT_ADM_CONSTELLATIONS sov_structures = providers.esi.client.Sovereignty.get_sovereignty_structures( ).result() names = {} alliances = [] for s in sov_structures: if s.get('alliance_id') in own_ids: if s.get('vulnerability_occupancy_level'): if s.get('vulnerability_occupancy_level') < 4.5: names[s.get('solar_system_id')] = { "system_name": s.get('solar_system_id'), "adm": s.get('vulnerability_occupancy_level') } if len(names) == 0: await ctx.send("All above 5! :ok_hand:") return True systems = [k for k, v in names.items()] constelations = {} region_id = {} for n in systems: system = providers.esi.client.Universe.get_universe_systems_system_id( system_id=n).result() names[n]["system_name"] = system.get("name") names[n]["system_id"] = system.get("system_id") names[n]["constellation_id"] = system.get("constellation_id") if system.get("constellation_id") not in constelations: constelations[system.get("constellation_id")] = {} for c, v in constelations.items(): const = providers.esi.client.Universe.get_universe_constellations_constellation_id( constellation_id=c).result() region = providers.esi.client.Universe.get_universe_regions_region_id( region_id=const.get("region_id")).result() v["region_id"] = const.get("region_id") v["region_name"] = region.get("name") v["constellation_name"] = const.get("name") out_array = {} for k, v in names.items(): out_array[k] = {**v, **constelations[v["constellation_id"]]} output = {} base_str = "**{}** ADM:{}" urls = {} for k, h in sorted(out_array.items(), key=lambda e: e[1]['adm']): show = False if h['region_id'] in include_regions: show = True elif h['constellation_id'] in include_constel: show = True elif h['system_id'] in include_systems: show = True if show: if h['region_name'] not in output: output[h['region_name']] = [] output[h['region_name']].append( base_str.format(h['system_name'], h['adm'])) if h['region_name'].replace(" ", "_") not in urls: urls[h['region_name'].replace(" ", "_")] = [] urls[h['region_name'].replace(" ", "_")].append( h['system_name'].replace(" ", "_")) url = "https://evemaps.dotlan.net/map/{}/{}#adm" for k, v in output.items(): await ctx.send("__{}__\n{}\n{}".format( k, "\n".join(v), url.format(k.replace(" ", "_"), ",".join(urls[k.replace(" ", "_")])))) embed = Embed(title="Disclaimer") embed.set_thumbnail( url="https://avatars3.githubusercontent.com/u/39349660?s=200&v=4") embed.colour = Color.red() embed.description = "Due to an ESI bug this data might only update once a day at around 2200-2300 Eve Time. **YMMY**\n[For more info please see this issue](https://github.com/esi/esi-issues/issues/1092)" await ctx.send(embed=embed) return True
async def lookup(self, ctx): """ Gets Auth data about a character Input: a Eve Character Name """ input_name = ctx.message.content[8:] embed = Embed(title="Character Lookup {character_name}".format( character_name=input_name)) try: char = EveCharacter.objects.get(character_name=input_name) try: main = char.character_ownership.user.profile.main_character state = char.character_ownership.user.profile.state.name groups = char.character_ownership.user.groups.all( ).values_list('name', flat=True) try: discord_string = "<@{}>".format( char.character_ownership.user.discord.uid) except Exception as e: logger.error(e) discord_string = "unknown" if aastatistics_active(): alts = char.character_ownership.user.character_ownerships.all( ).select_related('character', 'character_stats').values_list( 'character__character_name', 'character__corporation_ticker', 'character__character_id', 'character__corporation_id', 'character__character_stats__zk_12m', 'character__character_stats__zk_3m') zk12 = 0 zk3 = 0 else: alts = char.character_ownership.user.character_ownerships.all( ).select_related('character').values_list( 'character__character_name', 'character__corporation_ticker', 'character__character_id', 'character__corporation_id') zk12 = "Not Installed" zk3 = "Not Installed" if aastatistics_active(): for alt in alts: if alt[4]: zk12 += alt[4] zk3 += alt[5] embed.colour = Color.blue() embed.description = "**{0}** is linked to **{1} [{2}]** (State: {3})".format( char, main, main.corporation_ticker, state) alt_list = [ "[{}](https://evewho.com/character/{}) *[ [{}](https://evewho.com/corporation/{}) ]*" .format(a[0], a[2], a[1], a[3]) for a in alts ] for idx, names in enumerate( [alt_list[i:i + 6] for i in range(0, len(alt_list), 6)]): if idx < 6: embed.add_field( name="Linked Characters {}".format(idx + 1), value=", ".join(names), inline=False) else: embed.add_field( name= "Linked Characters {} **( Discord Limited There are More )**" .format(idx), value=", ".join(names), inline=False) break if len(groups) > 0: embed.add_field(name="Groups", value=", ".join(groups), inline=False) if aastatistics_active(): embed.add_field(name="12m Kills", value=zk12, inline=True) embed.add_field(name="3m Kills", value=zk3, inline=True) embed.add_field(name="Discord Link", value=discord_string, inline=False) return await ctx.send(embed=embed) except ObjectDoesNotExist: users = char.ownership_records.values('user') users = User.objects.filter(id__in=users) characters = EveCharacter.objects.filter( ownership_records__user__in=users).distinct() embed = Embed(title="Character Lookup") embed.colour = Color.blue() embed.description = "**{0}** is Unlinked searching for any characters linked to known users".format( char, ) user_names = ["{}".format(user.username) for user in users] embed.add_field(name="Old Users", value=", ".join(user_names), inline=False) alt_list = [ "[{}](https://evewho.com/character/{}) *[ [{}](https://evewho.com/corporation/{}) ]*" .format(a.character_name, a.character_id, a.corporation_ticker, a.corporation_id) for a in characters ] for idx, names in enumerate( [alt_list[i:i + 6] for i in range(0, len(alt_list), 6)]): if idx < 6: embed.add_field(name="Found Characters {}".format(idx + 1), value=", ".join(names), inline=False) else: embed.add_field( name= "Found Characters {} **( Discord Limited There are More )**" .format(idx), value=", ".join(names), inline=False) break return await ctx.send(embed=embed) except EveCharacter.DoesNotExist: embed.colour = Color.red() embed.description = ( "Character **{character_name}** does not exist in our Auth system" ).format(character_name=input_name) return await ctx.send(embed=embed)
def build_embed(self): fmt_utc = "%H:%M:%S (UTC)\n%A %d. %b %Y" fmt = "%H:%M:%S (UTC %z)\n%A %d. %b %Y" url = None embed = Embed(title="Time") embed.colour = Color.green() embed.add_field( name="EVE Time", value=datetime.utcnow().strftime(fmt_utc), inline=False, ) if timezones_active(): from timezones.models import Timezones url = get_site_url() + reverse("timezones:index") configured_timezones = ( Timezones.objects.select_related("timezone") .filter(is_enabled=True) .order_by("panel_name") ) # get configured timezones from module setting if configured_timezones.count() > 0: for configured_timezone in configured_timezones: embed.add_field( name=configured_timezone.panel_name, value=( datetime.utcnow() .astimezone( pytz.timezone( configured_timezone.timezone.timezone_name ) ) .strftime(fmt) ), inline=True, ) # get default timezones from module else: from timezones import __version__ as timezones_version from packaging import version if version.parse(timezones_version) >= version.parse("1.3.1"): from timezones.constants import AA_TIMEZONE_DEFAULT_PANELS configured_timezones = AA_TIMEZONE_DEFAULT_PANELS for configured_timezone in configured_timezones: embed.add_field( name=configured_timezone["panel_name"], value=( datetime.utcnow() .astimezone( pytz.timezone( configured_timezone["timezone"]["timezone_name"] ) ) .strftime(fmt) ), inline=True, ) # add url to the timezones module if url is not None: embed.add_field( name="Timezones Conversion", value=url, inline=False, ) return embed