]> git.cworth.org Git - turbot/blobdiff - turbot/interaction.py
Make the /solved command report to the hunt's channel
[turbot] / turbot / interaction.py
index 4606449edca9921850fd6473b7ced5f9a55f77d0..d2514e5d6543878b58483e582eea381db24e3313 100644 (file)
@@ -1,16 +1,61 @@
-from turbot.blocks import input_block
+from slack.errors import SlackApiError
+from turbot.blocks import input_block, section_block, text_block
+import turbot.rot
 import turbot.sheets
+import turbot.slack
 import json
 import re
 import requests
-import turbot.rot
+from botocore.exceptions import ClientError
+from turbot.slack import slack_send_message
+
+actions = {}
+commands = {}
+submission_handlers = {}
+
+# Hunt/Puzzle IDs are restricted to lowercase letters, numbers, and underscores
+valid_id_re = r'^[_a-z0-9]+$'
+
+lambda_ok = {'statusCode': 200}
+
+def bot_reply(message):
+    """Construct a return value suitable for a bot reply
+
+    This is suitable as a way to give an error back to the user who
+    initiated a slash command, for example."""
+
+    return {
+        'statusCode': 200,
+        'body': message
+    }
+
+def submission_error(field, error):
+    """Construct an error suitable for returning for an invalid submission.
+
+    Returning this value will prevent a submission and alert the user that
+    the given field is invalid because of the given error."""
+
+    print("Rejecting invalid modal submission: {}".format(error))
+
+    return {
+        'statusCode': 200,
+        'headers': {
+            "Content-Type": "application/json"
+        },
+        'body': json.dumps({
+            "response_action": "errors",
+            "errors": {
+                field: error
+            }
+        })
+    }
 
 def new_hunt(turb, payload):
     """Handler for the action of user pressing the new_hunt button"""
 
     view = {
         "type": "modal",
-        "private_metadata": "new_hunt",
+        "private_metadata": json.dumps({}),
         "title": { "type": "plain_text", "text": "New Hunt" },
         "submit": { "type": "plain_text", "text": "Create" },
         "blocks": [
@@ -28,89 +73,93 @@ def new_hunt(turb, payload):
     if (result['ok']):
         submission_handlers[result['view']['id']] = new_hunt_submission
 
-    return {
-        'statusCode': 200,
-        'body': 'OK'
-    }
+    return lambda_ok
 
-def new_hunt_submission(turb, payload):
+actions['button'] = {"new_hunt": new_hunt}
+
+def new_hunt_submission(turb, payload, metadata):
     """Handler for the user submitting the new hunt modal
 
     This is the modal view presented to the user by the new_hunt
     function above."""
 
     state = payload['view']['state']['values']
+    user_id = payload['user']['id']
     name = state['name']['name']['value']
     hunt_id = state['hunt_id']['hunt_id']['value']
     url = state['url']['url']['value']
 
     # Validate that the hunt_id contains no invalid characters
-    if not re.match(r'[_a-zA-Z0-9]+$', hunt_id):
-        print("Hunt ID field is invalid. Attmpting to return a clean error.")
-        return {
-            'statusCode': 200,
-            'headers': {
-                "Content-Type": "application/json"
-            },
-            'body': json.dumps({
-                "response_action": "errors",
-                "errors": {
-                    "hunt_id": "Hunt ID can only contain letters, "
-                    + "numbers, and underscores"
-                }
-            })
-        }
+    if not re.match(valid_id_re, hunt_id):
+        return submission_error("hunt_id",
+                                "Hunt ID can only contain lowercase letters, "
+                                + "numbers, and underscores")
 
-    # Create a channel for the hunt
-    response = turb.slack_client.conversations_create(name=hunt_id)
+    # Check to see if the hunts table exists
+    hunts_table = turb.db.Table("hunts")
 
-    if not response['ok']:
-        print("Error creating channel for hunt {}: {}"
-              .format(name, str(response)))
-        return {
-            'statusCode': 400
-        }
+    try:
+        exists = hunts_table.table_status in ("CREATING", "UPDATING",
+                                              "ACTIVE")
+    except ClientError:
+        exists = False
+
+    # Create the hunts table if necessary.
+    if not exists:
+        hunts_table = turb.db.create_table(
+            TableName='hunts',
+            KeySchema=[
+                {'AttributeName': 'channel_id', 'KeyType': 'HASH'},
+            ],
+            AttributeDefinitions=[
+                {'AttributeName': 'channel_id', 'AttributeType': 'S'},
+            ],
+            ProvisionedThroughput={
+                'ReadCapacityUnits': 5,
+                'WriteCapacityUnits': 5
+            }
+        )
+        return submission_error("hunt_id",
+                                "Still bootstrapping hunts table. Try again.")
 
-    user_id = payload['user']['id']
-    channel_id = response['channel']['id']
+    # Create a channel for the hunt
+    try:
+        response = turb.slack_client.conversations_create(name=hunt_id)
+    except SlackApiError as e:
+        return submission_error("hunt_id",
+                                "Error creating Slack channel: {}"
+                                .format(e.response['error']))
 
-    # Create a sheet for the channel
-    sheet = turbot.sheets.sheets_create(turb, hunt_id)
+    channel_id = response['channel']['id']
 
     # Insert the newly-created hunt into the database
-    hunts_table = turb.db.Table("hunts")
+    # (leaving it as non-active for now until the channel-created handler
+    #  finishes fixing it up with a sheet and a companion table)
     hunts_table.put_item(
         Item={
             'channel_id': channel_id,
-            "active": True,
+            "active": False,
             "name": name,
             "hunt_id": hunt_id,
-            "url": url,
-            "sheet_url": sheet['url']
+            "url": url
         }
     )
 
     # Invite the initiating user to the channel
     turb.slack_client.conversations_invite(channel=channel_id, users=user_id)
 
-    # Message the channel with the URL of the sheet
-    turb.slack_client.chat_postMessage(channel=channel_id,
-                                       text="Sheet created for this hunt: {}"
-                                       .format(sheet['url']))
-
-    return {
-        'statusCode': 200,
-    }
+    return lambda_ok
 
 def view_submission(turb, payload):
     """Handler for Slack interactive view submission
 
     Specifically, those that have a payload type of 'view_submission'"""
 
-    view_id = payload['view']['private_metadata']
+    view_id = payload['view']['id']
+    metadata = payload['view']['private_metadata']
 
     if view_id in submission_handlers:
-        return submission_handlers[view_id](turb, payload)
+        return submission_handlers[view_id](turb, payload, metadata)
 
     print("Error: Unknown view ID: {}".format(view_id))
     return {
@@ -147,17 +196,281 @@ def rot(turb, body, args):
     else:
         turb.slack_client.chat_postMessage(channel=channel_id, text=result)
 
-    return {
-        'statusCode': 200,
-        'body': ""
-    }
+    return lambda_ok
+
+commands["/rot"] = rot
+
+def get_table_item(turb, table_name, key, value):
+    """Get an item from the database 'table_name' with 'key' as 'value'
+
+    Returns a tuple of (item, table) if found and (None, None) otherwise."""
+
+    table = turb.db.Table(table_name)
+
+    response = table.get_item(Key={key: value})
+
+    if 'Item' in response:
+        return (response['Item'], table)
+    else:
+        return (None, None)
+
+def channel_is_puzzle(turb, channel_id, channel_name):
+    """Given a channel ID/name return the database item for the puzzle
+
+    If this channel is a puzzle, this function returns a tuple:
+
+        (puzzle, table)
+
+    Where puzzle is dict filled with database entries, and table is a
+    database table that can be used to update the puzzle in the
+    database.
+
+    Otherwise, this function returns (None, None)."""
+
+    hunt_id = channel_name.split('-')[0]
+
+    # Not a puzzle channel if there is no hyphen in the name
+    if hunt_id == channel_name:
+        return (None, None)
+
+    return get_table_item(turb, hunt_id, 'channel_id', channel_id)
+
+def channel_is_hunt(turb, channel_id):
+
+    """Given a channel ID/name return the database item for the hunt
+
+    Returns a dict (filled with database entries) if there is a hunt
+    for this channel, otherwise returns None."""
+
+    return get_table_item(turb, "hunts", 'channel_id', channel_id)
+
+def find_hunt_for_channel(turb, channel_id, channel_name):
+    """Given a channel ID/name find the id/name of the hunt for this channel
+
+    This works whether the original channel is a primary hunt channel,
+    or if it is one of the channels of a puzzle belonging to the hunt.
+
+    Returns None if channel does not belong to a hunt, otherwise a
+    dictionary with all fields from the hunt's row in the table,
+    (channel_id, active_, hun_id, name, url, sheet_url, etc.).
+
+    """
+
+    (hunt, _) = channel_is_hunt(turb, channel_id)
+
+    if hunt:
+        return hunt
+
+    # So we're not a hunt channel, let's look to see if we are a
+    # puzzle channel with a hunt-id prefix.
+    hunt_id = channel_name.split('-')[0]
+
+    hunts_table = turb.db.Table("hunts")
+
+    response = hunts_table.scan(
+        FilterExpression='hunt_id = :hunt_id',
+        ExpressionAttributeValues={':hunt_id': hunt_id}
+    )
+
+    if 'Items' in response and len(response['Items']):
+        item = response['Items'][0]
+        return item
+
+    return None
+
+def puzzle(turb, body, args):
+    """Implementation of the /puzzle command
+
+    The args string is currently ignored (this command will bring up
+    a modal dialog for user input instead)."""
+
+    channel_id = body['channel_id'][0]
+    channel_name = body['channel_name'][0]
+    trigger_id = body['trigger_id'][0]
+
+    hunt = find_hunt_for_channel(turb,
+                                 channel_id,
+                                 channel_name)
 
-actions = {
-    "button": {
-        "new_hunt": new_hunt
+    if not hunt:
+        return bot_reply("Sorry, this channel doesn't appear to "
+                         + "be a hunt or puzzle channel")
+
+    view = {
+        "type": "modal",
+        "private_metadata": json.dumps({
+            "hunt_id": hunt['hunt_id'],
+        }),
+        "title": {"type": "plain_text", "text": "New Puzzle"},
+        "submit": { "type": "plain_text", "text": "Create" },
+        "blocks": [
+            section_block(text_block("*For {}*".format(hunt['name']))),
+            input_block("Puzzle name", "name", "Name of the puzzle"),
+            input_block("Puzzle URL", "url", "External URL of puzzle",
+                        optional=True)
+        ]
     }
-}
 
-commands = {
-    "/rot": rot
-}
+    result = turb.slack_client.views_open(trigger_id=trigger_id,
+                                          view=view)
+
+    if (result['ok']):
+        submission_handlers[result['view']['id']] = puzzle_submission
+
+    return lambda_ok
+
+commands["/puzzle"] = puzzle
+
+def puzzle_submission(turb, payload, metadata):
+    """Handler for the user submitting the new puzzle modal
+
+    This is the modal view presented to the user by the puzzle function
+    above."""
+
+    meta = json.loads(metadata)
+    hunt_id = meta['hunt_id']
+
+    state = payload['view']['state']['values']
+    name = state['name']['name']['value']
+    url = state['url']['url']['value']
+
+    # Create a Slack-channel-safe puzzle_id
+    puzzle_id = re.sub(r'[^a-zA-Z0-9_]', '', name).lower()
+
+    # Create a channel for the puzzle
+    hunt_dash_channel = "{}-{}".format(hunt_id, puzzle_id)
+
+    try:
+        response = turb.slack_client.conversations_create(
+            name=hunt_dash_channel)
+    except SlackApiError as e:
+        return submission_error(
+            "name",
+            "Error creating Slack channel {}: {}"
+            .format(hunt_dash_channel, e.response['error']))
+
+    puzzle_channel_id = response['channel']['id']
+
+    # Insert the newly-created puzzle into the database
+    table = turb.db.Table(hunt_id)
+    table.put_item(
+        Item={
+            "channel_id": puzzle_channel_id,
+            "orig_channel_name": hunt_dash_channel,
+            "solution": [],
+            "status": 'unsolved',
+            "name": name,
+            "puzzle_id": puzzle_id,
+            "url": url,
+        }
+    )
+
+    return lambda_ok
+
+def rename_channel_to_solved(turb, puzzle):
+    orig_channel_name = puzzle['orig_channel_name']
+    channel_id = puzzle['channel_id']
+    newName = orig_channel_name + '-solved'
+    turb.slack_client.conversations_rename(channel=channel_id,
+                                           name=newName)
+
+# XXX: This duplicates functionality eith events.py:set_channel_description
+def set_channel_topic(turb, puzzle):
+    channel_id = puzzle['channel_id']
+    name = puzzle['name']
+    url = puzzle.get('url', None)
+    sheet_url = puzzle.get('sheet_url', None)
+    state = puzzle.get('state', None)
+    status = puzzle['status']
+
+    description = ''
+
+    if status == 'solved':
+        description += "SOLVED: `{}` ".format('`, `'.join(puzzle['solution']))
+
+    description += name
+
+    links = []
+    if url:
+        links.append("<{}|Puzzle>".format(url))
+    if sheet_url:
+        links.append("<{}|Sheet>".format(sheet_url))
+
+    if len(links):
+        description += "({})".format(', '.join(links))
+
+    if state:
+        description += " {}".format(state)
+
+    turb.slack_client.conversations_setTopic(channel=channel_id,
+                                             topic=description)
+
+def state(turb, body, args):
+    """Implementation of the /state command
+
+    The args string should be a brief sentence describing where things
+    stand or what's needed."""
+
+    channel_id = body['channel_id'][0]
+    channel_name = body['channel_name'][0]
+
+    (puzzle, table) = channel_is_puzzle(turb, channel_id, channel_name)
+
+    if not puzzle:
+        return bot_reply("Sorry, this is not a puzzle channel.")
+
+    # Set the state field in the database
+    puzzle['state'] = args
+    table.put_item(Item=puzzle)
+
+    set_channel_topic(turb, puzzle)
+
+    return lambda_ok
+
+commands["/state"] = state
+
+def solved(turb, body, args):
+    """Implementation of the /solved command
+
+    The args string should be a confirmed solution."""
+
+    channel_id = body['channel_id'][0]
+    channel_name = body['channel_name'][0]
+    user_name = body['user_name'][0]
+
+    (puzzle, table) = channel_is_puzzle(turb, channel_id, channel_name)
+
+    if not puzzle:
+        return bot_reply("Sorry, this is not a puzzle channel.")
+
+    # Set the status and solution fields in the database
+    puzzle['status'] = 'solved'
+    puzzle['solution'].append(args)
+    table.put_item(Item=puzzle)
+
+    # Report the solution to the puzzle's channel
+    slack_send_message(
+        turb.slack_client, channel_id,
+        "Puzzle mark solved by {}: `{}`".format(user_name, args))
+
+    # Also report the solution to the hunt channel
+    (hunt, _) = get_table_item(turb, "hunts", "hunt_id", puzzle['hunt_id'])
+    slack_send_message(
+        turb.slack_client, hunt['channel_id'],
+        "Puzzle '<{}|{}>' has been solved!".format(
+            puzzle['channel_url'],
+            puzzle['name'])
+    )
+
+    # And update the puzzle's description
+    set_channel_topic(turb, puzzle)
+
+    # And rename the sheet to prefix with "SOLVED: "
+    turbot.sheets.renameSheet(turb, puzzle['sheet_url'], 'SOLVED: ' + puzzle['name'])
+
+    # Finally, rename the Slack channel to add the suffix '-solved'
+    rename_channel_to_solved(turb, puzzle)
+
+    return lambda_ok
+
+commands["/solved"] = solved