python类Color()的实例源码

quickembed.py 文件源码 项目:Sitryk-Cogs 作者: Sitryk 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self, bot):
        self.bot = bot
        self.JSON = "data/Sitryk-Cogs/quickembed/settings.json"
        self.data = dataIO.load_json(self.JSON)
        self.colours = { "red" : discord.Color.red,
                         "dark_red" : discord.Color.dark_red,
                         "blue" : discord.Color.blue,
                         "dark_blue" : discord.Color.dark_blue,
                         "teal" : discord.Color.teal,
                         "dark_teal" :discord.Color.dark_teal,
                         "green" : discord.Color.green,
                         "dark_green" : discord.Color.dark_green,
                         "purple" : discord.Color.purple,
                         "dark_purple" :discord.Color.dark_purple,
                         "magenta" : discord.Color.magenta,
                         "dark_magenta" : discord.Color.dark_magenta,
                         "gold" :discord.Color.gold,
                         "dark_gold" : discord.Color.dark_gold,
                         "orange" :discord.Color.orange,
                         "dark_orange" :discord.Color.dark_orange,
                         "random" : returnhex
                         }
misc.py 文件源码 项目:lagbot 作者: mikevb1 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def hex_or_rgb(arg):
    s = arg.split(' ')
    if len(s) == 1:
        color = s[0]
        if len(color) == 6:
            color = f'0x{color}'
        elif len(color) == 7:
            color = color.replace('#', '0x')
        try:
            return discord.Color(int(color, 0))
        except ValueError:
            raise commands.BadArgument('A single argument must be passed as hex (`0x7289DA`, `#7289DA`, `7289DA`)')
    elif len(s) == 3:
        try:
            rgb = [*map(int, s)]
        except ValueError:
            raise commands.BadArgument('Three arguments must be passed as RGB (`114 137 218`, `153 170 181`)')
        if any(c < 0 or c > 255 for c in rgb):
            raise commands.BadArgument('RGB colors must be in the range `[0, 255]`')
        return discord.Color.from_rgb(*rgb)
    raise commands.BadArgument('You must pass 1 (hex) or 3 (RGB) arguments.')
statistics.py 文件源码 项目:aryas 作者: lattkkthxbbye 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def users(self, ctx: commands.Context, count=10):
        """
        Show users with the most messages
        """
        count = count
        # Show at least 1 user and 20 at most
        count = max(1, count)
        count = min(20, count)

        try:
            server = self.orm.Server.get(discord_id=ctx.message.server.id)
        except DoesNotExist as e:
            # If there's no server in the db an exception will be raised
            self.config.logger.error(e)
        else:
            users = await self.orm.query.user_top_list(count, server)
            embed = discord.Embed(color=discord.Color(self.config.constants.embed_color),
                                  timestamp=datetime.datetime.now())
            for user in users:
                # the user might not have a name if s/he hasn't sent a message already
                # so in that case use the id instead
                name = user.name if user.name != '' else user.discord_id
                embed.add_field(name=name, value='Total messages: {}'.format(user.count), inline=False)

            await self.bot.say(content='Top active users:', embed=embed)
general.py 文件源码 项目:Excalibot 作者: endreman0 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def timer_list(self, ctx):
        """Lists all of your currently active timers."""
        with db.Session() as session:
            timers = session.get(Timer, user_id=ctx.author.id).all()
        now = datetime.utcnow()
        e = discord.Embed(color=discord.Color.blurple())
        def format_timer(timer):
            channel = ctx.bot.get_channel(timer.channel_id)
            return 'ID {id}, in {channel}: {message} (in {duration})'.format(
                id=timer.id,
                channel='DMs' if isinstance(channel, discord.DMChannel) else channel.mention,
                message=timer.message or 'no message',
                duration=format.time(timer.end_time - now)
            )
        e.description = '\n'.join(map(format_timer, timers)) if timers else 'No timers set.'
        await ctx.send(embed=e)
mod.py 文件源码 项目:dogbot 作者: slice 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def mods(self, ctx):
        """
        Shows mods in this server.

        A mod is defined as a human in this server with the "Kick Members" permission, or is a Dogbot Moderator.
        """
        is_mod = lambda m: (m.guild_permissions.kick_members or checks.member_is_moderator(m)) and not m.bot
        mods = [m for m in ctx.guild.members if is_mod(m)]

        embed = discord.Embed(title='Moderators in ' + ctx.guild.name, color=discord.Color.blurple(),
                              description=f'There are {len(mods)} mod(s) total in {ctx.guild.name}.')

        for status in discord.Status:
            those_mods = [m for m in mods if m.status is status]
            if not those_mods:
                continue
            embed.add_field(name=str(status).title(), value='\n'.join(str(m) for m in those_mods))

        await ctx.send(embed=embed)
assistance.py 文件源码 项目:Kurisu 作者: ihaveamac 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def staffreq(self, ctx, *, msg_request=""):
        """Request staff, with optional additional text. Helpers, Staff, Verified only."""
        author = ctx.message.author
        if (self.bot.helpers_role not in author.roles) and (self.bot.staff_role not in author.roles) and (self.bot.verified_role not in author.roles) and (self.bot.trusted_role not in author.roles):
            msg = "{0} You cannot used this command at this time. Please ask individual staff members if you need help.".format(author.mention)
            await self.bot.say(msg)
            return
        await self.bot.delete_message(ctx.message)
        # await self.bot.say("Request sent.")
        msg = "?? **Assistance requested**: {0} by {1} | {2}#{3} @here".format(ctx.message.channel.mention, author.mention, author.name, ctx.message.author.discriminator)
        if msg_request != "":
            # msg += "\n?? __Additional text__: " + msg_request
            embed = discord.Embed(color=discord.Color.gold())
            embed.description = msg_request
        await self.bot.send_message(self.bot.mods_channel, msg, embed=(embed if msg_request != "" else None))
        try:
            await self.bot.send_message(author, "? Online staff has been notified of your request in {0}.".format(ctx.message.channel.mention), embed=(embed if msg_request != "" else None))
        except discord.errors.Forbidden:
            pass
assistance.py 文件源码 项目:Kurisu 作者: ihaveamac 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def guide(self, ctx, *, console="auto"):
        """Links to Plailect's or FlimFlam69's guide."""
        console = console.lower()
        if console == "3ds" or (console == "auto" and "wiiu" not in ctx.message.channel.name):
            embed = discord.Embed(title="Guide", color=discord.Color(0xCE181E))
            embed.set_author(name="Plailect", url="https://3ds.guide/")
            embed.set_thumbnail(url="https://3ds.guide/images/bio-photo.png")
            embed.url = "https://3ds.guide/"
            embed.description = "A complete guide to 3DS custom firmware, from stock to boot9strap."
            await self.bot.say("", embed=embed)
        if (console == "wiiu" or console == "wii u") or (console == "auto" and "3ds" not in ctx.message.channel.name):
            embed = discord.Embed(title="Guide", color=discord.Color(0x009AC7))
            embed.set_author(name="FlimFlam69 & Plailect", url="https://wiiu.guide/")
            embed.set_thumbnail(url="http://i.imgur.com/CpF12I4.png")
            embed.url = "https://wiiu.guide/"
            embed.description = "FlimFlam69 and Plailect's Wii U custom firmware + coldboothax guide"
            await self.bot.say("", embed=embed)

    #Embed to Soundhax Download Website
assistance.py 文件源码 项目:Kurisu 作者: ihaveamac 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def vc(self, ctx, *, console="auto"):
        """Link to Virtual Console Injects for 3DS/Wiiu."""
        console = console.lower()
        if console == "3ds" or (console == "auto" and "wiiu" not in ctx.message.channel.name):
            embed = discord.Embed(title="Virtual Console Injects for 3DS", color=discord.Color.blue())
            embed.set_author(name="Asdolo", url="https://gbatemp.net/members/asdolo.389539/")
            embed.set_thumbnail(url="https://i.imgur.com/rHa76XM.png")
            embed.url = "https://gbatemp.net/search/40920047/?q=injector&t=post&o=date&g=1&c[title_only]=1&c[user][0]=389539"
            embed.description = "The recommended way to play old classics on your 3DS"
            await self.bot.say("", embed=embed)
        if (console == "wiiu" or console == "wii u") or (console == "auto" and "3ds" not in ctx.message.channel.name):
            embed = discord.Embed(title="Virtual Console Injects for Wiiu", color=discord.Color.blue())
            embed.set_author(name="NicoAICP", url="https://gbatemp.net/members/nicoaicp.404553/")
            embed.set_thumbnail(url="https://i.imgur.com/OsXqiOv.png")
            embed.url = "https://gbatemp.net/threads/release-ultimate-vc-injector-for-wiiu.486781/"
            embed.description = "The recommended way to play old classics on your Wiiu"
            await self.bot.say("", embed=embed)

    # Embed to ih8ih8sn0w's godmode9 guide
events.py 文件源码 项目:Kurisu 作者: ihaveamac 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def keyword_search(self, message):
        msg = ''.join(char for char in message.content.lower() if char in printable)
        # if "wiiu" in message.channel.name and "download" in msg and "update" in msg and "manag" in msg:  # intentional typo in manage
        #     embed = discord.Embed(description="A failed update in Download Management does not mean there is an update and the system is trying to download it. This means your blocking method (DNS etc.) is working and the system can't check for an update.", color=discord.Color(0x009AC7))
        #     await self.bot.send_message(message.channel, message.author.mention, embed=embed)
        # search for terms that might indicate a question meant for the help channels
        help_embed = discord.Embed(description="Hello! If you are looking for help with setting up hacks for your 3DS or Wii U system, please ask your question in one of the assistance channels.\n\nFor 3DS, there is <#196635695958196224> or <#247557068490276864>. Ask in one of them.\n\nFor Wii U, go to <#279783073497874442>.\n\nThank you for stopping by!", color=discord.Color.green())
        help_embed.set_footer(text="This auto-response is under development. If you did not ask about the above, you don't need to do anything.")
        if message.author.id not in self.help_notice_anti_repeat:
            if message.channel.name == "hacking-general":
                if all(x in msg for x in ('help ', 'me',)):
                    await self.bot.send_message(message.channel, message.author.mention, embed=help_embed)
                    await self.bot.send_message(self.bot.mods_channel, "Auto-response test in {}".format(message.channel.mention))
                    self.help_notice_anti_repeat.append(message.author.id)
                    await asyncio.sleep(120)
                    try:
                        self.help_notice_anti_repeat.remove(message.author.id)
                    except ValueError:
                        pass
customroles.py 文件源码 项目:PaddoCogs 作者: PaddoInWonderland 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def server_add_role(self, server, role, color):
        if re.search(r'^(?:[0-9a-fA-F]{3}){1,2}$', color):
            color = discord.Color(int(color, 16))
            try:
                if not await self.server_has_role(server, role):
                    await self.bot.create_role(server, name=role, color=color, permissions=discord.Permissions(permissions=0), hoist=False)
                    if server.id not in self.roles:
                        self.roles[server.id] = {}
                    self.roles[server.id][role] = {}
                    await self.save_role_data()
                    return 0
                else:
                    return 3
            except discord.Forbidden:
                return 2
        else:
            return 1
botmanager.py 文件源码 项目:JshBot-legacy 作者: jkchen2 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def update_color_role(server_id, user_id, color):

    # Get server and user, along with role name
    server = discord.utils.get(client.servers, id=server_id)
    user = discord.utils.get(server.members, id=user_id)
    role_name = 'c_{}'.format(user_id)

    # Remove role if it exists, even if it's not used
    current_role = discord.utils.get(user.roles, name=role_name)
    if current_role is not None:
        await client.delete_role(server, current_role)
    if color is not None: # Assign new color
        new_role = await client.create_role(
            server,
            colour=discord.Color(color),
            name=role_name)

        # Finally, assign new role to user
        await client.add_roles(user, new_role)
ClientWrapper.py 文件源码 项目:pineapple 作者: peter765 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def get_color(name):
        random.seed(name)
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        return discord.Color((r << 16) + (g << 8) + b)
quickembed.py 文件源码 项目:Sitryk-Cogs 作者: Sitryk 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def qembed(self, ctx, text, color=None):
        """Used to make a quick embed

        {server} is ctx.message.server
        {author} is ctx.message.author
        {channel} is ctx.message.channel
        {message} is ctx.message
        {ctx} is ctx
        """

        if color is None:
            embed_color = self.colours[self.data["default_colour"]]()
        elif color.lower() not in self.colours:
            if color.startswith('#'):
                color = color[1:]
            try:
                if validhex(int(color, 16)):
                    embed_color = discord.Color(int(color, 16))
            except ValueError:
                await send_cmd_help(ctx)
                return
            if not validhex(int(color, 16)):
                await send_cmd_help(ctx)
                return
        else:
            embed_color = self.colours[color]()

        embed = discord.Embed(description=text.format(server=ctx.message.server, author=ctx.message.author, channel=ctx.message.channel, message=ctx.message, ctx=ctx), color=embed_color)
        await self.bot.say(embed=embed)
randomshizzle.py 文件源码 项目:PTSCogs 作者: PlanetTeamSpeakk 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def rainbow(self, times:int, interval:float):
        """Make a happy rainbow!"""
        rainbow = await self.bot.say(embed=discord.Embed(title="Rainbow!", color=discord.Color.red()))
        time = 0
        error = 0
        if interval < 1.4:
            interval = 1.5
        while times > time:
            time = time + 1
            color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
            color = int(color, 16)
            try:
                await self.bot.edit_message(rainbow, embed=discord.Embed(title="Rainbow!", color=discord.Color(value=color)))
            except:
                if error < 1:
                    await self.bot.say("An error occured, trying again.")
                    error = error + 1
                else:
                    await self.bot.say("Another error occured, exiting.")
                    return
            await asyncio.sleep(interval)
general.py 文件源码 项目:Excalibot 作者: endreman0 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def color(self, ctx, *, color : discord.Color):
        """Displays information about a color, by name or hex code."""
        async with ctx.typing(), ctx.bot.http._session.get('http://rgb.to/save/json/color/{:0>6x}'.format(color.value)) as resp:
            color_data = json.loads(await resp.text()) # resp.json() raises an exception because the content type is text/plain
        e = discord.Embed(color=color)
        e.add_field(name='Hex Representation', value=color_data['hex'].upper())
        e.add_field(name='Web-Safe Version', value=color_data['websafe'].upper())
        e.add_field(name='RGB', value='{r}, {g}, {b}'.format(**color_data['rgb']))
        e.add_field(name='HSL', value='{h}deg, {s}%, {l}%'.format(**color_data['hsl']))
        e.add_field(name='HSB', value='{h}deg, {s}%, {b}%'.format(**color_data['hsb']))
        e.add_field(name='CMYK', value='{c}, {m}, {y}, {k}'.format(**color_data['cmyk']))
        await ctx.send(embed=e)
general.py 文件源码 项目:Excalibot 作者: endreman0 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def color_list(self, ctx, per_page : int = 6):
        """Lists all named colors available."""
        colors = [(' '.join(word.title() for word in name.split('_')), color, str(color).upper()) for name, color in self._colors()]
        colors += [('Default', discord.Color(0), '#000000')] * (6 - len(colors) % 6)
        per_page = 6
        letter_emoji = abc_emoji[:per_page]
        pages = [discord.Embed() for page_num in range(math.ceil(len(colors) / per_page))]
        def update_embeds(shown):
            for page_num, page in enumerate(pages):
                page_colors = colors[page_num*per_page:][:per_page] # Two slices is more readable than [page_num*per_page:page_num*per_page + per_page]
                page.color = page_colors[shown][1]
                for field_num, (name, _, hex_) in enumerate(page_colors):
                    page.set_field_at(
                        field_num,
                        name='{}: {}{}'.format(string.ascii_uppercase[field_num], name, ' (shown)' if field_num == shown else ''),
                        value=hex_
                    )

        for i, _ in enumerate(colors):
            pages[i // per_page].add_field(name='', value='') # Add fields so set_field_at in update_embeds is valid
        update_embeds(0)

        reactor = react.Paginator(ctx, (..., *letter_emoji), pages)
        async for reaction in reactor:
            if reaction in letter_emoji:
                update_embeds(letter_emoji.index(reaction))
                reactor.next(0) # Re-send the same embed to show updated color and names
general.py 文件源码 项目:Excalibot 作者: endreman0 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def _colors(self, cls=discord.Color):
        for name in dir(cls):
            attr = getattr(cls, name)
            if inspect.ismethod(attr) and not inspect.signature(attr).parameters: # No-args classmethods are color factory methods
                yield (name, attr())
color.py 文件源码 项目:kitsuchan-2 作者: n303p4 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def setup(bot):
    """Sets up the cog."""
    bot.add_cog(Color())
oshimen.py 文件源码 项目:YukirinCogs 作者: skeith 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _wota(self, ctx):
        """Joins the wota and embrace 48G grace!"""

        server = ctx.message.server
        user = ctx.message.author

        if server.id not in self.oshi:
            self.oshi[server.id] = {}
        else:
            pass

        if user.id not in self.oshi[server.id]:
            self.oshi[server.id][user.id] = {}
            dataIO.save_json(OJSON, self.oshi)
            data = discord.Embed(colour=discord.Color(0xffb6c1))
            data.add_field(
                name="Ohayou! :tada:",
                value=("Your Oshimen card is ") +
                ("succesfully generated, {}.").format(user.name) +
                (" Use {}write to start adding ").format(ctx.prefix) +
                ("your Oshimen on the card"))
            await self.bot.say(embed=data)
        else:
            data = discord.Embed(colour=discord.Color(0xffb6c1))
            data.add_field(
                name="Ara~!",
                value=("Yuihan said you already have ") +
                ("an Oshimen card, {}.").format(user.name) +
                (" Use {}write to add Oshimen ").format(ctx.prefix) +
                ("onto your card"))
            await self.bot.say(embed=data)
oshimen.py 文件源码 项目:YukirinCogs 作者: skeith 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def oshimen(self, ctx, *, oshimen):
        """Who is your oshi?
        Please write the full name with the format of Familyname Givenname
        e.g. [p]write oshimen Kashiwagi Yuki

        [p] = prefix"""

        server = ctx.message.server
        user = ctx.message.author
        prefix = ctx.prefix

        if server.id not in self.oshi:
            self.oshi[server.id] = {}
        else:
            pass

        if not isascii(oshimen):
            await self.bot.say("Oshimens must be written in ASCII characters")
            return
        else:
            pass

        if user.id not in self.oshi[server.id]:
            data = discord.Embed(colour=discord.Color(0xffb6c1))
            data.add_field(
                name="Gomen ne~!",
                value=("You'll need to apply for an Oshimen card to use") +
                (" this feature. Type {}wota").format(prefix) +
                (" to apply for one."))
            await self.bot.say(embed=data)
        else:
            self.oshi[server.id][user.id].update({"Oshimen": oshimen})
            dataIO.save_json(OJSON, self.oshi)
            data = discord.Embed(colour=discord.Color(0xffb6c1))
            data.add_field(name="Yatta! :sparkling_heart:",
                           value=("I am sure {} is very ").format(oshimen) +
                           ("thankful for your support"))
            await self.bot.say(embed=data)
oshimen.py 文件源码 项目:YukirinCogs 作者: skeith 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def supporttype(self, ctx, *, support_type):
        """How devoted are you?
        Support types are : Kami-Oshi, Oshi, DD or Daredemo Daisuki,
         MD or Minna Daisuki or write anything you like"""

        server = ctx.message.server
        user = ctx.message.author
        prefix = ctx.prefix

        if server.id not in self.oshi:
            self.oshi[server.id] = {}
        else:
            pass

        if user.id not in self.oshi[server.id]:
            data = discord.Embed(colour=discord.Color(0xffb6c1))
            data.add_field(
                name="Gomen ne~!",
                value=("You'll need to apply for an Oshimen card to use") +
                (" this feature. Type {}wota").format(prefix) +
                (" to apply for one."))
            await self.bot.say(embed=data)
        else:
            self.oshi[server.id][user.id].update(
                {"Support Type": support_type})
            dataIO.save_json(OJSON, self.oshi)
            data = discord.Embed(colour=discord.Color(0xffb6c1))
            data.add_field(name="Arigatou! :bow:",
                           value=("We are very grateful of your support. ") +
                           ("The support type {} ").format(support_type) +
                           ("has been saved"))
            await self.bot.say(embed=data)
nandeyanen.py 文件源码 项目:YukirinCogs 作者: skeith 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def pat(self, ctx, *, user: discord.Member=None):
        """Pat users."""
        author = ctx.message.author

        if not user:
            await self.bot.say("{} is trying to pat the air ... and failed.".format(author.name))
        else:
            patdata = discord.Embed(description="**{}** got a pat from **{}**".format(user.name, author.name), color=discord.Color(0xffb6c1))
            patdata.set_image(url=rnd(self.patimg))
            # this line is for testing purpose
            # patdata.set_image(url="https://i.imgur.com/YTGnx49.gif")
            await self.bot.say(embed=patdata)
nandeyanen.py 文件源码 项目:YukirinCogs 作者: skeith 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def kitty(self):
        """The cure of boredom."""
        try:
            async with self.session.get(self.caturl) as r:
                result = await r.json()
            cat = discord.Embed(description="\u2063", color=discord.Color(0xffb6c1))
            cat.set_image(url=result['file'])
            # await self.bot.say(result['file'])
            await self.bot.say(embed=cat)
        except:
            await self.bot.say("Couldn't Get An Image")
nandeyanen.py 文件源码 项目:YukirinCogs 作者: skeith 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def doggo(self):
        """Wait! There is more cure of boredom?"""
        try:
            async with self.session.get(self.dogurl) as r:
                result = await r.json()
                print(result)
            dog = discord.Embed(description="\u2063", color=discord.Color(0xffb6c1))
            dog.set_image(url=result['message'])
            # await self.bot.say(result['file'])
            await self.bot.say(embed=dog)
        except:
            await self.bot.say("Couldn't Get An Image")
nandeyanen.py 文件源码 项目:YukirinCogs 作者: skeith 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def rquote(self):
        """To make human pointless existence worth."""
        try:
            async with self.session.get(self.qturl) as r:
                result = await r.text()
            qt = discord.Embed(description="\u2063", color=discord.Color(0xffb6c1))
            qt.set_image(url=result)
            await self.bot.say(embed=qt)
        except:
            await self.bot.say("Couldn't Get An Image")
mod.py 文件源码 项目:dogbot 作者: slice 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def vanity(self, ctx, name: str, color: discord.Color = None, assign_to: discord.Member = None):
        """
        Creates a vanity role.

        A vanity role is defined as a role with no permissions.
        """
        role = await ctx.guild.create_role(name=name, permissions=discord.Permissions.none(),
                                           color=color or discord.Color.default())
        if assign_to:
            try:
                await assign_to.add_roles(role)
            except discord.HTTPException:
                return await ctx.send(f"{ctx.red_tick} Couldn't give {role.name} to that person.")

        await ctx.send(f'{ctx.green_tick} Created vanity role {describe(role, quote=True)}.')
info.py 文件源码 项目:dogbot 作者: slice 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def profile_describe(self, ctx, color: discord.Color, *, description):
        """Sets your profile description and color. Supporter only."""
        if len(description) > 1024:
            return await ctx.send('That description is too long. There is a maximum of 1024 characters.')
        async with ctx.acquire() as conn:
            sql = """INSERT INTO profile_descriptions (id, description, color) VALUES ($1, $2, $3)
                     ON CONFLICT (id) DO UPDATE SET description = $2, color = $3"""
            await conn.execute(sql, ctx.author.id, description, color.value)
        await ctx.send('\N{OK HAND SIGN} Updated your profile!')
general.py 文件源码 项目:MangoByte 作者: mdiller 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def changelog(self, ctx):
        """Gets a rough changelog for mangobyte

        Note that this is a very rough changelog built from git commit messages and so will sometimes not relate directly to your perspective.

        For more commit versions or better detailed information, check out the source on [GitHub](https://github.com/mdiller/MangoByte/commits/master)
        """
        commit_url = "https://github.com/mdiller/MangoByte"
        description = f"For more information check out the [commit history]({commit_url}/commits/master) on GitHub\n"
        lines = get_changelog().split("\n")

        recent_date = 0

        for line in lines:
            if line == "":
                continue
            commit = line.split(",")
            full_sha = commit[0]
            timestamp = int(commit[1])
            small_sha = commit[2]
            message = ",".join(commit[3:])
            if timestamp > recent_date:
                recent_date = timestamp
            description += f"\n[`{small_sha}`]({commit_url}/commit/{full_sha}) {message}"

        if recent_date != 0:
            embed = discord.Embed(description=description, color=discord.Color.green(), timestamp=datetime.datetime.utcfromtimestamp(recent_date))
            embed.set_footer(text="Most recent change at")
        else:
            embed = discord.Embed(description=description, color=discord.Color.green())

        embed.set_author(name="Changelog", url=f"{commit_url}/commits/master")
        await ctx.send(embed=embed)
general.py 文件源码 项目:MangoByte 作者: mdiller 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def info(self, ctx):
        """Prints info about mangobyte"""
        github = "https://github.com/mdiller/MangoByte"
        python_version = "[Python {}.{}.{}]({})".format(*os.sys.version_info[:3], "https://www.python.org/")
        discordpy = "https://github.com/Rapptz/discord.py"

        embed = discord.Embed(description="The juiciest unsigned 8 bit integer you eva gonna see", color=discord.Color.green())

        embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar_url, url=github)

        embed.add_field(name="Development Info", value=(
            "Developed as an open source project, hosted on [GitHub]({}). "
            "Implemented using {} and a python discord api wrapper [discord.py]({})".format(github, python_version, discordpy)))

        embed.add_field(name="Features", value=(
            "• Answers questions (`?ask`)\n"
            "• Plays audio clips (`?play`, `?dota`)\n"
            "• Greets users joining a voice channel\n"
            "• For a list of command categories, try `?help`"))

        help_guild_link = "https://discord.gg/d6WWHxx"

        embed.add_field(name="Help", value=(
            f"If you want to invite mangobyte to your server/guild, click this [invite link]({invite_link}). "
            f"If you have a question, suggestion, or just want to try out mah features, check out the [Help Server/Guild]({help_guild_link})."))

        owner = (await self.bot.application_info()).owner

        embed.set_footer(text="MangoByte developed by {}".format(owner.name), icon_url=owner.avatar_url)

        await ctx.send(embed=embed)
general.py 文件源码 项目:MangoByte 作者: mdiller 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def botstats(self, ctx):
        """Displays some bot statistics"""
        embed = discord.Embed(color=discord.Color.green())

        embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar_url)

        embed.add_field(name="Servers/Guilds", value="{:,}".format(len(self.bot.guilds)))
        embed.add_field(name="Registered Users", value="{:,}".format(len(list(filter(lambda user: user.steam32, botdata.userinfo_list())))))

        commands = loggingdb_session.query(loggingdb.Message).filter(loggingdb.Message.command != None)
        commands_weekly = commands.filter(loggingdb.Message.timestamp > datetime.datetime.utcnow() - datetime.timedelta(weeks=1))
        embed.add_field(name="Commands", value=f"{commands.count():,}")
        embed.add_field(name="Commands (This Week)", value=f"{commands_weekly.count():,}")


        top_commands = loggingdb_session.query(loggingdb.Message.command, func.count(loggingdb.Message.command)).filter(loggingdb.Message.command != None).group_by(loggingdb.Message.command).order_by(func.count(loggingdb.Message.command).desc())
        if top_commands.count() >= 3:
            embed.add_field(name="Top Commands", value=(
                f"`?{top_commands[0][0]}`\n"
                f"`?{top_commands[1][0]}`\n"
                f"`?{top_commands[2][0]}`\n"))

        top_commands_weekly = top_commands.filter(loggingdb.Message.timestamp > datetime.datetime.utcnow() - datetime.timedelta(weeks=1))
        if top_commands_weekly.count() >= 3:
            embed.add_field(name="Top Commands (This Week)", value=(
                f"`?{top_commands_weekly[0][0]}`\n"
                f"`?{top_commands_weekly[1][0]}`\n"
                f"`?{top_commands_weekly[2][0]}`\n"))

        await ctx.send(embed=embed)


问题


面经


文章

微信
公众号

扫码关注公众号