Python discord.Colour() Examples

The following are 30 code examples of discord.Colour(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module discord , or try the search function .
Example #1
Source File: maths.py    From cyberdisc-bot with MIT License 35 votes vote down vote up
def challenge(self, ctx: Context, number: int = 1):
        """Show the provided challenge number."""
        challenge = await get_challenge(number)
        description = challenge["challenge"]
        if len(description) > 2048:
            description = description[:2045] + "..."
        embed = Embed(
            title=challenge["title"],
            colour=Colour(0xE5E242),
            url=f"https://www.kingsmathsschool.com/weekly-maths-challenge/{challenge['slug']}",
            description=description,
        )

        embed.set_image(url=challenge["image"])
        embed.set_thumbnail(
            url="https://pbs.twimg.com/profile_images/502115424121528320/hTQzj_-R.png"
        )
        embed.set_author(name="King's Maths School")
        embed.set_footer(
            text=f"Challenge Released: {challenge['published']} | Category: {challenge['category']}"
        )
        return await ctx.send(embed=embed) 
Example #2
Source File: core.py    From NabBot with Apache License 2.0 8 votes vote down vote up
def process_command_invoke_error(self, ctx: context.NabCtx, error: commands.CommandInvokeError):
        """Handles CommandInvokeError.

        This exception is raised when an exception is raised during command execution."""
        error_name = error.original.__class__.__name__
        if isinstance(error.original, errors.NetworkError):
            log.error(f"{error_name} in command {ctx.clean_prefix}{ctx.command.qualified_name}: {error.original}")
            return await ctx.error("I'm having network issues right now. Please try again in a moment.")
        log.error(f"{self.tag} Exception in command: {ctx.message.clean_content}", exc_info=error.original)
        if isinstance(error.original, discord.HTTPException):
            await ctx.error("Sorry, the message was too long to send.")
        else:
            if ctx.bot_permissions.embed_links:
                embed = discord.Embed(colour=discord.Colour(0xff1414))
                embed.set_author(name="Support Server", url="https://discord.gg/NmDvhpY",
                                 icon_url=self.bot.user.avatar_url)
                embed.set_footer(text="Please report this bug in the support server.")
                embed.add_field(name=f"{ctx.tick(False)}Command Error",
                                value=f"```py\n{error_name}: {error.original}```",
                                inline=False)
                await ctx.send(embed=embed)
            else:
                await ctx.error(f'Command error:\n```py\n{error_name}: {error.original}```') 
Example #3
Source File: modlog.py    From bot with MIT License 7 votes vote down vote up
def on_member_unban(self, guild: discord.Guild, member: discord.User) -> None:
        """Log member unban event to mod log."""
        if guild.id != GuildConstant.id:
            return

        if member.id in self._ignored[Event.member_unban]:
            self._ignored[Event.member_unban].remove(member.id)
            return

        member_str = escape_markdown(str(member))
        await self.send_log_message(
            Icons.user_unban, Colour.blurple(),
            "User unbanned", f"{member_str} (`{member.id}`)",
            thumbnail=member.avatar_url_as(static_format="png"),
            channel_id=Channels.mod_log
        ) 
Example #4
Source File: mod.py    From Discord-SelfBot with MIT License 6 votes vote down vote up
def _colour(self, ctx, role: str, colour: str):
        """Set the Color of a Role."""
        role = getRole(ctx, role)
        colour = getColor(colour)
        if not role:
            return await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Role not found", ttl=5)
        elif not colour:
            return await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Colour not found", ttl=5)
        else:
            value = discord.Colour(int((colour.hex_l.strip('#')), 16))
            try:
                await role.edit(colour=value)
            except discord.HTTPException:
                await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Missing permissions to edit this role", ttl=5)
            else:
                e = discord.Embed(color=value)
                e.set_author(name="Changed Role Color of: " + str(role))
                await edit(ctx, embed=e) 
Example #5
Source File: utility.py    From Discord-Selfbot with GNU General Public License v3.0 6 votes vote down vote up
def getcolour(self, ctx, *, colour_codes):
        """Posts color of given hex"""
        await ctx.message.delete()
        colour_codes = colour_codes.split()
        size = (60, 80) if len(colour_codes) > 1 else (200, 200)
        if len(colour_codes) > 5:
            return await ctx.send(self.bot.bot_prefix + "Sorry, 5 colour codes maximum")
        for colour_code in colour_codes:
            if not colour_code.startswith("#"):
                colour_code = "#" + colour_code
            image = Image.new("RGB", size, colour_code)
            with io.BytesIO() as file:
                image.save(file, "PNG")
                file.seek(0)
                await ctx.send("Colour with hex code {}:".format(colour_code), file=discord.File(file, "colour_file.png"))
            await asyncio.sleep(1)  # Prevent spaminess 
Example #6
Source File: tweets.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def _list(self, ctx):
        """Lists the autotweet accounts on the server"""
        account_list = ""
        server = ctx.message.server
        server_channels = [x.id for x in server.channels]
        for account in self.settings["accounts"]:
            for channel_id in self.settings["accounts"][account]["channel"]:
                if channel_id in server_channels:
                    account_list += self.settings["accounts"][account]["username"] + ", "
        if account_list != "":
            embed = discord.Embed(title="Twitter accounts posting in {}".format(server.name),
                                  colour=discord.Colour(value=self.random_colour()),
                                  description=account_list[:-2],
                                  timestamp=ctx.message.timestamp)
            embed.set_author(name=server.name, icon_url=server.icon_url)
            await self.bot.send_message(ctx.message.channel, embed=embed)
        else:
            await self.bot.send_message(ctx.message.channel, "I don't seem to have autotweets setup here!") 
Example #7
Source File: tibiawiki.py    From NabBot with Apache License 2.0 6 votes vote down vote up
def get_item_embed_adjust_city(cls, name, city, embed):
        name = name.lower()
        if name == 'alesar' or name == 'yaman':
            embed.colour = discord.Colour.green()
            return "Green Djinn's Fortress"
        elif name == "nah'bob" or name == "haroun":
            embed.colour = discord.Colour.blue()
            return "Blue Djinn's Fortress"
        elif name == 'rashid':
            embed.colour = discord.Colour(0xF0E916)
            return cls.get_rashid_position().city
        elif name == 'yasir':
            return 'his boat'
        elif name == 'briasol':
            embed.colour = discord.Colour(0xA958C4)
        return city 
Example #8
Source File: tweets.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def get_user(self, ctx, username: str):
        """Get info about the specified user"""
        message = ""
        if username is not None:
            api = await self.authenticate()
            user = api.get_user(username)
            url = "https://twitter.com/" + user.screen_name
            emb = discord.Embed(title=user.name,
                                colour=discord.Colour(value=self.random_colour()),
                                url=url,
                                description=user.description)
            emb.set_thumbnail(url=user.profile_image_url)
            emb.add_field(name="Followers", value=user.followers_count)
            emb.add_field(name="Friends", value=user.friends_count)
            if user.verified:
                emb.add_field(name="Verified", value="Yes")
            else:
                emb.add_field(name="Verified", value="No")
            footer = "Created at " + user.created_at.strftime("%Y-%m-%d %H:%M:%S")
            emb.set_footer(text=footer)
            await self.bot.send_message(ctx.message.channel, embed=emb)
        else:
            message = "Uh oh, an error occurred somewhere!"
            await self.bot.say(message) 
Example #9
Source File: tarot.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def _card(self, ctx, *, msg=None):
        user = ctx.message.author.id
        # msg = message.content
        card = None

        if msg is None:
            card = self.tarot_cards[str(random.randint(1, 78))]

        elif msg.isdigit() and int(msg) > 0 and int(msg) < 79:
            card = self.tarot_cards[str(msg)]
        
        elif not msg.isdigit():
            for cards in self.tarot_cards:
                if msg.lower() in self.tarot_cards[cards]["card_name"].lower():
                    card = self.tarot_cards[cards]
            if card is None:
                await self.bot.say("That card does not exist!")
                return

        embed = discord.Embed(title=card["card_name"],
                              description=card["card_meaning"],
                              colour=discord.Colour(value=self.get_colour()),
                              url=card["card_url"])
        embed.set_image(url=card["card_img"])
        await self.bot.send_message(ctx.message.channel, embed=embed) 
Example #10
Source File: tarot.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def _reading(self, ctx, user: discord.Member=None):
        card_meaning = ["Past", "Present", "Future", "Potential", "Reason"]
        if user is None:
            user = ctx.message.author
        
        cards = []
        cards = sample((range(1, 78)), 5)
        
        embed = discord.Embed(title="Tarot reading for {}".format(user.display_name),
                              colour=discord.Colour(value=self.get_colour()))
        number = 0
        for card in cards:
            embed.add_field(name="{0}: {1}".format(card_meaning[number], self.tarot_cards[str(card)]["card_name"]),
                            value=self.tarot_cards[str(card)]["card_meaning"])
            number += 1
        await self.bot.send_message(ctx.message.channel, embed=embed) 
Example #11
Source File: tarot.py    From Trusty-cogs-archive with MIT License 6 votes vote down vote up
def _life(self, ctx, user: discord.Member=None):
        card_meaning = ["Past", "Present", "Future", "Potential", "Reason"]
        if user is None:
            user = ctx.message.author
        userseed = user.id
        
        random.seed(int(userseed))
        cards = []
        cards = sample((range(1, 78)), 5)
        
        embed = discord.Embed(title="Tarot reading for {}".format(user.display_name),
                              colour=discord.Colour(value=self.get_colour()))
        number = 0
        for card in cards:
            embed.add_field(name="{0}: {1}".format(card_meaning[number], self.tarot_cards[str(card)]["card_name"]),
                            value=self.tarot_cards[str(card)]["card_meaning"])
            number += 1
        await self.bot.send_message(ctx.message.channel, embed=embed) 
Example #12
Source File: converter.py    From discord.py with MIT License 6 votes vote down vote up
def convert(self, ctx, argument):
        arg = argument.replace('0x', '').lower()

        if arg[0] == '#':
            arg = arg[1:]
        try:
            value = int(arg, base=16)
            if not (0 <= value <= 0xFFFFFF):
                raise BadArgument('Colour "{}" is invalid.'.format(arg))
            return discord.Colour(value=value)
        except ValueError:
            arg = arg.replace(' ', '_')
            method = getattr(discord.Colour, arg, None)
            if arg.startswith('from_') or method is None or not inspect.ismethod(method):
                raise BadArgument('Colour "{}" is invalid.'.format(arg))
            return method() 
Example #13
Source File: formatters.py    From Firetail with MIT License 6 votes vote down vote up
def colour(*args):
    """Returns a discord Colour object.
    Pass one as an argument to define colour:
        `str` match common colour names.
        `discord.Guild` bot's guild colour.
        `None` light grey.
    """
    arg = args[0] if args else None
    if isinstance(arg, str):
        color = arg
        try:
            return getattr(discord.Colour, color)()
        except AttributeError:
            return discord.Colour.lighter_grey()
    if isinstance(arg, discord.Guild):
        return arg.me.colour
    else:
        return discord.Colour.lighter_grey() 
Example #14
Source File: helpers.py    From bot with MIT License 6 votes vote down vote up
def __init__(self, **kwargs) -> None:
        default_kwargs = {
            'id': next(self.discord_id),
            'name': 'role',
            'position': 1,
            'colour': discord.Colour(0xdeadbf),
            'permissions': discord.Permissions(),
        }
        super().__init__(**collections.ChainMap(kwargs, default_kwargs))

        if isinstance(self.colour, int):
            self.colour = discord.Colour(self.colour)

        if isinstance(self.permissions, int):
            self.permissions = discord.Permissions(self.permissions)

        if 'mention' not in kwargs:
            self.mention = f'&{self.name}' 
Example #15
Source File: test_information.py    From bot with MIT License 6 votes vote down vote up
def test_roles_command_command(self):
        """Test if the `role_info` command correctly returns the `moderator_role`."""
        self.ctx.guild.roles.append(self.moderator_role)

        self.cog.roles_info.can_run = unittest.mock.AsyncMock()
        self.cog.roles_info.can_run.return_value = True

        coroutine = self.cog.roles_info.callback(self.cog, self.ctx)

        self.assertIsNone(asyncio.run(coroutine))
        self.ctx.send.assert_called_once()

        _, kwargs = self.ctx.send.call_args
        embed = kwargs.pop('embed')

        self.assertEqual(embed.title, "Role information (Total 1 role)")
        self.assertEqual(embed.colour, discord.Colour.blurple())
        self.assertEqual(embed.description, f"\n`{self.moderator_role.id}` - {self.moderator_role.mention}\n") 
Example #16
Source File: imagemaker.py    From Trusty-cogs with MIT License 6 votes vote down vote up
def banner(
        self, ctx: commands.Context, colour: Optional[discord.Colour] = (255, 0, 0), *, text: str
    ) -> None:
        """
            Generate a scrolling text gif banner
        """
        if isinstance(colour, discord.Colour):
            colour = colour.to_rgb() + (0,)
        async with ctx.channel.typing():
            task = functools.partial(self.make_banner, text=text, colour=colour)
            task = ctx.bot.loop.run_in_executor(None, task)
            try:
                image = await asyncio.wait_for(task, timeout=60)
            except asyncio.TimeoutError:
                return
            file = discord.File(image)
            await ctx.send(files=[file]) 
Example #17
Source File: welcome.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def colour(self, ctx: commands.Context, colour: discord.Colour) -> None:
        """
        Set the embed colour

        This accepts hex codes and integer value colours
        """
        await self.config.guild(ctx.guild).EMBED_DATA.colour.set(colour.value)
        await ctx.tick() 
Example #18
Source File: botadmin.py    From discordbot.py with MIT License 5 votes vote down vote up
def _setcolor(self, *, color : discord.Colour):
        """Sets the default color of embeds."""
        data = self.bot.config.get("meta", {})
        data['default_color'] = str(color)
        await self.bot.config.put('meta', data)
        await self.bot.responses.basic(message="The default color has been updated.") 
Example #19
Source File: tibiawiki.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def rashid(self, ctx: NabCtx):
        """Shows where Rashid is today.

        For more information, use `npc Rashid`."""
        rashid = self.get_rashid_position()
        npc = models.Npc.get_by_field(wiki_db, "name", "Rashid")
        embed = TibiaWiki.get_base_embed(npc)
        embed.colour = discord.Colour.greyple()
        embed.description = f"Rashid is in **{rashid.city}** today."
        embed.set_footer(text=rashid.location)
        if ctx.bot_permissions.attach_files:
            files = []
            if npc.image is not None:
                thumbnail = io.BytesIO(npc.image)
                filename = re.sub(r"[^A-Za-z0-9]", "", npc.name) + ".gif"
                embed.set_thumbnail(url=f"attachment://{filename}")
                files.append(discord.File(thumbnail, filename))
            if None not in [rashid.x, rashid.y, rashid.z]:
                map_filename = re.sub(r"[^A-Za-z0-9]", "", npc.name) + "-map.png"
                map_image = io.BytesIO(get_map_area(rashid.x, rashid.y, rashid.z))
                embed.set_image(url=f"attachment://{map_filename}")
                embed.add_field(name="Location", value=f"[Mapper link]"
                                                       f"({self.get_mapper_link(rashid.x,rashid.y,rashid.z)})",
                                inline=False)
                files.append(discord.File(map_image, map_filename))
            return await ctx.send(files=files, embed=embed)
        await ctx.send(embed=embed) 
Example #20
Source File: settings.py    From pollmaster with MIT License 5 votes vote down vote up
def __init__(self):
        self.color = discord.Colour(int('7289da', 16))
        self.title_icon = "https://i.imgur.com/vtLsAl8.jpg" #PM
        self.author_icon = "https://i.imgur.com/TYbBtwB.jpg" #tag
        self.report_icon = "https://i.imgur.com/YksGRLN.png" #report
        self.owner_id = 117687652278468610
        self.msg_errors = False
        self.log_errors = True
        self.invite_link = \
            'https://discordapp.com/api/oauth2/authorize?client_id=444831720659877889&permissions=126016&scope=bot'

        self.load_secrets() 
Example #21
Source File: tibiawiki.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def wikistats(self, ctx: NabCtx):
        """Shows information about the TibiaWiki database."""
        embed = discord.Embed(colour=discord.Colour.blurple(), title="TibiaWiki database statistics", description="")
        embed.set_thumbnail(url=WIKI_ICON)
        version = ""
        gen_date = None
        with closing(wiki_db.cursor()) as c:
            info = c.execute("SELECT * FROM database_info").fetchall()
            for entry in info:
                if entry['key'] == "version":
                    version = f" v{entry['value']}"
                if entry['key'] == "timestamp":
                    gen_date = float(entry['value'])
            nb_space = '\u00a0'
            embed.description += f"**‣ Achievements:** {self.count_table('achievement'):,}"
            embed.description += f"\n**‣ Charms:** {self.count_table('charm'):,}"
            embed.description += f"\n**‣ Creatures:** {self.count_table('creature'):,}"
            embed.description += f"\n**{nb_space*8}‣ Drops:** {self.count_table('creature_drop'):,}"
            embed.description += f"\n**‣ Houses:** {self.count_table('house'):,}"
            embed.description += f"\n**‣ Imbuements:** {self.count_table('imbuement'):,}"
            embed.description += f"\n**‣ Items:** {self.count_table('item'):,}"
            embed.description += f"\n**{nb_space*8}‣ Attributes:** {self.count_table('item_attribute'):,}"
            embed.description += f"\n**‣ Keys:** {self.count_table('item_key'):,}"
            embed.description += f"\n**‣ NPCs:** {self.count_table('npc'):,}"
            embed.description += f"\n**{nb_space*8}‣ Buy offers:** {self.count_table('npc_offer_buy'):,}"
            embed.description += f"\n**{nb_space*8}‣ Sell offers:** {self.count_table('npc_offer_sell'):,}"
            embed.description += f"\n**{nb_space*8}‣ Destinations:** {self.count_table('npc_destination'):,}"
            embed.description += f"\n**{nb_space*8}‣ Spell offers:** {self.count_table('npc_spell'):,}"
            embed.description += f"\n**‣ Quests:** {self.count_table('quest'):,}"
            embed.description += f"\n**‣ Spells:** {self.count_table('spell'):,}"
        embed.set_footer(text=f"Database generation date")
        embed.timestamp = dt.datetime.utcfromtimestamp(gen_date)
        embed.set_author(name=f"tibiawiki-sql{version}", icon_url="https://github.com/fluidicon.png",
                         url="https://github.com/Galarzaa90/tibiawiki-sql")
        await ctx.send(embed=embed)
    # endregion

    # region Helper Methods 
Example #22
Source File: events.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def _get_colour(self, channel: discord.TextChannel) -> discord.Colour:
        try:
            if await self.bot.db.guild(channel.guild).use_bot_color():
                return channel.guild.me.colour
            else:
                return await self.bot.db.color()
        except AttributeError:
            return await self.bot.get_embed_colour(channel) 
Example #23
Source File: mm.py    From SML-Cogs with MIT License 5 votes vote down vote up
def get_member_embeds(members, timestamp):
        """Discord embed of data display."""
        color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
        color = int(color, 16)
        embeds = []

        # split embed output to multiples of 25
        # because embed only supports 25 max fields
        out_members_group = grouper(25, members)

        for out_members_list in out_members_group:
            data = discord.Embed(
                color=discord.Colour(value=color))
            for m in out_members_list:
                value = []
                roles = [r.name for r in m.roles if r.name != "@everyone"]
                value.append(', '.join(roles))

                name = m.display_name
                since_joined = (timestamp - m.joined_at).days

                data.add_field(
                    name=str(name),
                    value=str(
                        ''.join(value) +
                        '\n{} days ago'.format(
                            since_joined)))
            embeds.append(data)
        return embeds 
Example #24
Source File: Utils.py    From NotSoBot with MIT License 5 votes vote down vote up
def addcolor(self, ctx, name, color:discord.Colour):
		"""Add a color role with the inputted name and Hex Color"""
		try:
				if ctx.message.server is None: return
				roles = list(map(str, ctx.message.server.roles))
				for s in roles:
					if re.search(r'^' + s + r'$', name):
						await self.bot.say("There's already a role with this name!")
						return
				await self.bot.create_role(server=ctx.message.server, permissions=permissions, name=name, color=color)
				await self.bot.say("Added role with name `{0}` and color `{1}`".format(name, color))
		except Exception as e:
				await self.bot.say(code.format(type(e).__name__ + ': ' + str(e))) 
Example #25
Source File: halo.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def Halo5_rank(self, ctx, *, gamertag):
        """Gather playter rank information from Halo 5"""
        colours = {
            "Unranked": "7f7f7f",
            "Bronze": "c27c0e",
            "Silver": "cccccc",
            "Gold": "xf1c40f",
            "Platinum": "e5e5e5",
            "Diamond": "ffffff",
            "Onyx": "000000",
            "Champion": "71368a",
        }
        player_data = await self.request_url(
            "https://www.haloapi.com/stats/h5/servicerecords/arena?", {"players": gamertag}
        )
        tier = player_data["Results"][0]["Result"]["ArenaStats"]["HighestCsrAttained"]["Tier"]
        designation = player_data["Results"][0]["Result"]["ArenaStats"]["HighestCsrAttained"][
            "DesignationId"
        ]
        designation_name, image_url = await self.get_halo5_rank_data(designation, tier)
        embed = discord.Embed(
            title=gamertag,
            description=designation_name,
            colour=discord.Colour(value=int(colours[designation_name], 16)),
            timestamp=ctx.message.created_at,
        )
        embed.add_field(name="Designation", value=str(designation), inline=True)
        embed.add_field(name="Tier", value=str(tier), inline=True)
        embed.set_thumbnail(url=image_url[0])
        await ctx.send(embed=embed) 
Example #26
Source File: starboard.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def colour_starboard(
        self, ctx: commands.Context, starboard: StarboardExists, colour: Union[discord.Colour, str]
    ) -> None:
        """
            Change the default colour for a starboard

            `<name>` is the name of the starboard to toggle
            `<colour>` The colour to use for the starboard embed
            This can be a hexcode or integer for colour or `author/member/user` to use
            the original posters colour or `bot` to use the bots colour.
            Colour also accepts names from [discord.py](https://discordpy.readthedocs.io/en/latest/api.html#colour)
        """
        guild = ctx.guild
        if isinstance(colour, str):
            colour = colour.lower()
            if colour not in ["user", "member", "author", "bot"]:
                return await ctx.send(_("The provided colour option is not valid."))
            else:
                starboard.colour = colour
        else:
            self.starboards[ctx.guild.id][starboard.name].colour = colour.value
        await self._save_starboards(guild)
        msg = _("Starboard `{name}` colour set to `{colour}`.").format(
            name=starboard.name, colour=starboard.colour
        )
        await ctx.send(msg) 
Example #27
Source File: eventmixin.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def get_event_colour(
        self, guild: discord.Guild, event_type: str, changed_object: Union[discord.Role] = None
    ) -> discord.Colour:
        if guild.text_channels:
            cmd_colour = await self.get_colour(guild.text_channels[0])
        else:
            cmd_colour = discord.Colour.red()
        defaults = {
            "message_edit": discord.Colour.orange(),
            "message_delete": discord.Colour.dark_red(),
            "user_change": discord.Colour.greyple(),
            "role_change": changed_object.colour if changed_object else discord.Colour.blue(),
            "role_create": discord.Colour.blue(),
            "role_delete": discord.Colour.dark_blue(),
            "voice_change": discord.Colour.magenta(),
            "user_join": discord.Colour.green(),
            "user_left": discord.Colour.dark_green(),
            "channel_change": discord.Colour.teal(),
            "channel_create": discord.Colour.teal(),
            "channel_delete": discord.Colour.dark_teal(),
            "guild_change": discord.Colour.blurple(),
            "emoji_change": discord.Colour.gold(),
            "commands_used": cmd_colour,
            "invite_created": discord.Colour.blurple(),
            "invite_deleted": discord.Colour.blurple(),
        }
        colour = defaults[event_type]
        if self.settings[guild.id][event_type]["colour"] is not None:
            colour = discord.Colour(self.settings[guild.id][event_type]["colour"])
        return colour 
Example #28
Source File: autorole.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def get_colour(self, channel: discord.TextChannel) -> discord.Colour:
        try:
            if await self.bot.db.guild(channel.guild).use_bot_color():
                return channel.guild.me.colour
            else:
                return await self.bot.db.color()
        except AttributeError:
            return await self.bot.get_embed_colour(channel) 
Example #29
Source File: tweets.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def get_user(self, ctx: commands.context, username: str) -> None:
        """Get info about the specified user"""
        try:
            user = await self.get_twitter_user(username)
        except asyncio.TimeoutError:
            await ctx.send(_("Looking up the user timed out."))
            return
        except tw.error.TweepError:
            await ctx.send(_("{username} could not be found.").format(username=username))
            return
        profile_url = "https://twitter.com/" + user.screen_name
        description = str(user.description)
        for url in user.entities["description"]["urls"]:
            if str(url["url"]) in description:
                description = description.replace(url["url"], str(url["expanded_url"]))
        emb = discord.Embed(
            colour=discord.Colour(value=int(user.profile_link_color, 16)),
            url=profile_url,
            description=str(description),
            timestamp=user.created_at,
        )
        emb.set_author(name=user.name, url=profile_url, icon_url=user.profile_image_url)
        emb.set_thumbnail(url=user.profile_image_url)
        emb.add_field(name="Followers", value=user.followers_count)
        emb.add_field(name="Friends", value=user.friends_count)
        if user.verified:
            emb.add_field(name="Verified", value="Yes")
        footer = "Created at "
        emb.set_footer(text=footer)
        if ctx.channel.permissions_for(ctx.me).embed_links:
            await ctx.send("<" + profile_url + ">", embed=emb)
        else:
            await ctx.send(profile_url) 
Example #30
Source File: tarotreading.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def _life(self, ctx: commands.Context, user: Optional[discord.Member] = None) -> None:
        """Unique reading based on your discord user ID. Doesn't change."""
        card_meaning = ["Past", "Present", "Future", "Potential", "Reason"]
        if user is None:
            user = ctx.message.author
        userseed = user.id

        random.seed(int(userseed))
        cards = []
        cards = sample((range(1, 78)), 5)

        embed = discord.Embed(
            title="Tarot reading for {}".format(user.display_name),
            colour=discord.Colour(value=self.get_colour()),
        )
        embed.set_thumbnail(url=self.tarot_cards[str(cards[-1])]["card_img"])
        embed.timestamp = ctx.message.created_at
        embed.set_author(name=user.name, icon_url=user.avatar_url)
        number = 0
        for card in cards:
            embed.add_field(
                name="{0}: {1}".format(
                    card_meaning[number], self.tarot_cards[str(card)]["card_name"]
                ),
                value=self.tarot_cards[str(card)]["card_meaning"],
            )
            number += 1
        await ctx.send(embed=embed)