From f7842e27fe49be2c6447ae717a68be91cd3f395a Mon Sep 17 00:00:00 2001 From: Thanos <111999343+Sachaa-Thanasius@users.noreply.github.com> Date: Sun, 7 Apr 2024 10:15:41 -0400 Subject: [PATCH] Add guild role color command. --- exts/misc.py | 67 +++++++++++++++++++++++++++++++++++++++++++++--- requirements.txt | 3 ++- 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/exts/misc.py b/exts/misc.py index 49a625d..8aecef6 100644 --- a/exts/misc.py +++ b/exts/misc.py @@ -6,12 +6,18 @@ from __future__ import annotations +import asyncio +import colorsys import logging +import math import random import re -from io import StringIO +import tempfile +from io import BytesIO, StringIO import discord +import openpyxl +import openpyxl.styles from discord import app_commands from discord.ext import commands @@ -79,6 +85,45 @@ async def context_menu_meowify(interaction: core.Interaction, message: discord.M await interaction.response.send_message(meowify_text(message.content), ephemeral=True) +def color_step(r: int, g: int, b: int, repetitions: int = 1) -> tuple[int, int, int]: + """Sorting algorithm for colors.""" + + lum = math.sqrt(0.241 * r + 0.691 * g + 0.068 * b) + h, _, v = colorsys.rgb_to_hsv(r, g, b) + h2 = int(h * repetitions) + lum2 = int(lum * repetitions) + v2 = int(v * repetitions) + if h2 % 2 == 1: + v2 = repetitions - v2 + lum = repetitions - lum + return (h2, lum2, v2) + + +def process_color_data(role_data: list[tuple[str, discord.Colour]]) -> BytesIO: + """Sort colors, format them in an excel sheet, and return that sheet as a bytes stream.""" + + headers = ["Role Name", "Role Color (Hex)"] + workbook = openpyxl.Workbook() + sheet = workbook.active + sheet.append(headers) # type: ignore + for i, (name, colour) in enumerate(role_data, start=2): + color_value = colour.value + str_hex = f"{color_value:#08x}".removeprefix("0x") + sheet.append([name, str_hex]) # type: ignore + if color_value != 0: + sheet[f"A{i}"].fill = openpyxl.styles.PatternFill(fill_type="solid", start_color=str_hex) # type: ignore + + ft = openpyxl.styles.Font(bold=True) + for row in sheet["A1:C1"]: # type: ignore + for cell in row: # type: ignore + cell.font = ft + + with tempfile.NamedTemporaryFile() as tmp: + workbook.save(tmp) + tmp.seek(0) + return BytesIO(tmp.read()) + + class MiscCog(commands.Cog, name="Misc"): """A cog with some basic commands, originally used for testing slash and hybrid command functionality.""" @@ -195,10 +240,10 @@ async def ping_(self, ctx: core.Context) -> None: discord.Embed(title="Pong! \N{TABLE TENNIS PADDLE AND BALL}") .add_field(name="Websocket", value=f"```json\n{ws_ping:.2f} ms\n```") .add_field(name="Typing", value=f"```json\n{typing_ping:.2f} ms\n```") - .add_field(name="\u200B", value="\u200B") + .add_field(name="\u200b", value="\u200b") .add_field(name="Database", value=f"```json\n{db_ping:.2f} ms\n```") .add_field(name="Message", value=f"```json\n{msg_ping:.2f} ms\n```") - .add_field(name="\u200B", value="\u200B") + .add_field(name="\u200b", value="\u200b") .add_field(name="Average", value=f"```json\n{(ws_ping + typing_ping + db_ping + msg_ping) / 4:.2f} ms\n```") ) @@ -223,6 +268,22 @@ async def meowify(self, ctx: core.Context, *, text: str) -> None: else: await ctx.reply(meowify_text(text), ephemeral=True) + @commands.guild_only() + @commands.hybrid_command() + async def role_excel(self, ctx: core.GuildContext, by_color: bool = False) -> None: + def color_key(item: tuple[str, discord.Colour]) -> tuple[int, int, int]: + r, g, b = item[1].to_rgb() + return color_step(r, g, b, 8) + + needed_role_data = [(role.name, role.colour) for role in reversed(ctx.guild.roles)] + if by_color: + needed_role_data.sort(key=color_key) + + processed_data = await asyncio.to_thread(process_color_data, needed_role_data) + + disc_file = discord.File(processed_data, f"{ctx.guild.name}-roles-sheet.xlsx") + await ctx.send("Created Excel sheet with roles.", file=disc_file) + async def setup(bot: core.Beira) -> None: """Connects cog to bot.""" diff --git a/requirements.txt b/requirements.txt index 80f9410..67812c2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -10,9 +10,10 @@ fichub-api @ https://github.com/Sachaa-Thanasius/fichub-api/releases/download/v0 importlib_resources; python_version < "3.12" jishaku @ git+https://github.com/Gorialis/jishaku@a6661e2813124fbfe53326913e54f7c91e5d0dec lxml>=4.9.3 -types-lxml msgspec[toml] +openpyxl Pillow>=10.0.0 +types-lxml wavelink>=3.0.0 # To be used later: