コード例 #1
0
ファイル: admin.py プロジェクト: LePokePug/MWSRam
 async def r_closets(self, ctx: Context):
     em = Embed(title="Administration: Reset Data",
                description="No description set.",
                color=0x00ff00)
     self.bot.user_data["Closets"] = {
         "authorID": {
             "closet_name": "closet_url"
         }
     }
     em.description = "Reset all closets."
     await ctx.send(embed=em)
     print("[] Deleted all closets on owner's request.")
コード例 #2
0
ファイル: admin.py プロジェクト: LePokePug/MWSRam
    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)
コード例 #3
0
ファイル: admin.py プロジェクト: LePokePug/MWSRam
 async def r_avatars(self, ctx: Context):
     em = Embed(title="Administration: Reset Data",
                description="No description set.",
                color=0x00ff00)
     self.bot.user_data["VanityAvatars"] = {
         "guildID": {
             "userID":
             ["avatar_url", "previous", "is_blocked", "quick_delete_on"]
         }
     }
     em.description = "Reset all avatars."
     await ctx.send(embed=em)
     print("[] Deleted all avatars on owner's request.")
コード例 #4
0
ファイル: c4.py プロジェクト: SirThane/BattleMaps
    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)
コード例 #5
0
    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)
コード例 #6
0
ファイル: player.py プロジェクト: SirThane/BattleMaps
    async def queue(self, ctx: Context):

        session = self.get_session(ctx.guild)

        em = Embed(colour=Colour.dark_green(), title="Upcoming requests")

        for index, track in enumerate(session.queue.requests[:10], 1):
            em.add_field(name=f"{index} - Requested by {track.requester}",
                         value=track.information)

        if not em.fields:
            em.description = "There are currently no requests"

        await ctx.send(embed=em)
コード例 #7
0
ファイル: admin_action.py プロジェクト: lexicalunit/spellbot
 async def award_add(
     self,
     count: int,
     role: str,
     message: str,
     **options: Optional[bool],
 ) -> None:
     repeating = bool(options.get("repeating", False))
     remove = bool(options.get("remove", False))
     max_message_len = GuildAward.message.property.columns[0].type.length  # type: ignore
     if len(message) > max_message_len:
         await safe_send_channel(
             self.interaction,
             f"Your message can't be longer than {max_message_len} characters.",
             ephemeral=True,
         )
         return
     if count < 1:
         await safe_send_channel(
             self.interaction,
             "You can't create an award for zero games played.",
             ephemeral=True,
         )
         return
     if await self.services.guilds.has_award_with_count(count):
         await safe_send_channel(
             self.interaction,
             "There's already an award for players who reach that many games.",
             ephemeral=True,
         )
         return
     await self.services.guilds.award_add(
         count,
         role,
         message,
         repeating=repeating,
         remove=remove,
     )
     embed = Embed()
     embed.set_thumbnail(url=self.settings.ICO_URL)
     embed.set_author(name="Award added!")
     every_or_after = "every" if repeating else "after"
     give_or_take = "take" if remove else "give"
     description = (
         f"• _{every_or_after} {count} games_ — {give_or_take} `@{role}`"
         f" — {message}\n\nYou can view all awards with the `/set awards` command."
     )
     embed.description = description
     embed.color = self.settings.EMBED_COLOR
     await safe_send_channel(self.interaction, embed=embed, ephemeral=True)
コード例 #8
0
    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)
コード例 #9
0
ファイル: bot.py プロジェクト: csabakoncz/discord-pybot
async def send_matches(message: discord.message.Message):
    resp = await do_get_todays_matches()
    for m in resp['matches']:
        e = Embed()
        e.title = m['competition']['name']
        e.description = m['competition']['area']['name']
        e.set_image(url=m['competition']['area']['ensignUrl'])
        e.add_field(name='Time', value=m['utcDate'], inline=False)
        e.add_field(name='Status', value=m['status'], inline=False)
        e.add_field(name=m['homeTeam']['name'],
                    value=m['score']['fullTime']['homeTeam'],
                    inline=True)
        e.add_field(name=m['awayTeam']['name'],
                    value=m['score']['fullTime']['awayTeam'],
                    inline=True)

        await message.reply(embed=e)
コード例 #10
0
ファイル: ukparliament.py プロジェクト: Hattyot/TLDR-Bot
 async def on_royal_assent_update(self, feed: Feed, update: FeedUpdate):
     channel = self._guild.get_channel(
         int(self.config.get_channel_id("royal_assent"))
     )
     if channel is None:
         return
     next_line = "\n"
     embed = Embed(
         colour=discord.Colour.from_rgb(134, 72, 186), timestamp=datetime.now()
     )
     embed.title = f"**Royal Assent Given:** {update.get_title()}"
     embed.description = (
         f"**Signed At:** {update.get_update_date().strftime('%H:%M:%S on %Y:%m:%d')}{next_line}"
         f"**Summary:** {update.get_description()}"
     )
     self.tracker_status["royalassent"]["confirmed"] = True
     await channel.send(embed=embed)
コード例 #11
0
    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
コード例 #12
0
ファイル: bot.py プロジェクト: Zepten/DiscordSpammerBot
async def rule34(ctx, *, tags: str = '*'):
    url34 = environ.get('URL34')

    def get_random_posts(url):
        respond_for_img = requests.get(url=url, headers=HEADERS)
        bs = BeautifulSoup(respond_for_img.text, 'html.parser')
        return bs.posts

    def get_any_random_post_url(url):
        resp = requests.get(url=url, headers=HEADERS)
        bs = BeautifulSoup(resp.text, 'html.parser')
        post_id = bs.title.string.split()[-1]
        post_url = url34+'page=dapi&s=post&q=index&id='+post_id
        return post_url

    if tags == '*':
        post_url = get_any_random_post_url(url34+'page=post&s=random')
        post = get_random_posts(post_url).post
        image_url = post['file_url'] # Image URL
        post_id = post['id'] # Post ID
    else:
        posts_count = get_random_posts(url34+'page=dapi&s=post&q=index&limit=1&tags='+tags)['count'] # Posts count
        try:
            post_pid = random.randint(0, int(posts_count) - 1) # Post PID
        except:
            await ctx.send(':sob: Не могу найти такой пост...')
            return
        post = get_random_posts(url34+'page=dapi&s=post&q=index&limit=1&pid='+str(post_pid)+'&tags='+tags).post # Post object
        image_url = post['file_url'] # Image URL
        post_id = post['id'] # Post ID

    print(f'Sending post ID{post_id}')
    emb = Embed()
    if tags != '*':
        emb.title='Rule34: '+tags
        emb.description = f'Количество постов с этим тэгом: **{posts_count}**\n'
    else:
        emb.title='Rule34: случайный пост'
    emb.set_author(name=f'ID: {post_id}', url=f'{url34}page=post&s=view&id={post_id}')
    emb.set_image(url=image_url)
    emb.set_footer(text='Тэги: '+post['tags'])

    await ctx.message.delete()
    await ctx.send(embed=emb)
コード例 #13
0
    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
コード例 #14
0
    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)
コード例 #15
0
    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)
コード例 #16
0
    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)
コード例 #17
0
    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)
コード例 #18
0
ファイル: ukparliament.py プロジェクト: Hattyot/TLDR-Bot
    async def on_feed_update(self, feed: Feed, update: FeedUpdate):
        channel = self._guild.get_channel(int(self.config.get_channel_id("feed")))
        if channel is None:
            return
        embed = Embed(colour=config.EMBED_COLOUR, timestamp=datetime.now())
        next_line = "\n"
        last_update = await self._bills_storage.get_last_update(update.get_bill_id())
        embed.description = (
            f"**Last Stage:**: {last_update['stage']}{next_line}"
            if last_update is not None
            else ""
            f"**Next Stage:** {update.get_stage()}{next_line} **Summary:** {update.get_description()}"
            f"{next_line}**Categories:**{', '.join(update.get_categories())}"
        )
        embed.title = update.get_title()
        if self._guild is not None:
            embed.set_author(name="TLDRBot", icon_url=self._guild.icon_url)

        self.tracker_status["feed"]["confirmed"] = True
        await channel.send(embed=embed)  # type: ignore
コード例 #19
0
ファイル: ukparliament.py プロジェクト: Hattyot/TLDR-Bot
    async def on_lords_division(self, division: LordsDivision, bill: Bill):
        channel = self._guild.get_channel(
            int(self.config.get_channel_id("lords_divisions"))
        )
        if channel is None:
            return
        print(f"Lords Event: {division.get_division_title()}")
        print(f"Lords Event Date: {division.get_division_date()}")
        print("Getting lords division image.")
        division_file = await self.generate_division_image(self.parliament, division)
        print("Got lords division image.")
        embed = Embed(
            color=discord.Colour.from_rgb(166, 42, 22), timestamp=datetime.now()
        )
        did_pass = division.get_aye_count() > division.get_no_count()
        embed.title = f"**{division.get_division_title()}**"
        embed.set_image(url="attachment://divisionimage.png")
        next_line = "\n"
        description = (
            f"**ID:** {division.get_id()}{next_line}**Summary [(Link)](https://votes.parliament.uk/"
            f"Votes/Lords/Division/{division.get_id()}):** {division.get_amendment_motion_notes()[0:250]}...{next_line}"
            f"**Division Result:** {'Passed' if did_pass else 'Not passed'} by a division of "
            f"{division.get_aye_count() if did_pass else division.get_no_count()} "
            f"{'Ayes' if did_pass else 'Noes'} to {division.get_no_count() if did_pass else division.get_aye_count()}"
            f" {'Noes' if did_pass else 'Ayes'}{next_line}**Division Date:** "
            f"{division.get_division_date().strftime('%Y-%m-%d %H:%M:%S')}"
        )

        if bill is not None:
            description += (
                f"{next_line}**Bill Summary [(Link)](https://bills.parliament.uk/bills/"
                f"{bill.get_bill_id()})**: {bill.get_long_title()}**"
            )
        embed.description = description
        self.tracker_status["lordsdivisions"]["confirmed"] = True
        embed.set_image(url="attachment://divisionimage.png")
        print("Sending lords division embed.")
        await channel.send(
            file=division_file,
            embed=embed,
        )
コード例 #20
0
ファイル: dexpy_bot.py プロジェクト: cirigj/DexPy
async def help(ctx, *raw_args):
    message = ctx.message.content
    print(f'\nHELP command triggered, bzzzzrt! Message details:\n{ctx.message.author} @ ({ctx.message.created_at}): {message}\n')

    output = MessageHelper()

    embed = Embed()
    embed.description = "User Docs can be found [here](https://docs.google.com/document/d/1dOJt6_xodsqWOFJPI2AY91mNmnrjLDyy7cRLki7G8qo/edit?usp=sharing)!"

    opt = ['--force-channel','-f']

    args = parse_arguments(raw_args, options=opt)
    if 'err' in args and len(args['err']) > 0:
        for error in args['err']:
            print(f'Error: {error}', file=output)
        await output.send(ctx)
        return
    
    force_channel = get_option(args['opt'], 'force-channel')

    await output.send(ctx if force_channel else ctx.author, '', embed)
コード例 #21
0
async def account(message, params, **options):
    if params:
        code = params[0]
        login_base = ControllerPostgres("pyelectron_service_login")
        login_base.update(
            columns=["user_id"],
            values=[message.author.id],
            condition=f"verify_code = {code.strip()}",
        )
        id_value = login_base.load(selector="user_id",
                                   condition=f"verify_code = {code.strip()}")
        print(id_value)
        embed_message = Embed(
            description="Successfully verified\nThank you for joined to us")
        return await message.channel.send(embed=embed_message)

    embed_message = Embed(title="Create Account")
    embed_message.description = (
        "[👆 click here](http://site) to create account on **pyElectron Service**"
    )
    await message.channel.send(embed=embed_message)
コード例 #22
0
ファイル: embeds.py プロジェクト: Laogeodritt/KazTron
 def _make_embed_skeleton(self, header: bool, desc: bool, footer: bool, image: bool):
     embed = self.template
     e_new = Embed(colour=embed.colour, type=embed.type)
     if header:
         e_new.title = embed.title
         e_new.url = embed.url
         author = embed.author
         if author.name is not EmptyEmbed:
             e_new.set_author(name=author.name, url=author.url, icon_url=author.icon_url)
     if desc:
         e_new.description = embed.description
     if image:
         if embed.image.url is not EmptyEmbed:
             e_new.set_image(url=embed.image.url)
         if embed.thumbnail.url is not EmptyEmbed:
             e_new.set_thumbnail(url=embed.thumbnail.url)
     if footer:
         e_new.timestamp = embed.timestamp
         footer = embed.footer
         e_new.set_footer(text=footer.text, icon_url=footer.icon_url)
     return e_new
コード例 #23
0
    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)
コード例 #24
0
    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)
コード例 #25
0
ファイル: settings.py プロジェクト: cephox/bettermod
 async def prefix(self, ctx: Context, prefix: Optional[str] = ""):
     lang = get_user_language(ctx.author.id)
     if prefix == "":
         embed = Embed(color=Colors.default, timestamp=datetime.now())
         prefixes = await ctx.bot.get_prefix(ctx.message)
         embed.add_field(name=lang.settings_prefix_current_prefix,
                         value=f"`{prefixes[0]}`",
                         inline=False)
         embed.add_field(
             name=lang.settings_prefix_change_prefix,
             value=
             f"`{prefixes[0]}settings prefix <{lang.settings_prefix_new_prefix}>`",
             inline=False)
         await ctx.send(embed=embed)
     else:
         new_prefix = update_prefix(ctx.guild.id, prefix)
         embed = Embed(color=Colors.default, timestamp=datetime.now())
         embed.description = lang.f_settings_prefix_changed_new_prefix(
             f"`{new_prefix}`")
         embed.add_field(name=lang.changed_by, value=ctx.author.mention)
         embed.set_footer(text=lang.member_id + ": " + str(ctx.author.id))
         await log(ctx, embed=embed)
         await ctx.send(embed=embed)
コード例 #26
0
    async def kinsy_slash(self, ctx):
        """
        Returns the Kinsy Video
        """
        embed = Embed(title="Kinsy")
        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.respond(embed=embed)
コード例 #27
0
 async def __updateUserRole(self, guild: Guild, user: User, member: Member,
                            rank: int, channelToUse: GuildChannel,
                            internal: bool):
     if user:
         if member:
             newRoles = RoleUtil.getKfpRolesFromLevel(guild.id, rank)
             if len(newRoles) > 0:
                 for newRole in newRoles:
                     newGuildRole: Role = guild.get_role(newRole.role_id)
                     if newGuildRole:
                         if not newGuildRole in user.roles:
                             # 用戶有新身份組
                             # 先移除所有不符合的身份組
                             oldRoles: KfpRole = RoleUtil.getCurrentRoles(
                                 guild.id,
                                 Util.RoleCategory(newRole.category))
                             if oldRoles:
                                 oldGuildRoles = []
                                 for oldRole in oldRoles:
                                     guildRole = guild.get_role(
                                         oldRole.role_id)
                                     if guildRole and guildRole in user.roles:
                                         oldGuildRoles.append(guildRole)
                                 for oldGuildRole in oldGuildRoles:
                                     await user.remove_roles(oldGuildRole)
                             # 添加新的身份組
                             await user.add_roles(newGuildRole)
                             if internal:
                                 print(
                                     "adding role {} to member {} successed!"
                                     .format(newGuildRole.name, user.name))
                             else:
                                 embed = Embed()
                                 embed.description = '恭喜<@!{}> 成為 {}'.format(
                                     user.id, newGuildRole.name)
                                 await channelToUse.send(embed=embed)
コード例 #28
0
    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)
コード例 #29
0
    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
コード例 #30
0
    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