Skip to content

Commit

Permalink
Add guild role color command.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sachaa-Thanasius committed Apr 7, 2024
1 parent c6ef292 commit f7842e2
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 4 deletions.
67 changes: 64 additions & 3 deletions exts/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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```")
)

Expand All @@ -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."""
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit f7842e2

Please sign in to comment.