412 lines
15 KiB
Python
Executable file
412 lines
15 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
"""Tuxothy — the daily question bot for `<Linux>` on WoW: Forever.
|
|
|
|
Posts one question a day in a terminal-mail block, slash commands gated
|
|
to the root role. Questions live in plain-text files under questions/,
|
|
one topic per file — `git pull` + /tux reload to add new ones.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import os
|
|
import random
|
|
import re
|
|
import sys
|
|
import textwrap
|
|
from pathlib import Path
|
|
from zoneinfo import ZoneInfo
|
|
|
|
import discord
|
|
from discord import app_commands
|
|
|
|
log = logging.getLogger("tux")
|
|
|
|
BASE = Path(__file__).resolve().parent
|
|
QUESTIONS_DIR = Path(os.environ.get("QUESTIONS_DIR", BASE / "questions"))
|
|
STATE_FILE = Path(os.environ.get("STATE_FILE", BASE / "state.json"))
|
|
ADMIN_ROLE = os.environ.get("ADMIN_ROLE", "root")
|
|
TIMEZONE = os.environ.get("QOTD_TZ", "America/New_York")
|
|
DEFAULT_TIME = os.environ.get("QOTD_TIME", "17:00")
|
|
GUILD_ID = int(os.environ.get("GUILD_ID", "0") or 0)
|
|
QOTD_CHANNEL = int(os.environ.get("QOTD_CHANNEL", "0") or 0)
|
|
|
|
VALUE_W = 35
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# question bank
|
|
|
|
|
|
def qid(topic: str, text: str) -> str:
|
|
return hashlib.sha1(f"{topic}\x1f{text}".encode()).hexdigest()[:12]
|
|
|
|
|
|
class Bank:
|
|
def __init__(self) -> None:
|
|
self.topics: dict[str, list[str]] = {}
|
|
|
|
def load(self) -> None:
|
|
self.topics = {}
|
|
for path in sorted(QUESTIONS_DIR.glob("*.txt")):
|
|
seen: set[str] = set()
|
|
items: list[str] = []
|
|
for line in path.read_text(encoding="utf-8").splitlines():
|
|
text = line.strip()
|
|
if not text or text.startswith("#"):
|
|
continue
|
|
key = text.lower()
|
|
if key in seen:
|
|
continue
|
|
seen.add(key)
|
|
items.append(text)
|
|
if items:
|
|
self.topics[path.stem] = items
|
|
log.info("bank loaded: %d topics, %d questions", len(self.topics), self.total())
|
|
|
|
def total(self) -> int:
|
|
return sum(len(v) for v in self.topics.values())
|
|
|
|
def pairs(self) -> list[tuple[str, str]]:
|
|
return [(t, q) for t, qs in self.topics.items() for q in qs]
|
|
|
|
def add(self, topic: str, text: str) -> tuple[str, int]:
|
|
slug = re.sub(r"[^a-z0-9-]", "-", topic.lower()).strip("-") or "fun"
|
|
path = QUESTIONS_DIR / f"{slug}.txt"
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
fresh = not path.exists() or path.stat().st_size == 0
|
|
with path.open("a", encoding="utf-8") as fh:
|
|
if fresh:
|
|
fh.write(f"# {slug}\n")
|
|
fh.write(text + "\n")
|
|
self.topics.setdefault(slug, []).append(text)
|
|
return slug, len(self.topics[slug])
|
|
|
|
|
|
class State:
|
|
DEFAULTS = {
|
|
"count": 0,
|
|
"used": [],
|
|
"last_question": None,
|
|
"last_post": None,
|
|
"last_auto": None,
|
|
"channel": QOTD_CHANNEL or None,
|
|
"time": DEFAULT_TIME,
|
|
"enabled": True,
|
|
}
|
|
|
|
def __init__(self) -> None:
|
|
self.data = dict(self.DEFAULTS)
|
|
if STATE_FILE.exists():
|
|
try:
|
|
self.data.update(json.loads(STATE_FILE.read_text(encoding="utf-8")))
|
|
except Exception as exc: # corrupt state must not brick the bot
|
|
log.warning("could not read %s: %s (starting fresh, file kept as .bak)", STATE_FILE, exc)
|
|
STATE_FILE.rename(STATE_FILE.with_suffix(".bak"))
|
|
|
|
def save(self) -> None:
|
|
tmp = STATE_FILE.with_suffix(".json.tmp")
|
|
tmp.write_text(json.dumps(self.data, indent=1) + "\n", encoding="utf-8")
|
|
tmp.replace(STATE_FILE)
|
|
|
|
|
|
bank = Bank()
|
|
state = State()
|
|
|
|
|
|
def next_question(topic: str | None = None) -> tuple[str, str] | None:
|
|
pairs = bank.pairs()
|
|
if topic:
|
|
pairs = [p for p in pairs if p[0] == topic.lower()]
|
|
if not pairs:
|
|
return None
|
|
used = set(state.data["used"])
|
|
cand = [p for p in pairs if qid(*p) not in used]
|
|
if not cand:
|
|
# pool exhausted (or topic exhausted): reshuffle, just don't
|
|
# immediately repeat the last question
|
|
last = state.data["last_question"]
|
|
state.data["used"] = []
|
|
cand = [p for p in pairs if qid(*p) != last]
|
|
choice = random.choice(cand)
|
|
state.data["used"].append(qid(*choice))
|
|
state.data["count"] += 1
|
|
state.data["last_question"] = qid(*choice)
|
|
state.data["last_post"] = dt.datetime.now(ZoneInfo(TIMEZONE)).isoformat(timespec="seconds")
|
|
state.save()
|
|
return choice
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# terminal-mail post style
|
|
|
|
|
|
def fmt_qotd(topic: str, text: str, number: int, now: dt.datetime) -> str:
|
|
sched = state.data.get("time") or DEFAULT_TIME
|
|
fields = [
|
|
("From:", "Tuxothy <theone@linux.na>"),
|
|
("To:", "<Linux> guild"),
|
|
("Date:", now.strftime("%a %Y-%m-%d %H:%M %Z")),
|
|
("Subj:", f"QOTD #{number} :: {topic}"),
|
|
]
|
|
box = []
|
|
box.append("\x1b[2m┌" + "─" * (VALUE_W + 8) + "┐\x1b[0m")
|
|
for key, val in fields:
|
|
val = val[:VALUE_W]
|
|
box.append(
|
|
"\x1b[2m│ \x1b[0m\x1b[1;36m" + f"{key:<6}" + "\x1b[0m"
|
|
+ f"{val:<{VALUE_W}}" + "\x1b[2m │\x1b[0m"
|
|
)
|
|
box.append("\x1b[2m└" + "─" * (VALUE_W + 8) + "┘\x1b[0m")
|
|
|
|
wrapped = textwrap.wrap(text, width=VALUE_W + 5) or [""]
|
|
body = ["\x1b[1;33mQ:\x1b[0m " + wrapped[0]]
|
|
body += [f" {line}" for line in wrapped[1:]]
|
|
|
|
head = "\x1b[1;32mtuxothy@forever\x1b[0m:\x1b[1;34m~\x1b[0m$ \x1b[37mopen qotd\x1b[0m"
|
|
foot = f"\x1b[2m# answer in-thread — next one lands at {sched} {ZoneInfo(TIMEZONE).tzname(now)}\x1b[0m"
|
|
return "```ansi\n" + "\n".join([head, *box, "", *body, "", foot]) + "\n```"
|
|
|
|
|
|
async def post_question(channel: discord.abc.Messageable, topic: str | None = None):
|
|
choice = next_question(topic)
|
|
if choice is None:
|
|
return None
|
|
top, text = choice
|
|
now = dt.datetime.now(ZoneInfo(TIMEZONE))
|
|
await channel.send(fmt_qotd(top, text, state.data["count"], now))
|
|
log.info("posted QOTD #%d (%s): %s", state.data["count"], top, text)
|
|
return choice
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# discord wiring
|
|
|
|
|
|
class Tux(discord.Client):
|
|
def __init__(self) -> None:
|
|
super().__init__(intents=discord.Intents.default())
|
|
self.tree = app_commands.CommandTree(self)
|
|
|
|
async def setup_hook(self) -> None:
|
|
if GUILD_ID:
|
|
self.tree.copy_global_to(guild=discord.Object(GUILD_ID))
|
|
await self.tree.sync()
|
|
self.loop.create_task(qotd_loop())
|
|
await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="/tux"))
|
|
|
|
async def on_ready(self) -> None:
|
|
guilds = ", ".join(f"{g.name} ({g.id})" for g in self.guilds) or "none yet"
|
|
log.info("tuxothy online as %s — guilds: %s", self.user, guilds)
|
|
|
|
|
|
client = Tux()
|
|
|
|
|
|
@client.tree.error
|
|
async def on_app_command_error(it: discord.Interaction, err: app_commands.AppCommandError) -> None:
|
|
log.exception("command failed", exc_info=err)
|
|
msg = f"that broke: `{err}`"
|
|
try:
|
|
if it.response.is_done():
|
|
await it.followup.send(msg, ephemeral=True)
|
|
else:
|
|
await it.response.send_message(msg, ephemeral=True)
|
|
except discord.DiscordException:
|
|
pass
|
|
|
|
|
|
def is_root(it: discord.Interaction) -> bool:
|
|
member = it.user
|
|
if isinstance(member, discord.Member) and member.guild_permissions.administrator:
|
|
return True
|
|
return isinstance(member, discord.Member) and any(r.name.lower() == ADMIN_ROLE.lower() for r in member.roles)
|
|
|
|
|
|
async def denied(it: discord.Interaction) -> None:
|
|
await it.response.send_message(f"the `/tux` commands are for folks with the `{ADMIN_ROLE}` role.", ephemeral=True)
|
|
|
|
|
|
tux = app_commands.Group(name="tux", description="Tuxothy the guild penguin (root only)", guild_only=True)
|
|
|
|
|
|
@tux.command(name="ask", description="post a question right now")
|
|
@app_commands.describe(topic="optional topic filter, e.g. wow")
|
|
async def ask(it: discord.Interaction, topic: str | None = None) -> None:
|
|
if not is_root(it):
|
|
return await denied(it)
|
|
await it.response.defer(ephemeral=True)
|
|
if topic and topic.lower() not in bank.topics:
|
|
return await it.response.send_message(
|
|
f"no topic `{topic}`. try: {', '.join(sorted(bank.topics))}", ephemeral=True
|
|
)
|
|
choice = await post_question(it.channel, topic)
|
|
assert choice is not None
|
|
if not state.data.get("channel"):
|
|
state.data["channel"] = it.channel.id
|
|
state.save()
|
|
await it.response.send_message(f"posted QOTD #{state.data['count']} from `{choice[0]}`.", ephemeral=True)
|
|
|
|
|
|
@tux.command(name="add", description="add a question to the bank")
|
|
@app_commands.describe(question="the question text", topic="topic file, created if missing")
|
|
async def addq(it: discord.Interaction, question: str, topic: str = "fun") -> None:
|
|
if not is_root(it):
|
|
return await denied(it)
|
|
text = " ".join(question.split())
|
|
if not text:
|
|
return await it.response.send_message("that question was blank, weirdly.", ephemeral=True)
|
|
if len(text) > 200:
|
|
return await it.response.send_message("max 200 chars — trim it down.", ephemeral=True)
|
|
if any(ord(c) > 127 for c in text):
|
|
return await it.response.send_message(
|
|
"plain ASCII only (no smart quotes/emoji) — sorry, penguins are typists.", ephemeral=True
|
|
)
|
|
slug = re.sub(r"[^a-z0-9-]", "-", topic.lower()).strip("-") or "fun"
|
|
if qid(slug, text) in set(state.data["used"]) or text.lower() in (
|
|
q.lower() for qs in bank.topics.values() for q in qs
|
|
):
|
|
return await it.response.send_message("that's already in the bank.", ephemeral=True)
|
|
slug, count = bank.add(slug, text)
|
|
await it.response.send_message(
|
|
f"added to `{slug}.txt` ({count} questions in topic, {bank.total()} in bank). "
|
|
"remember to commit it back to the repo when convenient.",
|
|
ephemeral=True,
|
|
)
|
|
|
|
|
|
@tux.command(name="topics", description="question count per topic")
|
|
async def topics(it: discord.Interaction) -> None:
|
|
if not is_root(it):
|
|
return await denied(it)
|
|
lines = [f"`{t}` — {len(qs)}" for t, qs in sorted(bank.topics.items())]
|
|
await it.response.send_message(" · ".join(lines), ephemeral=True)
|
|
|
|
|
|
@tux.command(name="status", description="bank + schedule summary")
|
|
async def status(it: discord.Interaction) -> None:
|
|
if not is_root(it):
|
|
return await denied(it)
|
|
ch_id = state.data.get("channel")
|
|
ch = client.get_channel(ch_id) if ch_id else None
|
|
remaining = bank.total() - len(set(state.data["used"]))
|
|
await it.response.send_message(
|
|
"\n".join(
|
|
[
|
|
f"posted so far: **{state.data['count']}**",
|
|
f"bank: **{bank.total()}** questions across {len(bank.topics)} topics ({remaining} unseen before reshuffle)",
|
|
f"schedule: **{'on' if state.data['enabled'] else 'off'}** at {state.data['time']} {TIMEZONE}",
|
|
f"auto-post channel: {ch.mention if ch else '`unset` — /tux ask once in the channel you want'}",
|
|
f"admin role: `{ADMIN_ROLE}`",
|
|
]
|
|
),
|
|
ephemeral=True,
|
|
)
|
|
|
|
|
|
@tux.command(name="schedule", description="set the daily post time, HH:MM (24h), or off")
|
|
@app_commands.describe(time="'HH:MM' or 'off'")
|
|
async def schedule(it: discord.Interaction, time: str) -> None:
|
|
if not is_root(it):
|
|
return await denied(it)
|
|
time = time.strip().lower()
|
|
if time == "off":
|
|
state.data["enabled"] = False
|
|
state.save()
|
|
return await it.response.send_message("daily post disabled.", ephemeral=True)
|
|
m = re.fullmatch(r"([01]?\d|2[0-3]):([0-5]\d)", time)
|
|
if not m:
|
|
return await it.response.send_message("give me `HH:MM` on a 24h clock, or `off`.", ephemeral=True)
|
|
state.data["time"] = f"{int(m[1]):02d}:{m[2]}"
|
|
state.data["enabled"] = True
|
|
if not state.data.get("channel"):
|
|
state.data["channel"] = it.channel.id
|
|
state.save()
|
|
await it.response.send_message(
|
|
f"daily post set to {state.data['time']} {TIMEZONE}"
|
|
+ (f", channel {it.channel.mention}." if state.data["channel"] == it.channel.id else "."),
|
|
ephemeral=True,
|
|
)
|
|
|
|
|
|
@tux.command(name="reload", description="re-read the question files from disk")
|
|
async def reloadq(it: discord.Interaction) -> None:
|
|
if not is_root(it):
|
|
return await denied(it)
|
|
before = bank.total()
|
|
bank.load()
|
|
await it.response.send_message(f"reloaded: {before} -> {bank.total()} questions.", ephemeral=True)
|
|
|
|
|
|
client.tree.add_command(tux)
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# daily scheduler
|
|
|
|
|
|
def resolve_channel() -> discord.abc.Messageable | None:
|
|
ch_id = state.data.get("channel")
|
|
if ch_id:
|
|
ch = client.get_channel(ch_id)
|
|
if ch is not None:
|
|
return ch
|
|
for guild in client.guilds:
|
|
for name in ("general", "qotd", "questions", "off-topic"):
|
|
ch = discord.utils.get(guild.text_channels, name=name)
|
|
if ch is not None and ch.permissions_for(guild.me).send_messages:
|
|
state.data["channel"] = ch.id
|
|
state.save()
|
|
log.info("auto-picked #%s in %s for daily posts", ch.name, guild.name)
|
|
return ch
|
|
return None
|
|
|
|
|
|
async def qotd_loop() -> None:
|
|
await client.wait_until_ready()
|
|
tz = ZoneInfo(TIMEZONE)
|
|
warned_no_channel = False
|
|
while not client.is_closed():
|
|
now = dt.datetime.now(tz)
|
|
hh, mm = (int(x) for x in (state.data.get("time") or DEFAULT_TIME).split(":"))
|
|
if state.data.get("enabled", True) and now.time() >= dt.time(hh, mm):
|
|
today = now.date().isoformat()
|
|
if state.data.get("last_auto") != today:
|
|
ch = resolve_channel()
|
|
if ch is None:
|
|
if not warned_no_channel:
|
|
log.warning("daily post due but no channel set — run /tux ask in the target channel")
|
|
warned_no_channel = True
|
|
else:
|
|
try:
|
|
await post_question(ch)
|
|
except discord.DiscordException:
|
|
log.exception("daily post failed; will retry next minute")
|
|
await asyncio.sleep(60)
|
|
continue
|
|
warned_no_channel = False
|
|
# mark the day handled either way so a missing channel
|
|
# doesn't spam the log every minute
|
|
state.data["last_auto"] = today
|
|
state.save()
|
|
await asyncio.sleep(60)
|
|
|
|
|
|
def main() -> None:
|
|
logging.basicConfig(
|
|
level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s", stream=sys.stdout
|
|
)
|
|
token = os.environ.get("BOT_TOKEN")
|
|
if not token:
|
|
sys.exit("set BOT_TOKEN in the environment (.env on the server) and start again")
|
|
bank.load()
|
|
if not bank.total():
|
|
sys.exit(f"no questions found under {QUESTIONS_DIR}")
|
|
client.run(token, log_handler=None)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|