From 5dd873d683b71f40f47b80ec8f75f6468228c2d3 Mon Sep 17 00:00:00 2001 From: kku Date: Tue, 31 Dec 2024 11:07:24 +0100 Subject: [PATCH] Closes #61 --- src/libbot/pycord/utils/__init__.py | 1 + src/libbot/pycord/utils/color.py | 35 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 src/libbot/pycord/utils/__init__.py create mode 100644 src/libbot/pycord/utils/color.py diff --git a/src/libbot/pycord/utils/__init__.py b/src/libbot/pycord/utils/__init__.py new file mode 100644 index 0000000..a2b41be --- /dev/null +++ b/src/libbot/pycord/utils/__init__.py @@ -0,0 +1 @@ +from .color import color_from_hex, hex_from_color diff --git a/src/libbot/pycord/utils/color.py b/src/libbot/pycord/utils/color.py new file mode 100644 index 0000000..9b61282 --- /dev/null +++ b/src/libbot/pycord/utils/color.py @@ -0,0 +1,35 @@ +from discord import Colour + + +def _int_from_hex(hex_string: str) -> int: + try: + return int(hex_string, base=16) + except Exception as exc: + raise ValueError("Input string must be a valid HEX code.") from exc + + +def _hex_from_int(color_int: int) -> str: + if not 0 <= color_int <= 0xFFFFFF: + raise ValueError("Color's value must be in the range 0 to 0xFFFFFF.") + + return f"#{color_int:06x}" + + +def color_from_hex(hex_string: str) -> Colour: + """Convert valid hexadecimal string to discord.Colour. + + :param hex_string: Hexadecimal string to convert into Colour object + :type hex_string: str + :return: Colour object + """ + return Colour(_int_from_hex(hex_string)) + + +def hex_from_color(color: Colour) -> str: + """Convert discord.Colour to hexadecimal string. + + :param color: Colour object to convert into the string + :type color: Colour + :return: Hexadecimal string in #XXXXXX format + """ + return _hex_from_int(color.value)