moontalk/bots/moonchat/scramble-bot.py
2024-02-11 01:02:02 +00:00

59 lines
2.1 KiB
Python

# TODO: add a fucking scoreboard or something? this is a copy of a Espernet bot.
from moonchat import *
import sys
import random
import io
class Bot:
def __init__(self, chat: Moonchat, words: list[str]):
self.chat = chat
self.words = words
async def next_winner(self, word: str, limit: float):
try:
async with asyncio.timeout(limit):
async for message in self.chat.messages():
if word in message.content.lower():
return message
except TimeoutError:
return None
async def handle_incoming(self):
limit = 60
async for message in self.chat.messages():
if message.nickname == 'Server':
continue # ignore the server
if "!scramble" not in message.content:
continue
print(f"GAME REQUESTED: {message=}")
selected_word = random.choice(self.words)
scrambled_word = ''.join(random.sample(selected_word, len(selected_word)))
print(f"GAME START: {scrambled_word} is {selected_word}")
await self.chat.send_message(f"Unscramble in {limit} seconds to win! The word is: {scrambled_word}.")
winner = await self.next_winner(selected_word, limit)
print(f"GAME OVER: {winner=}")
if winner:
await self.chat.send_message(f"The word was {selected_word}. {winner.nickname} wins!")
else:
await self.chat.send_message(f"Time's up! The word was {selected_word}. No one wins.")
async def main(words: list[str]):
chat = await Moonchat.connect("7ks473deh6ggtwqsvbqdurepv5i6iblpbkx33b6cydon3ajph73sssad.onion", 50000)
bot = Bot(chat, words)
await chat.send_message("To play scramble say: !scramble")
await bot.handle_incoming()
def load_words(file: io.TextIOBase):
for line in file:
line = line.strip().lower()
if "'" not in line and len(line) == 5:
yield line
if __name__ == "__main__":
import asyncio
words = list(load_words(sys.stdin))
print(f"Loaded {len(words)} words")
asyncio.run(main(words))