diff --git a/bot.py b/bot.py index 12cd490..ee15a99 100644 --- a/bot.py +++ b/bot.py @@ -1,10 +1,12 @@ import argparse -import asyncio +import asyncio.subprocess import datetime import json +import os.path import random import re import sys +import tempfile import traceback from typing import Callable from typing import List @@ -271,6 +273,55 @@ def cmd_settoday(match: Match[str]) -> Response: return SetTodayResponse(match, rest) +async def check_call(*cmd: str) -> None: + proc = await asyncio.subprocess.create_subprocess_exec( + *cmd, stdout=asyncio.subprocess.DEVNULL, + ) + await proc.communicate() + if proc.returncode != 0: + raise ValueError(cmd, proc.returncode) + + +class VideoIdeaResponse(MessageResponse): + def __init__(self, match: Match[str], videoidea: str) -> None: + super().__init__( + match, + 'added! https://github.com/asottile/scratch/wiki/anthony-explains-ideas', # noqa: E501 + ) + self.videoidea = videoidea + + async def __call__(self, config: Config) -> Optional[str]: + async def _git(*cmd: str) -> None: + await check_call('git', '-C', tmpdir, *cmd) + + with tempfile.TemporaryDirectory() as tmpdir: + await _git( + 'clone', '--depth=1', '--quiet', + 'git@github.com:asottile/scratch.wiki', '.', + ) + ideas_file = os.path.join(tmpdir, 'anthony-explains-ideas.md') + with open(ideas_file, 'rb+') as f: + f.seek(-1, os.SEEK_END) + c = f.read() + if c != b'\n': + f.write(b'\n') + f.write(f'- {self.videoidea}\n'.encode()) + await _git('add', '.') + await _git('commit', '-q', '-m', 'idea added by !videoidea') + await _git('push', '-q', 'origin', 'HEAD') + return await super().__call__(config) + + +@handle_message('![wv]ideoidea') +def cmd_videoidea(match: Match[str]) -> Response: + if match['user'] != match['channel']: + return MessageResponse( + match, 'https://www.youtube.com/watch?v=RfiQYRn7fBg', + ) + _, _, rest = match['msg'].partition(' ') + return VideoIdeaResponse(match, rest) + + class UptimeResponse(Response): async def __call__(self, config: Config) -> Optional[str]: url = f'https://api.twitch.tv/helix/streams?user_login={config.channel}' # noqa: E501