101 lines
2.3 KiB
Python
101 lines
2.3 KiB
Python
from dataclasses import dataclass
|
|
from html import escape
|
|
from random import choice
|
|
from typing import *
|
|
|
|
from ..functions import reply
|
|
from ..models import Message
|
|
|
|
HELP = """Die drei ??? Folgenindex
|
|
!ddf [episode #|title]
|
|
"""
|
|
|
|
|
|
def init(bot):
|
|
if "ddf.eps" not in bot.shared:
|
|
with open(bot.config.get("ddf.storage")) as fp:
|
|
bot.shared["ddf.db"] = db = load_db(fp)
|
|
bot.shared["ddf.eps"] = tuple(set(db.values()))
|
|
|
|
bot.on_command({"ddf", "???"}, handle)
|
|
|
|
|
|
def load_db(fp):
|
|
db = {}
|
|
for ep in Episode.from_csv(fp):
|
|
if ep.nr_europa:
|
|
db[ep.nr_europa.lower()] = ep
|
|
elif ep.nr_kosmos and ep.nr_kosmos.lower() not in db:
|
|
db[ep.nr_kosmos.lower()] = ep
|
|
if ep.title_de:
|
|
db[ep.title_de.lower()] = ep
|
|
if ep.title_us:
|
|
db[ep.title_us.lower()] = ep
|
|
return db
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Episode:
|
|
nr_kosmos: str
|
|
nr_europa: str
|
|
nr_randho: str
|
|
title_us: str
|
|
title_de: str
|
|
autor: str
|
|
year_randho: str
|
|
year_kosmos: str
|
|
year_europa: str
|
|
|
|
@classmethod
|
|
def from_csv(cls, fp) -> Iterable["Episode"]:
|
|
fp = iter(fp)
|
|
next(fp) # skip the first line, it contains the header
|
|
for line in fp:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
yield cls(*line.split(";"))
|
|
|
|
|
|
async def handle(message: Message):
|
|
bot = message.app
|
|
args = message.args
|
|
|
|
ep: Episode = None
|
|
if not args:
|
|
eps = bot.shared["ddf.eps"]
|
|
ep = choice(eps)
|
|
else:
|
|
arg = args.str(0).lower()
|
|
db = bot.shared["ddf.db"]
|
|
if arg in db:
|
|
ep = db[arg]
|
|
else:
|
|
for key in db:
|
|
if arg in key:
|
|
ep = db[key]
|
|
break
|
|
|
|
if not ep:
|
|
return
|
|
|
|
nr = year = src = None
|
|
if ep.nr_europa:
|
|
src = ""
|
|
nr = ep.nr_europa
|
|
year = ep.year_europa
|
|
elif ep.nr_kosmos:
|
|
src = "Buch"
|
|
nr = ep.nr_kosmos
|
|
year = ep.year_kosmos
|
|
|
|
if not nr or not year:
|
|
return
|
|
|
|
html = f"(<i>{src}<i>:) " if src else ""
|
|
html += f"<b>#{escape(nr)}</b> <i>Die drei ???</i>: <b>{escape(ep.title_de)}</b>"
|
|
if ep.title_us:
|
|
html += f" (US: <i>{escape(ep.title_us)}</i>)"
|
|
html += f" ({escape(year)})"
|
|
|
|
await reply(message, html=html)
|