Skip to content

Commit

Permalink
[Colour] Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Kreusada committed Mar 24, 2024
1 parent ef63a04 commit 5929a12
Show file tree
Hide file tree
Showing 4 changed files with 210 additions and 0 deletions.
68 changes: 68 additions & 0 deletions colour/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
.. _colour:

======
Colour
======

This is the cog guide for the 'Colour' cog. This guide
contains the collection of commands which you can use in the cog.

Through this guide, ``[p]`` will always represent your prefix. Replace
``[p]`` with your own prefix when you use these commands in Discord.

.. note::

This guide was last updated for version 1.1.0. Ensure
that you are up to date by running ``[p]cog update colour``.

If there is something missing, or something that needs improving
in this documentation, feel free to create an issue `here <https://github.com/Kreusada/Kreusada-Cogs/issues>`_.

This documentation is auto-generated everytime this cog receives an update.

--------------
About this cog
--------------

View information about colours.

--------
Commands
--------

Here are all the commands included in this cog (1):

* ``[p]colour <colour>``
View information about a colour.

------------
Installation
------------

If you haven't added my repo before, lets add it first. We'll call it
"kreusada-cogs" here.

.. code-block:: ini
[p]repo add kreusada-cogs https://github.com/Kreusada/Kreusada-Cogs
Now, we can install Colour.

.. code-block:: ini
[p]cog install kreusada-cogs colour
Once it's installed, it is not loaded by default. Load it by running the following
command:

.. code-block:: ini
[p]load colour
---------------
Further Support
---------------

For more support, head over to the `cog support server <https://discord.gg/GET4DVk>`_,
I have my own channel over there at #support_kreusada-cogs. Feel free to join my
`personal server <https://discord.gg/JmCFyq7>`_ whilst you're here.
9 changes: 9 additions & 0 deletions colour/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from redbot.core.utils import get_end_user_data_statement
from redbot.core.bot import Red
from .colour import Colour

__red_end_user_data_statement__ = get_end_user_data_statement(__file__)


async def setup(bot: Red):
await bot.add_cog(Colour(bot))
107 changes: 107 additions & 0 deletions colour/colour.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import aiohttp
import discord
import io
import re

from redbot.core import commands
from redbot.core.utils.chat_formatting import bold, inline
from PIL import Image, ImageDraw, ImageFont

HEX_CODE_RE = re.compile(r"#?[0-9a-fA-F]{6}\b")


class HexCodeConverter(commands.Converter):
async def convert(self, ctx: commands.Context, argument: str) -> discord.Colour:
argument = argument.lower()
if argument == "random":
return discord.Colour.random()
if not HEX_CODE_RE.match(argument):
raise commands.BadArgument(
f"Please provide a valid hex code (e.g. `{discord.Colour.random()}`). You may also state 'random' to get a random colour."
)
if argument[0] == "#":
argument = argument[1:]
return discord.Colour(int(argument, base=16))


class Colour(commands.Cog):
"""View information about a colour."""

__author__ = "Kreusada"
__version__ = "1.1.0"

def format_help_for_context(self, ctx: commands.Context) -> str:
context = super().format_help_for_context(ctx)
return f"{context}\n\nAuthor: {self.__author__}\nVersion: {self.__version__}"

async def red_delete_data_for_user(self, **kwargs):
return

@staticmethod
def generate_image(
*, colour: discord.Colour, name: str, constrast: discord.Colour
) -> io.BytesIO:
img = Image.new("RGB", (1500, 500), colour.to_rgb())
drawer = ImageDraw.Draw(img)
font = ImageFont.truetype("arial.ttf", 100)
drawer.text((10, 0), name, fill=constrast, font=font)
l, t, r, b = drawer.textbbox((10, 0), name, font=font)
cimg = img.crop([l - 10, t - 10, r + 10, b + 10])

buffer = io.BytesIO()
cimg.save(buffer, "png")
buffer.seek(0)
return buffer

@commands.command(aliases=["color"])
async def colour(self, ctx: commands.Context, colour: HexCodeConverter):
"""View information about a colour.
Provide a HEX code or "random".
"""
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://www.thecolorapi.com/id?hex={str(colour)[1:]}"
) as request:
data = await request.json()
if data["name"]["exact_match_name"]:
description = f"The provided colour is referred to as {bold(data['name']['value'])}.\n"
description += "This is an *exact* name match."
else:
description = f"The provided colour may be referred to as {bold(data['name']['value'])}.\n"
description += "This is not an *exact* name match, but is very similar to "
description += (
inline(data["name"]["closest_named_hex"])
+ ", the colour which is given this name."
)
embed = discord.Embed(
title=data["name"]["value"],
description=description,
colour=colour,
)

embed.add_field(name="Hex Code", value=data["hex"]["value"])
embed.add_field(name="RGB", value=data["rgb"]["value"])
embed.add_field(name="HSL", value=data["hsl"]["value"])
embed.add_field(name="HSV", value=data["hsv"]["value"])
embed.add_field(name="CMYK", value=data["cmyk"]["value"])
embed.add_field(name="XYZ", value=data["XYZ"]["value"])

writing_over = "\n\nWhen writing over {name}, it is visually clearer to use {choice} text, as shown in the image below.".format(
name=data["name"]["value"].lower(),
choice="(white/~~black~~)"
if str(data["contrast"]["value"]) == "#ffffff"
else "(~~white~~/black)",
)

embed.add_field(name="Writing over", value=writing_over, inline=False)

embed.set_thumbnail(url=data["image"]["bare"])
embed.set_image(url="attachment:https://image.png")
image = self.generate_image(
colour=colour,
name=data["name"]["value"].upper(),
constrast=int(data["contrast"]["value"][1:], base=16),
)

await ctx.send(embed=embed, file=discord.File(image, filename="image.png"))
26 changes: 26 additions & 0 deletions colour/info.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"author": [
"Kreusada"
],
"description": "View information about a colour.",
"disabled": false,
"end_user_data_statement": "This cog does not persistently store data or metadata about users.",
"hidden": false,
"install_msg": "Thanks for installing, have fun. Please refer to my docs if you need any help: https://kreusadacogs.readthedocs.io/en/latest/cog_colour.html",
"name": "Colour",
"required_cogs": {},
"requirements": [
"pillow"
],
"short": "View information about a colour.",
"tags": [
"Colour",
"Hex",
"RGB",
"HSL",
"HSV",
"CMYK",
"XYZ"
],
"type": "COG"
}

0 comments on commit 5929a12

Please sign in to comment.