breadbot/breadbot/plugins/bread.py

81 lines
2.2 KiB
Python

import logging
import random
import re
from pathlib import Path
from typing import Optional
from pinhook import plugin # type: ignore
from pinhook.bot import Bot # type: ignore
logger = logging.getLogger(__name__)
data_path = Path('/bread/breadbot')
count_file = data_path / 'breadcount.txt'
messages_file = data_path / 'bread_messages.txt'
word_regex = re.compile(r'\W')
def get_that_bread() -> str:
try:
bread_messages = messages_file.read_text().strip().splitlines()
assert bread_messages
except (IOError, TypeError, ValueError, AssertionError):
if not messages_file.exists():
messages_file.write_text('bread\n')
logger.warning(f'Bread messages file at {messages_file} not found '
'or corrupted, using ["bread"]')
bread_messages = ['bread']
return random.choice(bread_messages)
def increment_bread() -> None:
try:
count = int(count_file.read_text().strip())
except (IOError, TypeError, ValueError):
logger.warning(f'Breadcount file at {count_file} not found '
'or corrupted, restarting from zero')
count = 0
count += 1
count_file.write_text(str(count))
@plugin.listener('bread')
def bread(ctx: Bot.Message) -> Optional[plugin.Output]:
words = set(word_regex.split(ctx.text.lower()))
if 'bread' in words:
increment_bread()
if words == {'bread'}:
return plugin.message(get_that_bread())
return None
@plugin.command(
'!nukethebread',
help_text='Reset the breadcount.',
ops=True,
ops_msg='This command is restricted to breadpunk admins.'
)
def nukethebread(ctx: Bot.Message) -> plugin.Output:
count_file.write_text('0')
return plugin.message('Bread count has been reset.')
@plugin.command(
'!breadcount',
help_text='How many times did bakers say bread here?',
)
def breadcount(ctx: Bot.Message) -> plugin.Output:
try:
count = int(count_file.read_text().strip())
except (IOError, TypeError, ValueError):
return plugin.message(
'something is wrong with the breadcount! '
'quick, scream at lucitoast'
)
else:
return plugin.message(
f'{count} bread{"s" if count != 1 else ""} so far'
)