87 lines
2.8 KiB
Python
87 lines
2.8 KiB
Python
from .base import BaseModule
|
|
import random
|
|
import time
|
|
import json
|
|
|
|
RHYMES_FILE = "rhymes.txt"
|
|
|
|
|
|
class RhymesModule(BaseModule):
|
|
rhymes_keys: dict = {}
|
|
rhyme_strings: dict = {}
|
|
cooldown: dict = {}
|
|
|
|
def load(self):
|
|
with open(RHYMES_FILE, "r", encoding="utf-8") as f:
|
|
data = f.read()
|
|
|
|
keys_start = data.index("[KEYS]") + len("[KEYS]\n")
|
|
keys_end = data.index("[RHYMES]")
|
|
keys_data = data[keys_start:keys_end].split("\n")
|
|
keys = {}
|
|
for key_data in keys_data:
|
|
if key_data:
|
|
k, v = key_data.split(":")
|
|
keys[k] = v.split(",")
|
|
|
|
rhymes_start = data.index("[RHYMES]") + len("[RHYMES]\n")
|
|
rhymes_data = data[rhymes_start:].split("\n")
|
|
rhymes = {}
|
|
for rhyme_data in rhymes_data:
|
|
if rhyme_data:
|
|
k, v = rhyme_data.split(":")
|
|
rhymes[k] = v.split(",")
|
|
|
|
self.rhyme_keys = keys
|
|
self.rhyme_strings = rhymes
|
|
|
|
def save(self):
|
|
dump = {}
|
|
for key, value in self.cooldown.items():
|
|
dump[key.id] = value - time.time()
|
|
return dump
|
|
|
|
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]
|
|
return truncated
|
|
|
|
def poil_auquel(self, ch: str) -> str:
|
|
for key in self.rhyme_keys:
|
|
if ch.endswith(tuple(self.rhyme_keys[key])):
|
|
return random.choice(self.rhyme_strings[key])
|
|
return ""
|
|
|
|
async def handle_message(self, message):
|
|
message_content = message.content.lower()
|
|
|
|
|
|
if message_content == "debug":
|
|
dump = {}
|
|
for key, value in self.cooldown.items():
|
|
channel_name = await self.get_channel_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
|
|
|
|
last_word = self.get_last_word(message_content)
|
|
if message.author != self._client.user and last_word:
|
|
poil = self.poil_auquel(last_word)
|
|
# cooldown = 0
|
|
# if message.channel in self.cooldown:
|
|
# cooldown = self.cooldown[message.channel]
|
|
cooldown = self.cooldown.get(message.channel, 0)
|
|
|
|
if poil and time.time() - cooldown > 0:
|
|
wait_time = random.randint(0, 900)
|
|
if bool(random.getrandbits(1)):
|
|
wait_time = random.randint(900, 10800)
|
|
self.cooldown[message.channel] = time.time() + wait_time
|
|
await message.channel.send(poil)
|
|
return
|