welcome: aurora welcome/goodbye cards
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
5adcf3478e
commit
1b074d4b58
9 files changed
+276
No files matched your search
@@ -151,6 +151,8 @@ CATEGORIES: dict[str, tuple[str, str, str, str]] = {
|
||||
"playing Strinova, updated every 10 minutes.\n\n"
|
||||
"**Member count** — a channel name that shows how many members the server has, "
|
||||
"updated every 10 minutes.\n\n"
|
||||
"**Welcome & goodbye cards** — I post a card when someone joins the server, "
|
||||
"and a black & white one when someone leaves.\n\n"
|
||||
"**Custom roles** — in the roles channel, press *Get my role* and I'll DM you "
|
||||
"to make your own colored role.\n\n"
|
||||
"**Website** — the PC's live stats are shown on https://esefos.netlify.app"
|
||||
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
cogs/welcome.py
|
||||
─────────────────────────────────────────────────────────────────────────────
|
||||
Welcome / goodbye cards.
|
||||
|
||||
• When someone joins, posts an "Aurora" card in WELCOME_CHANNEL_ID: their
|
||||
avatar blurred into the background, the avatar itself in a ring on the left,
|
||||
and their name + join date beside it. The new member is pinged.
|
||||
• When someone leaves, posts the same card in black & white with how long
|
||||
they were here. No ping.
|
||||
• Bots are skipped, and only joins/leaves of the channel's own server count.
|
||||
• Fonts: Inter (SIL OFL), bundled in welcome_asset/fonts.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont, ImageOps
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
FONT_DIR = Path(__file__).parent.parent / "welcome_asset" / "fonts"
|
||||
W, H = 1200, 400
|
||||
SS = 2 # draw at 2x and downscale for smooth edges
|
||||
|
||||
|
||||
def _font(weight: str, size: int) -> ImageFont.FreeTypeFont:
|
||||
return ImageFont.truetype(str(FONT_DIR / f"Inter-{weight}.ttf"), size * SS)
|
||||
|
||||
|
||||
def _renderable(text: str) -> bool:
|
||||
"""True if Inter has a glyph for every character (no tofu boxes)."""
|
||||
f = _font("Bold", 20)
|
||||
|
||||
def glyph(c: str) -> bytes:
|
||||
img = Image.new("L", (100, 100))
|
||||
ImageDraw.Draw(img).text((10, 10), c, font=f, fill=255)
|
||||
return img.tobytes()
|
||||
|
||||
tofu = glyph("")
|
||||
return all(c.isspace() or glyph(c) != tofu for c in text)
|
||||
|
||||
|
||||
def _fit_font(draw: ImageDraw.ImageDraw, text: str, weight: str, size: int, max_w: int):
|
||||
while size > 20:
|
||||
f = _font(weight, size)
|
||||
if draw.textlength(text, font=f) <= max_w * SS:
|
||||
return f
|
||||
size -= 2
|
||||
return _font(weight, size)
|
||||
|
||||
|
||||
def _tracked(draw: ImageDraw.ImageDraw, xy, text: str, f, fill, tracking: int) -> None:
|
||||
"""Draw text with letter-spacing (tracking in px at 1x)."""
|
||||
x, y = xy
|
||||
for ch in text:
|
||||
draw.text((x, y), ch, font=f, fill=fill)
|
||||
x += draw.textlength(ch, font=f) + tracking * SS
|
||||
|
||||
|
||||
def _circle(img: Image.Image, d: int) -> Image.Image:
|
||||
img = ImageOps.fit(img, (d, d), Image.LANCZOS)
|
||||
mask = Image.new("L", (d, d), 0)
|
||||
ImageDraw.Draw(mask).ellipse((0, 0, d - 1, d - 1), fill=255)
|
||||
out = Image.new("RGBA", (d, d))
|
||||
out.paste(img, (0, 0), mask)
|
||||
return out
|
||||
|
||||
|
||||
def render_card(avatar: bytes, name: str, label: str, line1: str, line2: str, leaving: bool) -> io.BytesIO:
|
||||
"""Render the Aurora card; goodbye cards are greyscale."""
|
||||
av = Image.open(io.BytesIO(avatar)).convert("RGBA")
|
||||
cw, ch = W * SS, H * SS
|
||||
|
||||
bg = ImageOps.fit(av.convert("RGB"), (cw, ch), Image.LANCZOS, centering=(0.5, 0.35))
|
||||
bg = bg.filter(ImageFilter.GaussianBlur(60 * SS))
|
||||
bg = ImageEnhance.Color(bg).enhance(1.8)
|
||||
bg = ImageEnhance.Brightness(bg).enhance(0.5)
|
||||
canvas = bg.convert("RGBA")
|
||||
# soft left-to-right darkening so the text stays readable
|
||||
shade = Image.linear_gradient("L").rotate(90).resize((cw, ch))
|
||||
canvas = Image.composite(Image.new("RGBA", (cw, ch), (0, 0, 0, 255)), canvas, shade.point(lambda v: v * 0.35))
|
||||
d = ImageDraw.Draw(canvas)
|
||||
|
||||
ad = 220 * SS
|
||||
ax, ay = 90 * SS, (ch - ad) // 2
|
||||
ring = 6 * SS
|
||||
d.ellipse((ax - ring, ay - ring, ax + ad + ring, ay + ad + ring), fill=(255, 255, 255, 230))
|
||||
canvas.alpha_composite(_circle(av, ad), (ax, ay))
|
||||
|
||||
tx = ax + ad + 70 * SS
|
||||
max_w = W - tx // SS - 70
|
||||
_tracked(d, (tx, 92 * SS), label, _font("SemiBold", 22), (255, 255, 255, 170), 8)
|
||||
d.text((tx, 130 * SS), name, font=_fit_font(d, name, "Bold", 76, max_w), fill=(255, 255, 255))
|
||||
d.text((tx, 238 * SS), line1, font=_fit_font(d, line1, "Regular", 28, max_w), fill=(255, 255, 255, 215))
|
||||
d.text((tx, 282 * SS), line2, font=_font("Light", 24), fill=(255, 255, 255, 150))
|
||||
|
||||
if leaving:
|
||||
canvas = ImageOps.grayscale(canvas.convert("RGB")).convert("RGBA")
|
||||
|
||||
card = canvas.resize((W, H), Image.LANCZOS)
|
||||
mask = Image.new("L", (W, H), 0)
|
||||
ImageDraw.Draw(mask).rounded_rectangle((0, 0, W, H), 28, fill=255)
|
||||
card.putalpha(mask)
|
||||
|
||||
buf = io.BytesIO()
|
||||
card.save(buf, "PNG")
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def _stayed(joined: datetime | None) -> str:
|
||||
"""'Was here for 4 months' style duration."""
|
||||
if joined is None:
|
||||
return ""
|
||||
secs = (datetime.now(timezone.utc) - joined).total_seconds()
|
||||
for unit, size in (("year", 365 * 86400), ("month", 30 * 86400), ("day", 86400),
|
||||
("hour", 3600), ("minute", 60)):
|
||||
n = int(secs // size)
|
||||
if n >= 1:
|
||||
return f"Was here for {n} {unit}{'s' if n != 1 else ''}"
|
||||
return "Was here for less than a minute"
|
||||
|
||||
|
||||
class Welcome(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
val = os.getenv("WELCOME_CHANNEL_ID", "")
|
||||
self.channel_id = int(val) if val.isdigit() else None
|
||||
|
||||
def _channel(self, guild: discord.Guild) -> discord.TextChannel | None:
|
||||
if self.channel_id is None:
|
||||
return None
|
||||
channel = self.bot.get_channel(self.channel_id)
|
||||
return channel if channel and channel.guild.id == guild.id else None
|
||||
|
||||
def _display(self, member: discord.Member) -> str:
|
||||
name = member.display_name
|
||||
return name if _renderable(name) else member.name
|
||||
|
||||
async def _post(self, member, channel, label, line1, line2, leaving, content):
|
||||
try:
|
||||
avatar = await member.display_avatar.replace(size=512, format="png").read()
|
||||
img = await asyncio.to_thread(
|
||||
render_card, avatar, self._display(member), label, line1, line2, leaving)
|
||||
await channel.send(
|
||||
content,
|
||||
file=discord.File(img, filename="goodbye.png" if leaving else "welcome.png"),
|
||||
allowed_mentions=discord.AllowedMentions(users=True),
|
||||
)
|
||||
except Exception:
|
||||
log.exception("welcome card failed for %s", member)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_member_join(self, member: discord.Member):
|
||||
channel = self._channel(member.guild)
|
||||
if member.bot or channel is None:
|
||||
return
|
||||
joined = member.joined_at or datetime.now(timezone.utc)
|
||||
await self._post(member, channel, "WELCOME", f"Welcome to {member.guild.name}",
|
||||
f"Joined {joined:%b} {joined.day}, {joined.year}", False, member.mention)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_member_remove(self, member: discord.Member):
|
||||
channel = self._channel(member.guild)
|
||||
if member.bot or channel is None:
|
||||
return
|
||||
await self._post(member, channel, "GOODBYE", f"Left {member.guild.name}",
|
||||
_stayed(member.joined_at), True, None)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(Welcome(bot))
|
||||
@@ -19,6 +19,8 @@ STRINOVA_STAT_CHANNEL_ID="yo strinova stat channel here"
|
||||
STRINOVA_STAT_CHANNEL_ID_MAO="yo strinova stat channel here for mao server"
|
||||
#member count voice channel
|
||||
MEMBER_COUNT_CHANNEL_ID="yo member count channel here"
|
||||
#welcome / goodbye cards channel
|
||||
WELCOME_CHANNEL_ID="yo welcome channel here"
|
||||
|
||||
#me (for purging and other owner only things)
|
||||
OWNER_ID="your discord servers owner id here"
|
||||
|
||||
@@ -54,6 +54,7 @@ async def main():
|
||||
await bot.load_extension('cogs.sysinfo')
|
||||
await bot.load_extension('music.music_wrapper')
|
||||
await bot.load_extension('cogs.statchannel')
|
||||
await bot.load_extension('cogs.welcome')
|
||||
await bot.load_extension('cogs.ffmpeg_things')
|
||||
await bot.load_extension('cogs.roles')
|
||||
await bot.load_extension('cogs.gitpull')
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,92 @@
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Reference in new issue
Block a user