converted hangman to buttons

This commit is contained in:
NikolajDanger
2021-08-19 13:12:15 +02:00
parent 3819e56cd6
commit 98988efa4b
8 changed files with 266 additions and 250 deletions

View File

@ -8,4 +8,5 @@ from .helper_classes import DatabaseFuncs
from .event_handlers import EventHandler, ErrorHandler
from .util_functions import (get_params, log_this, cap, make_files,
replace_multiple, emoji_to_command, long_strings,
sanitize, get_options, get_credentials)
sanitize, get_options, get_credentials, encode_id,
decode_id)

View File

@ -16,7 +16,7 @@ from discord.ext import commands # Used to compare errors with command
# errors
from discord_slash.context import SlashContext, ComponentContext
from gwendolyn.utils.util_functions import emoji_to_command
from gwendolyn.utils.util_functions import emoji_to_command, decode_id
class EventHandler():
@ -79,37 +79,32 @@ class EventHandler():
params = [message, f"#{user.id}", column-1]
await self.bot.games.connect_four.place_piece(*params)
elif tests.hangman_reaction_test(*reaction_test_parameters):
self.bot.log("They reacted to the hangman message")
if ord(reaction.emoji) in range(127462, 127488):
# The range is letter-emojis
guess = chr(ord(reaction.emoji)-127397)
# Converts emoji to letter
params = [message, f"#{user.id}", guess]
await self.bot.games.hangman.guess(*params)
else:
self.bot.log("Bot they didn't react with a valid guess")
async def on_component(self, ctx: ComponentContext):
info = ctx.custom_id.split(":")
info = decode_id(ctx.custom_id)
channel = ctx.origin_message.channel
if info[0] == "plex":
if info[1] == "movie":
if info[0].lower() == "plex":
if info[1].lower() == "movie":
await self.bot.other.plex.add_movie(
ctx.origin_message,
info[2],
not isinstance(channel, discord.DMChannel)
)
if info[1] == "show":
elif info[1].lower() == "show":
await self.bot.other.plex.add_show(
ctx.origin_message,
info[2],
not isinstance(channel, discord.DMChannel)
)
elif info[0].lower() == "hangman":
if str(ctx.author_id) == info[2]:
if info[1].lower() == "guess":
await self.bot.games.hangman.guess(ctx, *info[3:])
elif info[1].lower() == "end":
await self.bot.games.hangman.stop(ctx, *info[3:])
class ErrorHandler():
"""

View File

@ -24,11 +24,6 @@ class DatabaseFuncs():
wipe_games()
connect_four_reaction_test(message: discord.Message,
user: discord.User) -> bool
hangman_reaction_test(message: discord.Message,
user: discord.User) -> bool
plex_reaction_test(message: discord.Message,
user: discord.User) -> bool, bool,
list
imdb_commands()
"""
@ -111,8 +106,7 @@ class DatabaseFuncs():
game_types = [
"trivia questions",
"blackjack games",
"connect 4 games",
"hangman games",
"connect 4 games"
"hex games"
]
for game_type in game_types:
@ -163,48 +157,6 @@ class DatabaseFuncs():
return valid_reaction
def hangman_reaction_test(self, message: discord.Message,
user: discord.User):
"""
Test if the given message is the current hangman game.
Also tests if the given user is the one who's playing hangman.
*Parameters*
------------
message: discord.Message
The message to test.
user: discord.User
The user to test.
*Returns*
---------
: bool
Whether the given message is the current hangman game
and if the user who reacted is the user who's playing
hangman.
"""
channel = message.channel
file_path = f"gwendolyn/resources/games/old_images/hangman{channel.id}"
if os.path.isfile(file_path):
with open(file_path, "r") as file_pointer:
old_messages = file_pointer.read().splitlines()
else:
return False
game_message = False
for old_message in old_messages:
old_message_id = int(old_message)
if message.id == old_message_id:
database = self.bot.database["hangman games"]
channel_search = {"_id": str(channel.id)}
game = database.find_one(channel_search)
if user == game["player"]:
game_message = True
break
return game_message
async def imdb_commands(self):
"""Sync the slash commands with the discord API."""
collection = self.bot.database["last synced"]

View File

@ -21,6 +21,17 @@ import logging # Used for logging
import os # Used by make_files() to check if files exist
import sys # Used to specify printing for logging
import imdb # Used to disable logging for the module
import string
BASE_37 = ":" + string.digits + string.ascii_uppercase
BASE_128 = list(
string.digits +
string.ascii_letters +
"!#$€£¢¥¤&%()*+,-./;:<=>?@[]_{|}~ `¦§©®«»±µ·¿əʒ" +
"ÆØÅÐÉÈÊÇÑÖ" +
"æøåðéèêçñö"
)
# All of this is logging configuration
FORMAT = " %(asctime)s | %(name)-16s | %(levelname)-8s | %(message)s"
@ -340,3 +351,39 @@ def emoji_to_command(emoji: str):
return_value = ""
return return_value
def encode_id(info: list):
letters = list(":".join(info))
dec = 0
for i, letter in enumerate(letters):
try:
dec += (37**i) * BASE_37.index(letter.upper())
except ValueError:
log_this("Could not encode letter {letter}", level=30)
custom_id = []
while dec:
custom_id.append(BASE_128[dec % 128])
dec = dec // 128
custom_id = ''.join(custom_id)
log_this(f"Encoded {info} to {custom_id}")
return custom_id
def decode_id(custom_id: str):
letters = list(custom_id)
dec = 0
for i, letter in enumerate(letters):
dec += (128**i) * BASE_128.index(letter)
info_string = []
while dec:
info_string.append(BASE_37[dec % 37])
dec = dec // 37
info = ''.join(info_string).split(':')
log_this(f"Decoded {custom_id} to be {info}")
return ''.join(info_string).split(':')