from .base import BaseModule import random import time import json import appdirs RHYMES_FILE = "rhymes.json" SAVE_FILE = appdirs.user_data_dir() + "/poilau_save.json" class RhymesModule(BaseModule): rhymes: list = [] guild_config: dict = {} def load(self): with open(RHYMES_FILE, "r") as f: self.rhymes = json.load(f) try: with open(SAVE_FILE, "r") as file: self.guild_config = json.load(file) print('Loaded poilau save file "{0}"'.format(SAVE_FILE)) except FileNotFoundError: print('No previous "{0}" save file found'.format(SAVE_FILE)) except json.JSONDecodeError: print('"{0}" is an invalid JSON file.'.format(SAVE_FILE)) def save(self): with open(SAVE_FILE, "w") as file: json.dump(self.guild_config, file) print('Saved poilau state in file "{0}"'.format(SAVE_FILE)) def get_last_word(self, ch: str) -> str: truncated = ch while True: if len(truncated) < 2 or truncated[-1].isnumeric(): return "" if truncated[-1].isalpha() and truncated[-2].isalpha(): break truncated = truncated[:-1] truncated = truncated.split(' ')[-1] if truncated.isalpha(): return truncated else: return "" def poil_auquel(self, ch: str) -> str: for rhyme in self.rhymes: if ch in rhyme["blacklist"]: return "" if ch.endswith(tuple(rhyme["keys"])): return random.choice(rhyme["rhymes"]) return "" async def handle_message(self, message): message_content = message.content.lower() if message_content == "debug poilau": if(message.author.id == 151626081458192384): dump = {} for key, value in self.guild_config.items(): channel_name = await self.get_guild_name(key) dump[channel_name] = value - time.time() await message.author.send( "```json\n{0}```".format(json.dumps(dump, ensure_ascii=False, indent=4)) ) return if message_content == "tg fouras" and message.guild: self.guild_config[message.guild.id] = {43000,1.0} await message.channel.send("ok :'(") return last_word = self.get_last_word(message_content) if message.author != self._client.user and message.guild and last_word: poil = self.poil_auquel(last_word) guild_config = self.guild_config.get(message.guild.id, {"cooldown": 0, "self-control": 1.0}) if poil and time.time() - guild_config["cooldown"] > 0: if random.random() < guild_config["self-control"]: self.guild_config[message.guild.id]["self-control"] *= 0.9 return wait_time = random.randint(0, 900) if bool(random.getrandbits(1)): wait_time = random.randint(900, 10800) self.guild_config[message.guild.id] = {"cooldown": time.time() + wait_time, "self-control": 1.0} await message.channel.send(poil) return