Python discord.Color() Examples

The following are 30 code examples of discord.Color(). 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: characters.py    From GW2Bot with MIT License 11 votes vote down vote up
def __init__(self, cog, data):
        self.cog = cog
        self.data = data
        self.name = data["name"]
        self.race = data["race"]
        self.gender = data["gender"].lower()
        self.profession = data["profession"].lower()
        self.level = data["level"]
        self.specializations = data.get("specializations")
        self.color = discord.Color(
            int(self.cog.gamedata["professions"][self.profession]["color"],
                16))
        self.created = datetime.datetime.strptime(data["created"],
                                                  "%Y-%m-%dT%H:%M:%Sz")
        self.age = data["age"]
        self.spec_cache = {} 
Example #2
Source File: moderation.py    From bot with MIT License 6 votes vote down vote up
def modlogs(self, ctx, user: UserWithFallback = None):
		if not user:
			user = ctx.author
		mlogs = await self.bot.db.fetch(
			'SELECT * FROM modlogs WHERE uid=$1 AND gid=$2',
			user.id,
			ctx.guild.id
		)
		if not mlogs:
			return await ctx.error('No modlogs found')
		paginator = WrappedPaginator(prefix='', suffix='')
		for log in mlogs:
			paginator.add_line(f'**Case ID**: {log["caseid"]}\n'
							   f'**Type**: {log["type"].capitalize()}\n'
							   f'**User**: {user}\n'
							   f'**Reason**: {log["reason"]}\n'
							   f'**Date**: {log["date"]}\n'
							   f'**-----------------**')
		embed = discord.Embed(color=discord.Color(15105570), timestamp=datetime.datetime.now(datetime.timezone.utc))
		interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed)
		await interface.send_to(ctx) 
Example #3
Source File: characters.py    From GW2Bot with MIT License 6 votes vote down vote up
def get_profession(self, profession, specializations):
        async def get_elite_spec():
            try:
                spec = specializations[-1]
            except IndexError:
                return None
            if spec:
                if not spec["elite"]:
                    return None
                return spec["name"]
            return None

        def get_icon_url(prof_name):
            base_url = ("https://api.gw2bot.info/"
                        "resources/professions/{}_icon.png")
            return base_url.format(prof_name.replace(" ", "_").lower())

        Profession = collections.namedtuple("Profession",
                                            ["name", "icon", "color"])
        color = discord.Color(
            int(self.gamedata["professions"][profession.lower()]["color"], 0))
        name = await get_elite_spec() or profession
        icon = get_icon_url(name)
        return Profession(name.title(), icon, color) 
Example #4
Source File: userdata.py    From SML-Cogs with MIT License 6 votes vote down vote up
def userdata_info(self, ctx, member: discord.Member=None):
        """Display user data."""
        self.init_server(ctx)
        self.init_user(ctx)
        server = ctx.message.server
        if member is None:
            member = ctx.message.author
        if member.id not in self.settings[server.id]["users"]:
            await self.bot.say("User does not have any user data set.")
            return
        color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
        color = int(color, 16)
        em = discord.Embed(
            color=discord.Color(value=color))
        em.set_author(name=member.display_name)
        for k, v in self.settings[server.id]["users"][member.id].items():
            em.add_field(name=k, value=v)
        await self.bot.say(embed=em) 
Example #5
Source File: simpleembed.py    From FlameCogs with MIT License 6 votes vote down vote up
def sendembed(self, ctx, color:Optional[discord.Color]=None, *, text):
		"""
		Send an embed.
		
		Use the optional parameter `color` to change the color of the embed.
		The embed will contain the text `text`.
		All normal discord formatting will work inside the embed. 
		"""
		if color is None:
			color = await ctx.embed_color()
		embed = discord.Embed(
			description=text,
			color=color
		)
		await ctx.send(embed=embed)
		try:
			await ctx.message.delete()
		except discord.Forbidden:
			pass 
Example #6
Source File: eslog.py    From SML-Cogs with MIT License 5 votes vote down vote up
def random_discord_color():
    """Return random color as an integer."""
    color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
    color = int(color, 16)
    return discord.Color(value=color) 
Example #7
Source File: moderation.py    From bot with MIT License 5 votes vote down vote up
def unmute(self, ctx, user: MuteCheck):
		try:
			await ctx.message.delete()
		except Exception:
			pass
		if not user:
			return
		await ctx.trigger_typing()
		muted = ctx.config.get('mod.mutedrole') or discord.utils.get(ctx.guild.roles, name="Muted")
		await user.remove_roles(muted, reason=f'Unmuted by {ctx.author}')
		if not ctx.silent:
			await ctx.success(f"**{discord.utils.escape_mentions(discord.utils.escape_markdown(str(user)))}** has been unmuted")
		con = await self.bot.db.acquire()
		async with con.transaction():
			query = 'DELETE FROM mutes WHERE uid = $1 AND gid = $2;'
			await self.bot.db.execute(query, user.id, ctx.guild.id)
		await self.bot.db.release(con)
		try:
			self.mutes[ctx.guild.id].pop(user.id, None)
		except KeyError:
			pass
		logch = ctx.config.get('log.moderation')
		if logch:
			embed = discord.Embed(color=discord.Color.green(), timestamp=datetime.datetime.now(datetime.timezone.utc))
			embed.set_author(name=f'Unmute | {user}', icon_url=str(user.avatar_url_as(static_format='png', size=2048)))
			embed.add_field(name='User', value=user.mention, inline=False)
			embed.add_field(name='Moderator', value=ctx.author.mention, inline=False)
			embed.set_footer(text=f'User ID: {user.id} | Mod ID: {ctx.author.id}')
			try:
				await logch.send(embed=embed)
			except Exception:
				pass 
Example #8
Source File: moderation.py    From bot with MIT License 5 votes vote down vote up
def block(self, ctx, blocked: typing.Union[StaffCheck, Role] = None, *, reason = 'No Reason Provided.'):
		try:
			await ctx.message.delete()
		except Exception:
			pass
		await ctx.trigger_typing()
		if isinstance(blocked, discord.Member):
			blocktype = 'User'
		elif isinstance(blocked, discord.Role):
			blocktype = 'Role'
		if blocked == False:
			return

		if not blocked:
			return await ctx.send("You must specify a user")

		current = ctx.channel.overwrites_for(blocked)
		current.update(
			send_messages=False,
			add_reactions=False
		)
		await ctx.channel.set_permissions(
			blocked,
			overwrite=current,
			reason=reason
		)
		if not ctx.silent:
			await ctx.success(f'Successfully blocked **{discord.utils.escape_mentions(discord.utils.escape_markdown(str(blocked)))}** from chatting in {ctx.channel.mention}.')
		logch = ctx.config.get('log.moderation')
		if logch:
			embed = discord.Embed(color=discord.Color.red(), timestamp=datetime.datetime.now(datetime.timezone.utc))
			embed.set_author(name=f'Block | {blocked}', icon_url=str(blocked.avatar_url_as(static_format='png', size=2048)) if blocktype == 'User' else str(ctx.guild.icon_url))
			embed.add_field(name=blocktype, value=f'{blocked}({blocked.id})', inline=False)
			embed.add_field(name='Moderator', value=ctx.author.mention, inline=False)
			embed.add_field(name='Channel', value=ctx.channel.mention, inline=False)
			embed.add_field(name='Reason', value=reason, inline=False)
			embed.set_footer(text=f'{blocktype} ID: {blocked.id} | Mod ID: {ctx.author.id}')
			try:
				await logch.send(embed=embed)
			except Exception:
				pass 
Example #9
Source File: hacktoberstats.py    From seasonalbot with MIT License 5 votes vote down vote up
def build_embed(self, github_username: str, prs: List[dict]) -> discord.Embed:
        """Return a stats embed built from github_username's PRs."""
        logging.info(f"Building Hacktoberfest embed for GitHub user: '{github_username}'")
        pr_stats = self._summarize_prs(prs)

        n = pr_stats['n_prs']
        if n >= PRS_FOR_SHIRT:
            shirtstr = f"**{github_username} has earned a tshirt!**"
        elif n == PRS_FOR_SHIRT - 1:
            shirtstr = f"**{github_username} is 1 PR away from a tshirt!**"
        else:
            shirtstr = f"**{github_username} is {PRS_FOR_SHIRT - n} PRs away from a tshirt!**"

        stats_embed = discord.Embed(
            title=f"{github_username}'s Hacktoberfest",
            color=discord.Color(0x9c4af7),
            description=(
                f"{github_username} has made {n} "
                f"{HacktoberStats._contributionator(n)} in "
                f"October\n\n"
                f"{shirtstr}\n\n"
            )
        )

        stats_embed.set_thumbnail(url=f"https://www.github.com/{github_username}.png")
        stats_embed.set_author(
            name="Hacktoberfest",
            url="https://hacktoberfest.digitalocean.com",
            icon_url="https://hacktoberfest.digitalocean.com/pretty_logo.png"
        )
        stats_embed.add_field(
            name="Top 5 Repositories:",
            value=self._build_top5str(pr_stats)
        )

        logging.info(f"Hacktoberfest PR built for GitHub user '{github_username}'")
        return stats_embed 
Example #10
Source File: crladder.py    From SML-Cogs with MIT License 5 votes vote down vote up
def random_discord_color():
    """Return random color as an integer."""
    color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
    color = int(color, 16)
    return discord.Color(value=color) 
Example #11
Source File: keenlog.py    From SML-Cogs with MIT License 5 votes vote down vote up
def random_discord_color():
    """Return random color as an integer."""
    color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
    color = int(color, 16)
    return discord.Color(value=color) 
Example #12
Source File: card.py    From SML-Cogs with MIT License 5 votes vote down vote up
def get_random_color(self):
        """Return a discord.Color instance of a random color."""
        color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
        color = int(color, 16)
        return discord.Color(value=color) 
Example #13
Source File: rushwars.py    From SML-Cogs with MIT License 5 votes vote down vote up
def random_discord_color():
    """Return random color as an integer."""
    color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
    color = int(color, 16)
    return discord.Color(value=color) 
Example #14
Source File: brawlstars.py    From SML-Cogs with MIT License 5 votes vote down vote up
def random_discord_color():
    """Return random color as an integer."""
    color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
    color = int(color, 16)
    return discord.Color(value=color) 
Example #15
Source File: magic.py    From SML-Cogs with MIT License 5 votes vote down vote up
def change_magic_color(self, server):
        """Change magic role color."""
        if not self.magic_is_running:
            return

        server_settings = self.settings[server.id].copy()
        role_name = server_settings["role"]["name"]
        magic_role = discord.utils.get(server.roles, name=role_name)

        self.hue = self.hue + 10
        self.hue = self.hue % 360
        hex_ = hsluv.hsluv_to_hex((self.hue, 100, 60))
        # Remove # sign from hex
        hex_ = hex_[1:]
        new_color = discord.Color(value=int(hex_, 16))

        await self.bot.edit_role(
            server,
            magic_role,
            color=new_color)

        await self.verify_members(server, magic_role)

        await asyncio.sleep(self.interval)
        if self.magic_is_running:
            if self is self.bot.get_cog("Magic"):
                self.task = self.bot.loop.create_task(
                    self.change_magic_color(server)) 
Example #16
Source File: challonge.py    From SML-Cogs with MIT License 5 votes vote down vote up
def embed_challonge(self, tournament):
        """Return challonge info as Discord embed."""
        em = discord.Embed(
            color=discord.Color(value=int('ff7324', 16)),
            title=tournament["name"])
        fields = [
            ("id", "ID"),
            ("url", "URL"),
            ("description", "Description"),
            ("tournament-type", "Tournament Type"),
            ("started-at", "Started At"),
            ("completed-at", "Completed At"),
            ("full-challonge-url", "URL")
        ]
        for (k, v) in fields:
            em.add_field(
                name=v,
                value=tournament[k])
        return em 
Example #17
Source File: RedditSource.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def create_subreddit_obj(self, data):
        """Given a dict, create a subreddit object"""
        color = data['key_color']
        if "#" in color:
            color = color.replace("#", "")

        try:
            color = discord.Color(int(color, 16))
        except ValueError:
            color = self.color

        return RedditSource.SubReddit(data['display_name'], data['url'], color) 
Example #18
Source File: crapikey.py    From SML-Cogs with MIT License 5 votes vote down vote up
def random_discord_color():
    """Return random color as an integer."""
    color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
    color = int(color, 16)
    return discord.Color(value=color) 
Example #19
Source File: crapikey.py    From SML-Cogs with MIT License 5 votes vote down vote up
def server_log(self, ctx, action, data=None):
        """Send server log to designated channel."""
        if data is None:
            data = '_'
        em = discord.Embed(title="CRAPIKey", description=action, color=discord.Color.red())
        if ctx is not None:
            em.add_field(name="Author", value=ctx.message.author)
            em.add_field(name="Author ID", value=ctx.message.author.id)
            em.add_field(name="Channel", value=ctx.message.channel.mention)
        em.add_field(name="Response", value=data)
        channel = discord.utils.get(ctx.message.server.channels, name=self.config.channels.log)
        await self.bot.send_message(channel, embed=em) 
Example #20
Source File: mm.py    From SML-Cogs with MIT License 5 votes vote down vote up
def edit_role_color(self, ctx, hex: discord.Color, *, role_names):
        """Edit color of role(s)

        Separate each role with a comma. Multi-word roles do not require quotes.
        Use 000000 to change to default color.
        [p]editrolecolor 4286f4 Name of role to edit, Yet another role
        """
        # get list of valid roles
        server = ctx.message.server
        valid_roles = []
        r_names = [rn.strip() for rn in role_names.split(',')]
        for role_name in r_names:
            role = self.get_server_role(server, role_name)
            if role is None:
                await self.bot.say("{} is not a valid role.".format(role_name))
            else:
                valid_roles.append(role)

        # process valid roles
        if len(valid_roles) == 0:
            await self.bot.say("No valid roles left to process")
            return

        tasks = [self.bot.edit_role(server, role, color=hex) for role in valid_roles]
        await self.bot.type()
        results = await asyncio.gather(*tasks, return_exceptions=True)
        for index, result in enumerate(results):
            if isinstance(result, Exception):
                await self.bot.say("Unexpected exception: {} when editing {}".format(result, valid_roles[index]))

        await self.bot.say("Role colors updated.") 
Example #21
Source File: crprofile.py    From SML-Cogs with MIT License 5 votes vote down vote up
def random_discord_color():
    """Return random color as an integer."""
    color = ''.join([choice('0123456789ABCDEF') for x in range(6)])
    color = int(color, 16)
    return discord.Color(value=color) 
Example #22
Source File: funcs.py    From NotSoBot with MIT License 5 votes vote down vote up
def get_color(self):
		if self.color_count >= len(self.colors):
			self.color_count = 0
		color = self.colors[self.color_count]
		self.color_count += 1
		return getattr(discord.Color, color) 
Example #23
Source File: functions.py    From discord-roombot with GNU General Public License v3.0 5 votes vote down vote up
def get_default_colors():
    return [ c.value for c in [
        discord.Color.teal(),
        discord.Color.green(),
        discord.Color.blue(),
        discord.Color.purple(),
        discord.Color.magenta(),
        discord.Color.gold(),
        discord.Color.orange(),
        discord.Color.red()] ] 
Example #24
Source File: functions.py    From discord-roombot with GNU General Public License v3.0 5 votes vote down vote up
def get_color(color, return_default=True):
    hex_match = re.search('[0-9a-fA-F]{6}', color)
    if hex_match and hex_match.group():
        return discord.Color(int(hex_match.group(), 16))
    elif color in get_all_text('red'):
        return discord.Color.red()
    elif color in get_all_text('orange'):
        return discord.Color.orange()
    elif color in get_all_text('yellow'):
        return discord.Color.gold()
    elif color in get_all_text('green'):
        return discord.Color.green()
    elif color in get_all_text('teal'):
        return discord.Color.teal()
    elif color in get_all_text('blue'):
        return discord.Color.blue()
    elif color in get_all_text('purple'):
        return discord.Color.purple()
    elif color in get_all_text('pink'):
        return discord.Color.magenta()
    elif return_default:
        return discord.Color(some_color())
    else:
        return None



# other ============= 
Example #25
Source File: room.py    From discord-roombot with GNU General Public License v3.0 5 votes vote down vote up
def unpack_value(cls, value, default):
        v = value
        if isinstance(default, list) and isinstance(v, str):
            v = str_to_ids(v)
        elif isinstance(default, int) and not isinstance(v, int):
            try:
                v = int(v)
            except ValueError:
                v = -1
        elif isinstance(default, bool) and not isinstance(v, bool):
            v = bool(v)
        elif isinstance(default, discord.Color) and isinstance(v, discord.Color):
            v = v.value
        return v 
Example #26
Source File: room.py    From discord-roombot with GNU General Public License v3.0 5 votes vote down vote up
def pack_data(self):
        data = {}
        for (key, value) in self.props.items():
            s = self.__getattribute__(key)
            if s == None:
                s = value
            elif isinstance(value, list) and isinstance(s, list):
                s = ids_to_str(s)
            elif isinstance(value, int) and not isinstance(s, int):
                s = int(s)
            elif isinstance(value, discord.Color) and isinstance(s, discord.Color):
                s = s.value
            data[key] = s
        return data 
Example #27
Source File: backups.py    From xenon with GNU General Public License v3.0 5 votes vote down vote up
def _load_roles(self):
        log.debug(f"Loading roles on {self.guild.id}")
        existing_roles = list(reversed(list(filter(
            lambda r: not r.managed and not r.is_default()
                      and self.guild.me.top_role.position > r.position,
            self.guild.roles
        ))))
        for role in reversed(self.data["roles"]):
            try:
                if role["default"]:
                    await self.guild.default_role.edit(
                        permissions=discord.Permissions(role["permissions"])
                    )
                    new_role = self.guild.default_role
                else:
                    kwargs = {
                        "name": role["name"],
                        "hoist": role["hoist"],
                        "mentionable": role["mentionable"],
                        "color": discord.Color(role["color"]),
                        "permissions": discord.Permissions.none(),
                        "reason": self.reason
                    }

                    if len(existing_roles) == 0:
                        try:
                            new_role = await asyncio.wait_for(self.guild.create_role(**kwargs), 10)
                        except asyncio.TimeoutError:
                            # Probably hit the 24h rate limit. Just skip roles
                            break
                    else:
                        new_role = existing_roles.pop(0)
                        await new_role.edit(**kwargs)

                self.id_translator[role["id"]] = new_role.id
            except Exception:
                pass 
Example #28
Source File: embedwiz.py    From calebj-cogs with GNU General Public License v3.0 5 votes vote down vote up
def embedwiz(self, ctx, *, specification):
        """
        Posts an embed according to the given specification:

        title;color;footer;footer_icon;image;thumbnail;body

        All values can be seperated by newlines, spaces, or other whitespace.
        Only the first six semicolons are used, the rest are ignored. To
        use semicolons in any of the first six fields, escape it like so: \\;
        To include a backslash before a semicolon without escaping, do: \\\\;

        Color can be a #HEXVAL, "random", or a name that discord.Color knows.
        Options: https://discordpy.readthedocs.io/en/async/api.html#discord.Colour

        All URLs (footer_icon, image, thumbnail) can be empty or "none".

        Use a body of "prompt" to use your next message as the content.

        Timestamp must be an ISO8601 timestamp, UNIX timestamp or 'now'.
        An ISO8601 timestamp looks like this: 2017-12-11T01:15:03.449371-0500.

        Start the specification with -noauthor to skip the author header.
        Note: only mods, admins and the bot owner can edit authorless embeds.

        Keyword-based expressions can be built by starting it with '-kw'
        Each parameter above can be specified as param1=value1;param2=value2;...
        This method allows two more parameters: url and timestamp (see above).

        WARNING: embeds are hidden to anyone with 'link previews' disabled.
        """
        if ctx.invoked_subcommand is None:
            embed = await self._parse_embed(ctx, specification)
            if embed:
                await self.bot.say(embed=embed) 
Example #29
Source File: formatter.py    From xenon with GNU General Public License v3.0 5 votes vote down vote up
def embed_message(content=None, title=None, type=None):
    emb_title, content_format, icon, color = message_types.get(type) or message_types.get(None)
    title = title or emb_title
    embed = discord.Embed(color=discord.Color(color), description=content_format.format(c=content))
    embed.set_author(name=title, icon_url=icon)
    return {"embed": embed} 
Example #30
Source File: general.py    From MangoByte with MIT License 5 votes vote down vote up
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)