コード例 #1
0
def StartGame(msid, sms_from, body_of_sms):
    """Locks-in the table assignments and updates each player's database to record
    the event of these players being at the same table.
    """
    logger.info("Start game night function entered.")
    logger.debug(pprint_dicts(TABLE_ASSIGNED))
    for player in TONIGHTS_PLAYERS:
        logger.debug(player)
        # set players tablename
        players_database[player][CURRENT_TABLE_ASSIGNMENT] = TABLE_ASSIGNED[
            player]
        # Notify players by text of their table assignments.
        sms_text = f"SpeedTrivia suggests you sit at table: {TABLE_ASSIGNED[player]}"
        if TESTING == True:
            logger.info(f'Update: "{sms_text}" NOT SENT to {player}.')
        else:
            Send_SMS(sms_text, player)
            logger.info(f'"{sms_text}" sent to {player}')
        time.sleep(
            0.02)  # for delay between SMS messages (probably not needed)
        # add other players from table to history list
        for teammate in least_meetups[TABLE_ASSIGNED[player]]:
            if teammate == player:
                pass
            else:
                logger.debug(f"Adding : {teammate} to {player}")
                players_database[player][PARTNER_HISTORY].append(teammate)
                # TODO consider if this should be a database with teammates and dates.
                # for now it just a list with duplicates.
    return "Players have been notified."
コード例 #2
0
 def Total_number_of_meetups(table_dict):
     """Return a total number of times any player has played against
     any other player at their table.
     """
     Total_collisions = 0
     # loop through tables
     logger.debug(pprint_dicts(table_dict))
     for table in table_dict.keys():
         table_collisions = 0
         logger.debug(str(table))
         # loop through players at that table
         for player in table_dict[table]:
             logger.debug(player)
             # look at their history for players at their table tonight.
             for prev in players_database[player][PARTNER_HISTORY]:
                 if prev in table_dict[table]:
                     table_collisions += 1
                     Total_collisions += 1
                     # increment the total counter for each collision
         logger.debug(f"Table collisions: {table_collisions}")
     logger.debug(f"Player collisions: {Total_collisions}")
     return Total_collisions
コード例 #3
0
def Respond_to(msid, sms_from, body_of_sms):
    """Takes incoming SMS details and determines correct response.

    Args:
        msid (str)): Twilio message ID
        sms_from (str): 12 character phone number
        body_of_sms (str): Actual text os incoming SMS

    Returns:
        str: The string sent back to the caller.
    """
    response = update_caller_database(msid, sms_from, body_of_sms)
    logger.info(pprint_dicts(players_database[sms_from]))
    if (response ==
            "Hello! I don't have your number in my records. Could you please tell me your name?"
        ):
        return response
    elif ("Glad to meet you. Welcome to SpeedTrivia."
          in response):  # new player name has been found and entered.
        return response
    cmnds = COMMANDS.keys()
    # logger.info(cmnds)
    for word in cmnds:
        command_slice = str(body_of_sms).lower()[:len(word)]
        # logger.debug(f'SMS slice from front of text: {command_slice}')
        if word.lower() == command_slice:
            # ALTERNATE APPROACH: Ensure that only whole words are matched.
            # search = word.lower()
            # strn = str(body_of_sms).lower()
            # matches = re.findall(r"\b" + search + r"\b", strn)
            # matches is a list of each match.
            logger.info(f"Found command: {word}")
            # slice off command from front of string
            action_value = body_of_sms[len(word):]
            logger.debug(f"Command action value is: {action_value}")
            logger.debug(f"Attempting to call function: {COMMANDS[word]}")
            if word in CONTROLLER_ONLY_COMMANDS:
                if sms_from == CONTROLLER:
                    response = COMMANDS[word](msid, sms_from, action_value)
                else:
                    logger.info("Command not available to this user.")
                    response = "Sorry, That command is only available to the CONTROLLER of this app."
            else:
                response = COMMANDS[word](msid, sms_from, action_value)
            # break loop here to stop after first command word found.
            break
        else:
            pass
            # logger.debug(f"Did not find '{word}' in '{body_of_sms}'")
    else:
        logger.info("No command words found in this SMS.")
        logger.debug(f"Checking for a trivia answer form in SMS...")
        if TESTING:
            response = "System under test."
            print(
                Check_for_webform_answer_submission(
                    msid,
                    sms_from,
                    body_of_sms,
                    players_database[sms_from][CURRENT_TEAM_NAME],
                    Send=False,
                ))
        else:
            # TODO Ensure that the function below does not fail silently due to bad data in body_of_sms
            response = Check_for_webform_answer_submission(
                msid,
                sms_from,
                body_of_sms,
                players_database[sms_from][CURRENT_TEAM_NAME],
                Send=True,
            )
    return response
コード例 #4
0
 def Proposed_assignments():
     proposed_tables = Assign_Tables(tables, TONIGHTS_PLAYERS)
     logger.info(pprint_dicts(proposed_tables))
     return proposed_tables
コード例 #5
0
# Save a dictionary into a pickle file.
import pickle  # TODO put all of pickle code into seperate .py file and import
from collections import defaultdict
from pathlib import Path
from pprint import pformat as pprint_dicts

from loguru import logger

from ST_common import *

# export commands GetDB() and PutDB()

print(DATABASE_PATHOBJ.name)
if DATABASE_PATHOBJ.exists():
    logger.info("Recovering pickle database...")
    players_database = pickle.load(open(DATABASE_PATHOBJ, "rb"))
else:
    logger.info("Creating new pickle database...")
    pickle.dump(players_database, open(DATABASE_PATHOBJ, "wb"))

print(pprint_dicts(players_database))