[Alignment] 1.0.0 Generate alignment charts based on chat history

- Generate an alignment chart randomly picked from previous members in the channel.
- Pick specific slots for who goes where in the alignment chart.
- Customize the display to fit your server's theme.
This commit is contained in:
TrustyJAID committed 2024-12-02 12:59:49 -07:00
1 parent ab2be496b7
commit daebffb196
6 files changed
+654 -1

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ TrustyJAID's Cogs for [Red-DiscordBot](https://github.com/Cog-Creators/Red-Disc
|-----------------|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
| AddImage | 1.3.5 | <details><summary>Add images for direct upload per guild and globally.</summary>Add image for the bot to directly upload similar to alias.</details> | TrustyJAID |
| AdventureAlert | 1.5.1 | <details><summary>Receive notifications from adventure activities!</summary>Receive notifications from adventure activities!</details> | TrustyJAID |
| Bingo | 1.0.0 | <details><summary>Play Bingo!</summary>Generate an alignment chart from users!</details> | TrustyJAID |
| Alignment | 1.0.0 | <details><summary>Create an alignment chart!</summary>Generate an alignment chart from users!</details> | TrustyJAID |
| APNGFilter | 1.0.1 | <details><summary>Automatically filter animated PNG's.</summary>Automatically filter animated PNG's.</details> | TrustyJAID, Sinbad, and Soulrift |
| Automod | 1.0.4 | <details><summary>Discord Automod</summary>A cog to interact with Discord Automod.</details> | TrustyJAID |
| Badges | 1.2.0 | <details><summary>Create your own badge!</summary>Create your own badge with your discord info.</details> | TrustyJAID |
+12
View File
@@ -0,0 +1,12 @@
import json
from pathlib import Path
from .alignment import Alignments
with open(Path(__file__).parent / "info.json") as fp:
__red_end_user_data_statement__ = json.load(fp)["end_user_data_statement"]
async def setup(bot):
cog = Alignments(bot)
await bot.add_cog(cog)
+437
View File
@@ -0,0 +1,437 @@
from __future__ import annotations
import asyncio
import functools
import random
import re
import textwrap
from io import BytesIO
from typing import Optional, Pattern
import aiohttp
import discord
from PIL import Image, ImageDraw, ImageFont
from red_commons.logging import getLogger
from redbot.core import Config, commands
from redbot.core.data_manager import bundled_data_path, cog_data_path
from .converter import Alignment, AlignmentFlags, GoodVsEvil, LawVsChaos
log = getLogger("red.trusty-cogs.alignment")
IMAGE_LINKS: Pattern = re.compile(
r"(https?:\/\/[^\"\'\s]*\.(?:png|jpg|jpeg)(\?size=[0-9]*)?)", flags=re.I
)
class Alignments(commands.Cog):
__version__ = "1.0.0"
__author__ = ["TrustyJAID"]
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 218773382617890828)
self.config.register_guild(
stamp_colour="#e6d705",
text_colour="#FFF8E7",
textborder_colour="#333333",
background_colour="#010028",
box_colour="#FFF8E7",
watermark=None,
background_tile=None,
)
async def red_delete_data_for_user(self, **kwargs):
"""
Nothing to delete
"""
return
@commands.command(name="alignment")
@commands.guild_only()
@commands.bot_has_permissions(attach_files=True, read_message_history=True)
async def alignment(self, ctx: commands.Context, *, alignments: AlignmentFlags):
"""
Generate a Alignment Card
`alignments` - Who or what is the specific alignment?
- `lg:` Lawful Good.
- `ln:` Lawful Neutral.
- `le:` Lawful Evil.
- `ng:` Neutral Good.
- `nn:` Neutral Neutral.
- `ne:` Neutral Evil.
- `cg:` Chaotic Good.
- `cn:` Chaotic Neutral.
- `ce:` Chaotic Evil.
"""
msg = None
log.debug(alignments)
# perm = self.nth_permutation(ctx.author.id, 24, tiles)
users = set()
alignments = await alignments.to_table()
empty_alignments = []
existing_users = set()
for al, slot in alignments.items():
if slot["text"] is None:
empty_alignments.append(al)
if slot["user_id"]:
existing_users.add(slot["user_id"])
async for message in ctx.channel.history(limit=50):
if message.author not in users and message.author.id not in existing_users:
users.add(message.author)
if len(users) > 9:
break
for user in users:
if len(empty_alignments) < 1:
continue
al = empty_alignments.pop(empty_alignments.index(random.choice(empty_alignments)))
b = BytesIO()
await user.display_avatar.save(b)
image = Image.open(b).convert("RGBA")
alignments[al]["text"] = user.display_name
alignments[al]["image"] = image
card_settings = await self.get_card_options(ctx)
temp = await self.create_alignment_card(
alignments, guild_name=ctx.guild.name, **card_settings
)
await ctx.send(
content=msg,
file=temp,
allowed_mentions=discord.AllowedMentions(users=False),
)
async def get_card_options(self, ctx: commands.Context) -> dict:
ret = {
"background_colour": await self.config.guild(ctx.guild).background_colour(),
"text_colour": await self.config.guild(ctx.guild).text_colour(),
"textborder_colour": await self.config.guild(ctx.guild).textborder_colour(),
"box_colour": await self.config.guild(ctx.guild).box_colour(),
}
if watermark := await self.config.guild(ctx.guild).watermark():
ret["watermark"] = Image.open(cog_data_path(self) / watermark)
if background_tile := await self.config.guild(ctx.guild).background_tile():
ret["background_tile"] = Image.open(cog_data_path(self) / background_tile)
return ret
@commands.group(name="alignmentset")
@commands.mod_or_permissions(manage_messages=True)
@commands.guild_only()
async def alignmentset(self, ctx: commands.Context):
"""
Commands for setting alignment settings
"""
pass
@alignmentset.command(name="text")
async def alignmentset_text(
self, ctx: commands.Context, colour: Optional[discord.Colour] = None
):
"""
Set the colour of the text.
`colour` - must be a hex colour code
"""
if colour is None:
await self.config.guild(ctx.guild).text_colour.clear()
else:
await self.config.guild(ctx.guild).text_colour.set(str(colour))
colour = await self.config.guild(ctx.guild).text_colour()
await ctx.send(f"The Alignment card text colour has been set to {colour}")
@alignmentset.command(name="textborder")
async def alignmentset_textborder(
self, ctx: commands.Context, colour: Optional[discord.Colour] = None
):
"""
Set the colour of the text border.
`colour` - must be a hex colour code
"""
if colour is None:
await self.config.guild(ctx.guild).textborder_colour.clear()
else:
await self.config.guild(ctx.guild).textborder_colour.set(str(colour))
colour = await self.config.guild(ctx.guild).textborder_colour()
await ctx.send(f"The Alignment card text border colour has been set to {colour}")
@alignmentset.command(name="background")
async def alignmentset_background(
self, ctx: commands.Context, colour: Optional[discord.Colour] = None
):
"""
Set the colour of the Alignment card background.
`colour` - must be a hex colour code
"""
if colour is None:
await self.config.guild(ctx.guild).background_colour.clear()
else:
await self.config.guild(ctx.guild).background_colour.set(str(colour))
colour = await self.config.guild(ctx.guild).background_colour()
await ctx.send(f"The Alignment card background has been set to {colour}.")
@alignmentset.command(name="box")
async def alignmentset_box(
self, ctx: commands.Context, colour: Optional[discord.Colour] = None
):
"""
Set the colour of the Alignment card boxes border.
`colour` - must be a hex colour code
"""
if colour is None:
await self.config.guild(ctx.guild).box_colour.clear()
else:
await self.config.guild(ctx.guild).box_colour.set(str(colour))
colour = await self.config.guild(ctx.guild).box_colour()
await ctx.send(f"The Alignment card box colour has been set to {colour}")
@alignmentset.command(name="watermark")
async def alignmentset_watermark(self, ctx: commands.Context, image_url: Optional[str] = None):
"""
Add a watermark image to the alignment card
`[image_url]` - Must be an image url with `.jpg` or `.png` extension.
"""
if image_url is None and not ctx.message.attachments:
await ctx.send("I have cleared the alignment watermark.")
await self.config.guild(ctx.guild).watermark.clear()
return
elif image_url is None and ctx.message.attachments:
image = ctx.message.attachments[0]
ext = image.filename.split(".")[-1]
filename = f"{ctx.guild.id}-watermark.{ext}"
await image.save(cog_data_path(self) / filename)
await self.config.guild(ctx.guild).watermark.set(filename)
await ctx.send("Saved the image as a watermark.")
else:
if not IMAGE_LINKS.search(image_url):
await ctx.send("That is not a valid image URL. It must be either jpg or png.")
return
async with aiohttp.ClientSession() as session:
async with session.get(image_url) as resp:
data = await resp.read()
ext = image_url.split(".")[-1]
filename = f"{ctx.guild.id}-watermark.{ext}"
with open(cog_data_path(self) / filename, "wb") as outfile:
outfile.write(data)
await self.config.guild(ctx.guild).watermark.set(filename)
await ctx.send("Saved the image as a watermark.")
@alignmentset.command(name="bgtile")
async def alignmentset_bgtile(self, ctx: commands.Context, image_url: Optional[str] = None):
"""
Set the background image (tiled).
This will override the background colour if set as it will attempt
to tile the image over the entire background.
`[image_url]` - Must be an image url with `.jpg` or `.png` extension.
"""
if image_url is None and not ctx.message.attachments:
await ctx.send("I have cleared the alignment background image.")
await self.config.guild(ctx.guild).background_tile.clear()
return
elif image_url is None and ctx.message.attachments:
image = ctx.message.attachments[0]
ext = image.filename.split(".")[-1]
filename = f"{ctx.guild.id}-bgtile.{ext}"
await image.save(cog_data_path(self) / filename)
await self.config.guild(ctx.guild).background_tile.set(filename)
await ctx.send("Saved the image as an background tile.")
else:
if not IMAGE_LINKS.search(image_url):
await ctx.send("That is not a valid image URL. It must be either jpg or png.")
return
async with aiohttp.ClientSession() as session:
async with session.get(image_url) as resp:
data = await resp.read()
ext = image_url.split(".")[-1]
filename = f"{ctx.guild.id}-bgtile.{ext}"
with open(cog_data_path(self) / filename, "wb") as outfile:
outfile.write(data)
await self.config.guild(ctx.guild).background_tile.set(filename)
await ctx.send("Saved the image as the background tile.")
@alignmentset.command(name="settings")
async def alignmentset_settings(self, ctx: commands.Context):
"""
Show the current alignment card settings
"""
settings = await self.get_card_options(ctx)
msg = ""
for k, v in settings.items():
if k == "watermark":
v = await self.config.guild(ctx.guild).watermark()
name = k.split("_")[0]
msg += f"{name.title()}: `{v}`\n"
await ctx.maybe_send_embed(msg)
async def create_alignment_card(
self,
tiles: dict,
guild_name: str,
background_colour: str,
text_colour: str,
textborder_colour: str,
box_colour: str,
watermark: Optional[Image.Image] = None,
background_tile: Optional[Image.Image] = None,
) -> Optional[discord.File]:
task = functools.partial(
self._create_alignment_card,
options=tiles,
guild_name=guild_name,
background_colour=background_colour,
text_colour=text_colour,
textborder_colour=textborder_colour,
box_colour=box_colour,
watermark=watermark,
background_tile=background_tile,
)
loop = asyncio.get_running_loop()
task = loop.run_in_executor(None, task)
try:
return await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
log.error("There was an error generating the alignment card")
return None
def _create_alignment_card(
self,
options: dict,
guild_name: str,
background_colour: str,
text_colour: str,
textborder_colour: str,
box_colour: str,
watermark: Optional[Image.Image] = None,
background_tile: Optional[Image.Image] = None,
):
base_height, base_width = 650, 570
base = Image.new("RGBA", (base_width, base_height), color=background_colour)
draw = ImageDraw.Draw(base)
if background_tile:
# https://stackoverflow.com/a/69807463
bg_x, bg_y = background_tile.size
for i in range(0, base_width, bg_x):
for j in range(0, base_height, bg_y):
base.paste(background_tile, (i, j))
font_path = str(bundled_data_path(self) / "SourceSansPro-SemiBold.ttf")
font = ImageFont.truetype(font=font_path, size=180)
font2 = ImageFont.truetype(font=font_path, size=20)
font3 = ImageFont.truetype(font=font_path, size=30)
credit_font = ImageFont.truetype(font=font_path, size=10)
draw.text(
(545, 615),
f"Alignment Cog written by @trustyjaid\nAlignment card colours and images provided by {guild_name} moderators",
fill=text_colour,
stroke_width=1,
align="right",
stroke_fill=textborder_colour,
anchor="rs",
font=credit_font,
)
if watermark is not None:
watermark = watermark.convert("RGBA")
# https://stackoverflow.com/a/72983761
wm = watermark.copy()
wm.putalpha(128)
watermark.paste(wm, watermark)
watermark.thumbnail(
(int(base.size[0] * 0.75), int(base.size[1] * 0.75)), Image.LANCZOS
)
# watermark.putalpha(128)
# https://stackoverflow.com/a/56868633
x1 = int(0.5 * base.size[0]) - int(0.5 * watermark.size[0])
y1 = int(0.5 * base.size[1]) - int(0.5 * watermark.size[1])
x2 = int(0.5 * base.size[0]) + int(0.5 * watermark.size[0])
y2 = int(0.5 * base.size[1]) + int(0.5 * watermark.size[1])
base.alpha_composite(watermark, (x1, y1))
draw.text(
(285, 50),
f"{guild_name} Alignment Chart",
fill=text_colour,
stroke_width=1,
stroke_fill=textborder_colour,
anchor="ms",
font=font3,
)
count = 0
for x in range(4):
# Lawful/Chaotic
for y in range(4):
# Good/Evil
scale = 130
x0 = 25 + (scale * x)
x1 = x0 + scale
y0 = 75 + (scale * y)
y1 = y0 + scale
try:
if y == 0:
align = LawVsChaos(x - 1)
elif x == 0:
align = GoodVsEvil(y - 1)
else:
align = Alignment(LawVsChaos(x - 1), GoodVsEvil(y - 1))
except ValueError:
align = "Alignment"
pass
bg_img = None
table_input = {}
if x == 0 or y == 0:
text = str(align)
else:
try:
key = getattr(align, "short", None)
table_input = options.get(key, None)
if table_input is not None:
text = table_input["text"]
bg_img = table_input["image"]
else:
text = ""
except (IndexError, AttributeError):
text = ""
count += 1
log.debug(f"{text=}")
if bg_img and table_input:
log.info("Adding avatar background")
bg_img = bg_img.resize((130, 130), Image.LANCZOS)
bg_img.putalpha(128)
base.paste(bg_img, (x0, y0, x1, y1))
draw.rectangle((x0, y0, x1, y1), outline=box_colour)
if text is None:
text = ""
if len(text) > 60:
text = text[:57] + "..."
lines = textwrap.wrap(text, width=13)
font_height = font2.getbbox(text)[3] - font2.getbbox(text)[1]
text_x = x0 + int(scale / 2)
if len(lines) > 1:
text_y = y0 + (int(scale / 2) - ((len(lines) / 3) * font_height))
else:
text_y = y0 + (int(scale / 2))
for line in lines:
draw.text(
(text_x, text_y),
line,
fill=text_colour,
stroke_width=1,
stroke_fill=textborder_colour,
anchor="ms",
font=font2,
)
text_y += font_height
temp = BytesIO()
base.save(temp, format="webp", optimize=True)
temp.seek(0)
return discord.File(temp, filename="alignment.webp")
+172
View File
@@ -0,0 +1,172 @@
from __future__ import annotations
from enum import Enum
from io import BytesIO
from typing import List, Optional, Tuple, Union
import discord
from PIL import Image
from redbot.core import commands
class LawVsChaos(Enum):
lawful = 0
neutral = 1
chaotic = 2
def __str__(self) -> str:
return self.name.title()
@property
def short(self) -> str:
return self.name[0]
@classmethod
def from_name(cls, name: str) -> LawVsChaos:
for i in cls:
if i.name == name.lower():
return i
raise ValueError
class GoodVsEvil(Enum):
good = 0
neutral = 1
evil = 2
def __str__(self) -> str:
return self.name.title()
@property
def short(self) -> str:
return self.name[0]
@classmethod
def from_name(cls, name: str) -> GoodVsEvil:
for i in cls:
if i.name == name.lower():
return i
raise ValueError
class Alignment:
def __init__(self, law: LawVsChaos, good: GoodVsEvil):
self.lawful = law
self.good = good
@property
def idx(self) -> Tuple[int, int]:
return (self.lawful.value, self.good.value)
@property
def short(self) -> str:
return f"{self.lawful.short}{self.good.short}"
def __str__(self) -> str:
return f"{self.lawful} {self.good}"
def __eq__(self, other) -> bool:
if not isinstance(other, Alignment):
return False
return self.lawful is other.lawful and self.good is other.good
def __ne__(self, other) -> bool:
return not self.__eq__(other)
@classmethod
def from_name(cls, name: str) -> Alignment:
lawful, good = name.split("_")
return cls(LawVsChaos.from_name(lawful), GoodVsEvil.from_name(good))
class Stamp:
async def convert(self, ctx: commands.Context, argument: str) -> List[int]:
if len(argument) > 2:
raise commands.BadArgument("Your stamp must be 2 characters max.")
y = int(argument[1]) - 1
bingo = await ctx.cog.config.guild(ctx.guild).bingo()
try:
x = bingo.index(argument[0].upper())
except ValueError:
raise commands.BadArgument(
f"`{argument[0].upper()}` is not a valid letter in {bingo}."
)
return [x, y]
class AlignmentFlags(discord.ext.commands.FlagConverter, case_insensitive=True):
lawful_good: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="lawful_good",
aliases=["lg", "lawfulgood"],
default=None,
description="Who or what is Lawful Good?",
)
lawful_neutral: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="lawful_neutral",
aliases=["ln", "lawfulneutral"],
default=None,
description="Who or what is Lawful Neutral?",
)
lawful_evil: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="lawful_evil",
aliases=["le", "lawfulevil"],
default=None,
description="Who or what is Lawful Evil?",
)
neutral_good: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="neutral_good",
aliases=["ng", "neutralgood"],
default=None,
description="Who or what is Neutral Good?",
)
neutral_neutral: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="neutral_neutral",
aliases=["nn", "neutralneutral"],
default=None,
description="Who or what is Neutral Neutral?",
)
neutral_evil: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="neutral_evil",
aliases=["ne", "neutralevil"],
default=None,
description="Who or what is Neutral Evil?",
)
chaotic_good: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="chaotic_good",
aliases=["cg", "chaoticgood"],
default=None,
description="Who or what is Chaotic Good?",
)
chaotic_neutral: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="chaotic_neutral",
aliases=["cn", "chaoticneutral"],
default=None,
description="Who or what is Chaotic Neutral?",
)
chaotic_evil: Optional[Union[discord.Member, str]] = discord.ext.commands.flag(
name="chaotic_evil",
aliases=["ce", "chaoticevil"],
default=None,
description="Who or what is Chaotic Evil?",
)
async def to_table(self):
table = {}
for alignment in self:
align = Alignment.from_name(alignment[0])
table[align.short] = {"text": None, "image": None, "user_id": None}
if alignment[1] is None:
continue
if isinstance(alignment[1], discord.Member):
b = BytesIO()
await alignment[1].display_avatar.save(b)
image = Image.open(b).convert("RGBA")
table[align.short]["text"] = alignment[1].display_name
table[align.short]["image"] = image
table[align.short]["user_id"] = alignment[1].id
else:
table[align.short]["text"] = str(alignment[1])
return table
Binary file not shown.
+32
View File
@@ -0,0 +1,32 @@
{
"author": [
"TrustyJAID"
],
"description": "Generate an alignment chart from users!",
"disabled": false,
"end_user_data_statement": "This cog does not persistently store data or metadata about users. This cog can store images uploaded by the user or provided for the purpose of generating alignment charts.",
"hidden": false,
"install_msg": "This cog contains a data folder with a single font and can download and store images for watermarks and icons for alignment charts.",
"max_bot_version": "0.0.0",
"min_bot_version": "3.5.0",
"min_python_version": [
3,
7,
2
],
"name": "Alignment",
"permissions": [
"attach_files"
],
"required_cogs": {},
"requirements": [
"pillow"
],
"short": "Create an alignment chart!",
"tags": [
"fun",
"memes",
"meme"
],
"type": "COG"
}