holy-heck-i-really-like-stats/bot.py

74 lines
1.7 KiB
Python
Raw Normal View History

2023-04-07 10:01:57 +10:00
#!/usr/bin/env python3
from discord.utils import setup_logging
import argparse
import discord
import logging
import re
2023-04-07 10:13:11 +10:00
import shutil
2023-04-07 10:01:57 +10:00
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)
2023-04-07 10:13:11 +10:00
shutil.move(_DB, _DB_DEST)
2023-04-07 10:01:57 +10:00
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()