From 9fb728678ce798254ad188582bcb65545e547890 Mon Sep 17 00:00:00 2001 From: Walter Kuppens Date: Sat, 21 Sep 2019 16:31:03 -0700 Subject: [PATCH] Appeased pylint and cleaned up naming --- cho_commands.py => commands.py | 25 ++++----- config.py | 3 +- cho_game.py => game.py | 87 ++++++++++++------------------ game_state.py | 77 ++++++++++++++------------ cho_client.py => lorewalker_cho.py | 42 +++++++++++---- main.py | 4 +- sql/active_game.py | 40 +++++++------- sql/guild.py | 12 ++--- sql/schema.py | 14 ++--- sql/scoreboard.py | 36 ++++++------- cho_utils.py => utils.py | 0 11 files changed, 175 insertions(+), 165 deletions(-) rename cho_commands.py => commands.py (92%) rename cho_game.py => game.py (80%) rename cho_client.py => lorewalker_cho.py (83%) rename cho_utils.py => utils.py (100%) diff --git a/cho_commands.py b/commands.py similarity index 92% rename from cho_commands.py rename to commands.py index 6847bbc..01f34c5 100644 --- a/cho_commands.py +++ b/commands.py @@ -18,10 +18,11 @@ import logging import re + import discord import sql.guild -from cho_utils import cho_command +from utils import cho_command CMD_START = "start" CMD_STOP = "stop" @@ -36,11 +37,11 @@ LOGGER = logging.getLogger("cho") -class ChoCommandsMixin(): +class CommandsMixin(): """Contains command handler functions for ChoClient.""" @cho_command(CMD_HELP) - async def _handle_help(self, message, args, config): + async def handle_help(self, message, args, config): """Responds with help to teach users about the bot's functions. :param m message: @@ -92,7 +93,7 @@ async def _handle_help(self, message, args, config): await message.channel.send(embed=embed) @cho_command(CMD_START, kind="channel") - async def _handle_start_command(self, message, args, config): + async def handle_start_command(self, message, args, config): """Starts a new game at the request of a user. :param m message: @@ -101,7 +102,7 @@ async def _handle_start_command(self, message, args, config): :type m: discord.message.Message """ - if self._is_game_in_progress(message.guild.id): + if self.is_game_in_progress(message.guild.id): await message.channel.send( "A game is already active in the trivia channel. If you " "want to participate please go in there." @@ -115,10 +116,10 @@ async def _handle_start_command(self, message, args, config): await message.channel.send( "Okay I'm starting a game. Don't expect me to go easy." ) - await self._start_game(message.guild, message.channel) + await self.start_game(message.guild, message.channel) @cho_command(CMD_STOP, kind="channel") - async def _handle_stop_command(self, message, args, config): + async def handle_stop_command(self, message, args, config): """Stops the current game at the request of the user. :param m message: @@ -129,12 +130,12 @@ async def _handle_stop_command(self, message, args, config): guild_id = message.guild.id - if self._is_game_in_progress(guild_id): + if self.is_game_in_progress(guild_id): LOGGER.info( "Stopping game in guild %s, requested by %s", guild_id, message.author ) - await self._stop_game(guild_id) + await self.stop_game(guild_id) await message.channel.send( "I'm stopping the game for now. Maybe we can play another time?" @@ -147,7 +148,7 @@ async def _handle_stop_command(self, message, args, config): ) @cho_command(CMD_SCOREBOARD, kind="channel") - async def _handle_scoreboard_command(self, message, args, config): + async def handle_scoreboard_command(self, message, args, config): """Displays a scoreboard at the request of the user. :param m message: @@ -190,7 +191,7 @@ async def _handle_scoreboard_command(self, message, args, config): "get some scores in the scoreboard.") @cho_command(CMD_SET_CHANNEL, admin_only=True) - async def _handle_set_channel(self, message, args, config): + async def handle_set_channel(self, message, args, config): """Updates the trivia channel configuration for the guild. :param m message: @@ -225,7 +226,7 @@ async def _handle_set_channel(self, message, args, config): ) @cho_command(CMD_SET_PREFIX, admin_only=True) - async def _handle_set_prefix(self, message, args, config): + async def handle_set_prefix(self, message, args, config): """Updates the prefix used for the guild. :param m message: diff --git a/config.py b/config.py index 7a313c9..bcf04a1 100644 --- a/config.py +++ b/config.py @@ -16,9 +16,10 @@ """Contains helper functions to get configuration data for the worker.""" -import logging import os +import logging + from logging.handlers import RotatingFileHandler diff --git a/cho_game.py b/game.py similarity index 80% rename from cho_game.py rename to game.py index 59f100f..70a79f5 100644 --- a/cho_game.py +++ b/game.py @@ -21,9 +21,7 @@ from discord.channel import TextChannel from discord.guild import Guild -from discord.message import Message -import cho_utils import sql.guild import sql.scoreboard @@ -35,26 +33,16 @@ LOGGER = logging.getLogger("cho") -class ChoGameMixin(): +class GameMixin(): """Adds trivia game logic to ChoClient. Gotta love compartmentalization.""" - async def handle_message_response(self, message: Message): - """Processes a non-command message received during an active game. + def __cleanup_game(self, guild_id: int): + """Removes the game state of a guild from memory. - :param m message: - :type m: discord.message.Message + :param int guild_id: """ - guild_id = guild_id = message.guild.id - - guild_query_results = sql.guild.get_guild(self.engine, guild_id) - if guild_query_results: - _, config = guild_query_results - else: - config = {} - - if cho_utils.is_message_from_trivia_channel(message, config): - await self._process_answer(message) + del self.active_games[guild_id] async def resume_incomplete_games(self): """Resumes all inactive games, usually caused by the bot going down.""" @@ -65,22 +53,21 @@ async def resume_incomplete_games(self): "Found %d incomplete games that need to be resumed", len(incomplete_games)) - for guild_id, active_game_dict in incomplete_games: + for guild_id, existing_game in incomplete_games: existing_game_state = GameState( self.engine, guild_id, - active_game_dict=active_game_dict, + existing_game=existing_game, save_to_db=True) self.active_games[guild_id] = existing_game_state guild = self.get_guild(guild_id) - if guild: channel = guild.get_channel(existing_game_state.channel_id) asyncio.ensure_future( - self._ask_question(channel, existing_game_state)) + self.ask_question(channel, existing_game_state)) - async def _start_game(self, guild: Guild, channel: TextChannel): + async def start_game(self, guild: Guild, channel: TextChannel): """Starts a new trivia game. :param g guild: @@ -89,30 +76,30 @@ async def _start_game(self, guild: Guild, channel: TextChannel): :type c: discord.channel.TextChannel """ - new_game = self._create_game(guild.id, channel.id) + new_game = self.create_game(guild.id, channel.id) await asyncio.sleep(SHORT_WAIT_SECS) - await self._ask_question(channel, new_game) + await self.ask_question(channel, new_game) - async def _stop_game(self, guild_id: int): + async def stop_game(self, guild_id: int): """Stops a game in progress for a guild. :param int guild_id: """ - game_state = self._get_game(guild_id) + game_state = self.get_game(guild_id) game_state.stop_game() - self._cleanup_game(guild_id) + self.__cleanup_game(guild_id) - async def _process_answer(self, message): + async def process_answer(self, message): """Called when an answer is received from a user. :param m message: :type m: discord.message.Message """ - game_state = self._get_game(message.guild.id) + game_state = self.get_game(message.guild.id) # Don't process the answer if the bot is currently in-between asking # questions. Without this multiple people can get the answer right @@ -138,11 +125,11 @@ async def _process_answer(self, message): ), ) await asyncio.sleep(SHORT_WAIT_SECS) - await self._ask_question(message.channel, game_state) + await self.ask_question(message.channel, game_state) else: LOGGER.debug("Incorrect answer received: %s", message.content) - async def _ask_question(self, channel, game_state): + async def ask_question(self, channel, game_state): """Asks a trivia question in a Discord channel. :param c channel: @@ -158,22 +145,22 @@ async def _ask_question(self, channel, game_state): # This check also covers the rare edge-case where a game is stopped and # started again within the 10 second window between questions so that # the trivia game doesn't duplicate itself. - if not self._is_same_game_in_progress(guild_id, game_state): + if not self.is_same_game_in_progress(guild_id, game_state): return if game_state.complete: - await self._finish_game(channel, game_state) + await self.complete_game(channel, game_state) return question = game_state.get_question() last_correct_answers_total = game_state.correct_answers_total - game_state.waiting = True + await channel.send(question["text"]) await asyncio.sleep(LONG_WAIT_SECS) # Check again as it can happen here too. - if not self._is_same_game_in_progress(guild_id, game_state): + if not self.is_same_game_in_progress(guild_id, game_state): return # If the correct answer total was not incrememnted, that means that no @@ -188,9 +175,9 @@ async def _ask_question(self, channel, game_state): ), ) await asyncio.sleep(SHORT_WAIT_SECS) - await self._ask_question(channel, game_state) + await self.ask_question(channel, game_state) - async def _finish_game(self, channel, game_state): + async def complete_game(self, channel, game_state): """Outputs the scoreboard and announces the winner of a game. :param c channel: @@ -199,14 +186,14 @@ async def _finish_game(self, channel, game_state): """ guild_id = channel.guild.id - self._cleanup_game(guild_id) + self.__cleanup_game(guild_id) score_fmt = "{emoji} <@!{user_id}> - {score} point{suffix}\n" scores = list(game_state.scores.items()) # Don't bother making a scoreboard if it's going to be empty. It's # better to make fun of everyone for being so bad at the game instead! - if len(scores) == 0: + if not scores: await channel.send( "Well it appears no one won because no one answered a " "*single* question right. You people really don't know much " @@ -260,15 +247,7 @@ async def _finish_game(self, channel, game_state): .format(str(ties + 1), scoreboard) ) - def _cleanup_game(self, guild_id: int): - """Removes the game state of a guild from memory. - - :param int guild_id: - """ - - del self.active_games[guild_id] - - def _get_game(self, guild_id: int) -> GameState: + def get_game(self, guild_id: int) -> GameState: """Retrieves a guild's game state from memory. :param int guild_id: @@ -278,7 +257,7 @@ def _get_game(self, guild_id: int) -> GameState: return self.active_games[guild_id] - def _create_game(self, guild_id: int, channel_id: int) -> GameState: + def create_game(self, guild_id: int, channel_id: int) -> GameState: """Creates a new game state. :param int guild_id: @@ -292,10 +271,12 @@ def _create_game(self, guild_id: int, channel_id: int) -> GameState: guild_id, channel_id=channel_id, save_to_db=True) + self.active_games[guild_id] = new_game + return new_game - def _is_game_in_progress(self, guild_id: int) -> bool: + def is_game_in_progress(self, guild_id: int) -> bool: """Checks if a game is in progress for a guild. :param int guild_id: @@ -305,7 +286,7 @@ def _is_game_in_progress(self, guild_id: int) -> bool: return guild_id in self.active_games - def _is_same_game_in_progress( + def is_same_game_in_progress( self, guild_id: int, game_state: GameState) -> bool: @@ -318,6 +299,6 @@ def _is_same_game_in_progress( """ return ( - self._is_game_in_progress(guild_id) - and self._get_game(guild_id).uuid == game_state.uuid + self.is_game_in_progress(guild_id) + and self.get_game(guild_id).uuid == game_state.uuid ) diff --git a/game_state.py b/game_state.py index f0a992a..b4c5a36 100644 --- a/game_state.py +++ b/game_state.py @@ -22,7 +22,7 @@ from sqlalchemy.engine import Engine -import cho_utils +import utils import sql.active_game from data.questions import DEFAULT_QUESTIONS @@ -38,14 +38,14 @@ def __init__( engine: Engine, guild_id: int, channel_id: int = None, - active_game_dict: dict = None, + existing_game: dict = None, save_to_db=False): """Converts a game state dict into an object. :param e engine: :param int guild_id: :param int channel_id: - :param dict active_game_dict: + :param dict existing_game: :param bool save_to_db: :type e: sqlalchemy.engine.Engine """ @@ -54,19 +54,19 @@ def __init__( self.guild_id = guild_id self.save_to_db = save_to_db - if active_game_dict: - if CURRENT_REVISION != active_game_dict["revision"]: + if existing_game: + if CURRENT_REVISION != existing_game["revision"]: raise ValueError("GameState revision mismatch.") self.revision = CURRENT_REVISION - self.questions = active_game_dict["questions"] - self.current_question = active_game_dict["current_question"] - self.complete = active_game_dict["complete"] - self.scores = active_game_dict["scores"] - self.channel_id = active_game_dict["channel_id"] + self.questions = existing_game["questions"] + self.current_question = existing_game["current_question"] + self.complete = existing_game["complete"] + self.scores = existing_game["scores"] + self.channel_id = existing_game["channel_id"] else: self.revision = CURRENT_REVISION - self.questions = self._select_questions(DEFAULT_QUESTIONS) + self.questions = self.__select_questions(DEFAULT_QUESTIONS) self.current_question = 0 self.complete = False self.scores = {} @@ -83,7 +83,8 @@ def __init__( if self.save_to_db: sql.active_game.save_game_state(self.engine, self) - def _select_questions(self, questions: list, count=10) -> list: + @staticmethod + def __select_questions(questions: list, count=10) -> list: """Selects a bunch of random questions for a trivia session. :param list questions: @@ -95,19 +96,11 @@ def _select_questions(self, questions: list, count=10) -> list: return cloned_questions[:count] - def _complete_game(self): + def __complete_game(self): """Completes the game and determines the winner.""" self.complete = True - def stop_game(self): - """Stops a game in progress.""" - - self._complete_game() - - if self.save_to_db: - sql.active_game.save_game_state(self.engine, self) - def serialize(self) -> str: """Converts the game state object into JSON so it an be stored. @@ -124,17 +117,42 @@ def serialize(self) -> str: "channel_id": self.channel_id, } + def stop_game(self): + """Stops a game in progress.""" + + self.__complete_game() + + if self.save_to_db: + sql.active_game.save_game_state(self.engine, self) + def step(self): - """Advances the game forward.""" + """Advances the game forward to the next question. + + This function will check if the game is complete and ensure the + active game state is saved to the database as it's likely the game + state was mutated before this function was called. + """ self.current_question += 1 if self.current_question >= len(self.questions): - self._complete_game() + self.__complete_game() if self.save_to_db: sql.active_game.save_game_state(self.engine, self) + def bump_score(self, user_id: int, amount=1): + """Increases the score of a player by an amount. + + :param int user_id: + :param int amount: + """ + + user_score = self.scores.get(str(user_id), 0) + + self.scores[str(user_id)] = user_score + amount + self.correct_answers_total += 1 + def check_answer(self, answer: str, ratio=0.8) -> bool: """Checks an answer for correctness. @@ -152,23 +170,12 @@ def check_answer(self, answer: str, ratio=0.8) -> bool: question = self.get_question() for correct_answer in question["answers"]: - answer_ratio = cho_utils.levenshtein_ratio(answer, correct_answer) + answer_ratio = utils.levenshtein_ratio(answer, correct_answer) if answer_ratio >= ratio: return True return False - def bump_score(self, user_id: int, amount=1): - """Increases the score of a player by an amount. - - :param int user_id: - :param int amount: - """ - - user_score = self.scores.get(str(user_id), 0) - self.scores[str(user_id)] = user_score + amount - self.correct_answers_total += 1 - def get_question(self) -> dict: """Returns the current question.""" diff --git a/cho_client.py b/lorewalker_cho.py similarity index 83% rename from cho_client.py rename to lorewalker_cho.py index b562f55..ed12878 100644 --- a/cho_client.py +++ b/lorewalker_cho.py @@ -19,21 +19,23 @@ import asyncio import logging import traceback + +from commands import CommandsMixin + import discord from discord.message import Message from sqlalchemy.engine import Engine -import cho_utils +import utils import sql.guild -from cho_commands import ChoCommandsMixin -from cho_game import ChoGameMixin +from game import GameMixin LOGGER = logging.getLogger("cho") -class ChoClient(ChoCommandsMixin, ChoGameMixin, discord.Client): +class LorewalkerCho(CommandsMixin, GameMixin, discord.Client): """Discord client wrapper that uses functionality from cho.py.""" def __init__(self, engine: Engine): @@ -96,13 +98,13 @@ async def on_message(self, message: Message): results = sql.guild.get_guild(self.engine, guild_id) if results: _, config = results - prefix = cho_utils.get_prefix(config) + prefix = utils.get_prefix(config) else: - prefix = cho_utils.get_prefix(None) + prefix = utils.get_prefix(None) - if cho_utils.is_command(message, prefix): + if utils.is_command(message, prefix): await self.handle_command(message) - elif self._is_game_in_progress(guild_id): + elif self.is_game_in_progress(guild_id): await self.handle_message_response(message) async def on_error(self, event_name, *args, **kwargs): @@ -146,13 +148,13 @@ async def handle_command(self, message): command = args[1].lower() # Process commands that are marked for global usage. - for global_command, func in cho_utils.GLOBAL_COMMANDS.items(): + for global_command, func in utils.GLOBAL_COMMANDS.items(): if global_command == command: await func(self, message, args, config) return # Anything not handled above must be done in the configured channel. - if not cho_utils.is_message_from_trivia_channel(message, config): + if not utils.is_message_from_trivia_channel(message, config): await message.channel.send( "Sorry, I can't be summoned into this channel. Please go " "to the trivia channel for this server." @@ -160,7 +162,7 @@ async def handle_command(self, message): return # Process commands that are marked for channel-only usage. - for channel_command, func in cho_utils.CHANNEL_COMMANDS.items(): + for channel_command, func in utils.CHANNEL_COMMANDS.items(): if channel_command == command: await func(self, message, args, config) return @@ -169,3 +171,21 @@ async def handle_command(self, message): "I'm afraid I don't know that command. If you want to " "start a game use the \"start\" command." ) + + async def handle_message_response(self, message: Message): + """Processes a non-command message received during an active game. + + :param m message: + :type m: discord.message.Message + """ + + guild_id = guild_id = message.guild.id + + guild_query_results = sql.guild.get_guild(self.engine, guild_id) + if guild_query_results: + _, config = guild_query_results + else: + config = {} + + if utils.is_message_from_trivia_channel(message, config): + await self.process_answer(message) diff --git a/main.py b/main.py index 969e618..3954a44 100755 --- a/main.py +++ b/main.py @@ -24,7 +24,7 @@ import sqlalchemy as sa import config -from cho_client import ChoClient +from lorewalker_cho import LorewalkerCho DISCORD_TOKEN = os.environ["CHO_DISCORD_TOKEN"] SQLALCHEMY_POOL_SIZE = int(os.environ.get("SQLALCHEMY_POOL_SIZE", 6)) @@ -58,7 +58,7 @@ def main(): engine.connect() LOGGER.info("Started connection pool with size: %d", SQLALCHEMY_POOL_SIZE) - discord_client = ChoClient(engine) + discord_client = LorewalkerCho(engine) discord_client.run(DISCORD_TOKEN) LOGGER.info("Shutting down... good bye!") diff --git a/sql/active_game.py b/sql/active_game.py index b331410..b24922e 100644 --- a/sql/active_game.py +++ b/sql/active_game.py @@ -22,7 +22,7 @@ from sqlalchemy.engine.interfaces import Connectable from sqlalchemy.engine.result import ResultProxy -from sql.schema import guilds, active_games +from sql.schema import GUILDS, ACTIVE_GAMES LOGGER = logging.getLogger("cho") @@ -36,11 +36,11 @@ def get_incomplete_games(conn: Connectable) -> list: :return: """ - query = sa.select([guilds.c.discord_guild_id, active_games.c.game_state]) \ + query = sa.select([GUILDS.c.discord_guild_id, ACTIVE_GAMES.c.game_state]) \ .select_from( - sa.join(active_games, guilds, - active_games.c.guild_id == guilds.c.id)) \ - .where(active_games.c.game_state['complete'] == "false") + sa.join(ACTIVE_GAMES, GUILDS, + ACTIVE_GAMES.c.guild_id == GUILDS.c.id)) \ + .where(ACTIVE_GAMES.c.game_state['complete'] == "false") return conn.execute(query).fetchall() @@ -54,13 +54,13 @@ def get_game_state(conn: Connectable, guild_id: int) -> tuple: :return: """ - query = sa.select([guilds.c.id]) \ - .where(guilds.c.discord_guild_id == guild_id) \ + query = sa.select([GUILDS.c.id]) \ + .where(GUILDS.c.discord_guild_id == guild_id) \ .limit(1) guild_id_fkey = conn.execute(query).first() - query = sa.select([active_games.c.game_state]) \ - .where(active_games.c.guild_id == guild_id_fkey[0]) \ + query = sa.select([ACTIVE_GAMES.c.game_state]) \ + .where(ACTIVE_GAMES.c.guild_id == guild_id_fkey[0]) \ .limit(1) return conn.execute(query).first() @@ -77,27 +77,27 @@ def save_game_state(conn: Connectable, game_state) -> ResultProxy: :return: """ - query = sa.select([guilds.c.id]) \ - .where(guilds.c.discord_guild_id == game_state.guild_id) \ + query = sa.select([GUILDS.c.id]) \ + .where(GUILDS.c.discord_guild_id == game_state.guild_id) \ .limit(1) guild_id_fkey = conn.execute(query).first() - query = sa.select([active_games.c.id]) \ - .where(active_games.c.guild_id == guild_id_fkey[0]) \ + query = sa.select([ACTIVE_GAMES.c.id]) \ + .where(ACTIVE_GAMES.c.guild_id == guild_id_fkey[0]) \ .limit(1) existing_game_id = conn.execute(query).first() if existing_game_id is not None: LOGGER.debug("Updating existing game state.") - query = active_games.update(None).values({ + query = ACTIVE_GAMES.update(None).values({ "game_state": game_state.serialize(), - }).where(active_games.c.id == existing_game_id[0]) + }).where(ACTIVE_GAMES.c.id == existing_game_id[0]) return conn.execute(query) else: LOGGER.debug("Creating new game state.") - query = active_games.insert(None).values({ + query = ACTIVE_GAMES.insert(None).values({ "guild_id": guild_id_fkey[0], "game_state": game_state.serialize(), }) @@ -115,11 +115,11 @@ def clear_game_state(conn: Connectable, guild_id: int) -> ResultProxy: :return: """ - query = sa.select([guilds.c.id]) \ - .where(guilds.c.discord_guild_id == guild_id) \ + query = sa.select([GUILDS.c.id]) \ + .where(GUILDS.c.discord_guild_id == guild_id) \ .limit(1) guild_id_fkey = conn.execute(query).first() - query = active_games.delete(None) \ - .where(active_games.c.guild_id == guild_id_fkey[0]) + query = ACTIVE_GAMES.delete(None) \ + .where(ACTIVE_GAMES.c.guild_id == guild_id_fkey[0]) return conn.execute(query) diff --git a/sql/guild.py b/sql/guild.py index 3ffe427..e95bdca 100644 --- a/sql/guild.py +++ b/sql/guild.py @@ -20,7 +20,7 @@ from sqlalchemy.engine.interfaces import Connectable from sqlalchemy.engine.result import ResultProxy -from sql.schema import guilds +from sql.schema import GUILDS def get_guild(conn: Connectable, guild_id: int) -> tuple: @@ -33,8 +33,8 @@ def get_guild(conn: Connectable, guild_id: int) -> tuple: :return: """ - query = sa.select([guilds.c.discord_guild_id, guilds.c.config]) \ - .where(guilds.c.discord_guild_id == guild_id) \ + query = sa.select([GUILDS.c.discord_guild_id, GUILDS.c.config]) \ + .where(GUILDS.c.discord_guild_id == guild_id) \ .limit(1) return conn.execute(query).first() @@ -54,7 +54,7 @@ def create_guild( :return: """ - query = guilds.insert(None).values({ + query = GUILDS.insert(None).values({ "discord_guild_id": guild_id, "config": config or {}, }) @@ -76,7 +76,7 @@ def update_guild_config( :return: """ - query = guilds.update(None).values({ + query = GUILDS.update(None).values({ "config": config or {}, - }).where(guilds.c.discord_guild_id == guild_id) + }).where(GUILDS.c.discord_guild_id == guild_id) return conn.execute(query) diff --git a/sql/schema.py b/sql/schema.py index bebd567..a73cd6c 100644 --- a/sql/schema.py +++ b/sql/schema.py @@ -17,11 +17,11 @@ import sqlalchemy as sa import sqlalchemy.dialects.postgresql as postgresql -metadata = sa.MetaData() +METADATA = sa.MetaData() -guilds = sa.Table( +GUILDS = sa.Table( "guilds", - metadata, + METADATA, sa.Column("id", sa.BigInteger, primary_key=True), sa.Column("discord_guild_id", sa.BigInteger, nullable=False), sa.Column("config", postgresql.JSONB(), nullable=False), @@ -32,9 +32,9 @@ ), ) -active_games = sa.Table( +ACTIVE_GAMES = sa.Table( "active_games", - metadata, + METADATA, sa.Column("id", sa.BigInteger, primary_key=True), sa.Column("guild_id", sa.BigInteger, nullable=False), sa.Column("game_state", postgresql.JSONB(), nullable=False), @@ -46,9 +46,9 @@ sa.Index("active_games_guild_id_idx", "guild_id", unique=True), ) -scoreboards = sa.Table( +SCOREBOARDS = sa.Table( "scoreboards", - metadata, + METADATA, sa.Column("id", sa.BigInteger, primary_key=True), sa.Column("guild_id", sa.BigInteger, nullable=False), sa.Column("scores", postgresql.JSONB(), nullable=False), diff --git a/sql/scoreboard.py b/sql/scoreboard.py index 0e3637b..b451c78 100644 --- a/sql/scoreboard.py +++ b/sql/scoreboard.py @@ -22,7 +22,7 @@ from sqlalchemy.engine.interfaces import Connectable from sqlalchemy.engine.result import ResultProxy -from sql.schema import guilds, scoreboards +from sql.schema import GUILDS, SCOREBOARDS LOGGER = logging.getLogger("cho") @@ -37,13 +37,13 @@ def get_scoreboard(conn: Connectable, guild_id: int) -> tuple: :return: """ - query = sa.select([guilds.c.id]) \ - .where(guilds.c.discord_guild_id == guild_id) \ + query = sa.select([GUILDS.c.id]) \ + .where(GUILDS.c.discord_guild_id == guild_id) \ .limit(1) guild_id_fkey = conn.execute(query).first() - query = sa.select([scoreboards.c.scores]) \ - .where(scoreboards.c.guild_id == guild_id_fkey[0]) \ + query = sa.select([SCOREBOARDS.c.scores]) \ + .where(SCOREBOARDS.c.guild_id == guild_id_fkey[0]) \ .limit(1) return conn.execute(query).first() @@ -60,28 +60,28 @@ def save_scoreboard(conn: Connectable, guild_id: int, scores) -> ResultProxy: :return: """ - query = sa.select([guilds.c.id]) \ - .where(guilds.c.discord_guild_id == guild_id) \ + query = sa.select([GUILDS.c.id]) \ + .where(GUILDS.c.discord_guild_id == guild_id) \ .limit(1) guild_id_fkey = conn.execute(query).first() - query = sa.select([scoreboards.c.id]) \ - .where(scoreboards.c.guild_id == guild_id_fkey[0]) \ + query = sa.select([SCOREBOARDS.c.id]) \ + .where(SCOREBOARDS.c.guild_id == guild_id_fkey[0]) \ .limit(1) existing_scoreboard_id = conn.execute(query).first() if existing_scoreboard_id is not None: LOGGER.debug("Updating existing scoreboard.") - query = scoreboards.update(None).values({ + query = SCOREBOARDS.update(None).values({ "scores": scores or {}, - }).where(scoreboards.c.id == existing_scoreboard_id[0]) + }).where(SCOREBOARDS.c.id == existing_scoreboard_id[0]) return conn.execute(query) - else: - LOGGER.debug("Creating new scoreboard.") - query = scoreboards.insert(None).values({ - "guild_id": guild_id_fkey[0], - "scores": scores or {}, - }) - return conn.execute(query) + LOGGER.debug("Creating new scoreboard.") + + query = SCOREBOARDS.insert(None).values({ + "guild_id": guild_id_fkey[0], + "scores": scores or {}, + }) + return conn.execute(query) diff --git a/cho_utils.py b/utils.py similarity index 100% rename from cho_utils.py rename to utils.py