From 6b36720c3725a198b3add060a4c97748a3524cc6 Mon Sep 17 00:00:00 2001 From: xeals Date: Fri, 7 Apr 2023 10:01:57 +1000 Subject: [PATCH] add bot --- .gitignore | 3 ++- bot.py | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ flake.nix | 1 + 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100755 bot.py diff --git a/.gitignore b/.gitignore index 8560a9f..ac63138 100644 --- a/.gitignore +++ b/.gitignore @@ -8,5 +8,6 @@ tmp/ build htmlcov -data.db +*.db cache/ +token diff --git a/bot.py b/bot.py new file mode 100755 index 0000000..b858675 --- /dev/null +++ b/bot.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 + +from discord.utils import setup_logging +import argparse +import discord +import logging +import os +import re +import subprocess as sp + +discord.utils.setup_logging() +_log = logging.getLogger("statbot") + +_GAMES = "games.txt" +_DB = "holy-heck2.db" +_DB_DEST = f"/var/lib/grafana/{_DB}" + + +def _write_game(content: str): + try: + with open(_GAMES, "a") as f: + f.write(content) + f.write("\n") + except: + _log.exception(f"failed writing game {content}") + + +def _update_db(): + try: + games = [] + with open(_GAMES) as f: + for line in f: + games.append(line.strip()) + sp.run(["./index.py", "-o", _DB] + games) + os.rename(_DB, _DB_DEST) + except: + _log.exception(f"failed updating db") + + +class BotClient(discord.Client): + async def on_ready(self): + _log.info(f"ready as {self.user}") + + async def on_message(self, message: discord.Message): + content = message.content + if re.match("https://replay.pokemonshowdown.com/dl-.*", content): + _log.info(f"Recognised {content} as a League game") + _write_game(content) + _update_db() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + "-t", + "--token-file", + metavar="FILE", + default="token", + help="file containing Discord API token", + ) + + args = parser.parse_args() + + intents = discord.Intents.default() + intents.message_content = True + client = BotClient(intents=intents) + with open(args.token_file) as f: + token = f.read().strip() + client.run(token, log_handler=None) + + +if __name__ == "__main__": + main() diff --git a/flake.nix b/flake.nix index 5e245ee..eb08739 100644 --- a/flake.nix +++ b/flake.nix @@ -13,6 +13,7 @@ buildInputs = let python = pkgs.python3.withPackages (ps: [ + ps.discordpy ps.requests ]); in