]> git.cworth.org Git - turbot/blobdiff - turbot/events.py
Limit Turbot home display to hunts a user belongs to
[turbot] / turbot / events.py
index 32d061ab1bb62da91655891beb9c626d7859d6c4..1b15f0cdd32b918c141ab13466b74a0de208c8d8 100644 (file)
 from turbot.blocks import (
-    section_block, text_block, button_block, actions_block
+    section_block, text_block, button_block, actions_block, divider_block
 )
+import turbot.sheets
+import turbot.slack
+from turbot.slack import slack_send_message, slack_channel_members
 
-def hunt_block(hunt):
+TURBOT_USER_ID = 'U01B9QM4P9R'
+
+events = {}
+
+lambda_success = {'statusCode': 200}
+lambda_error = {'statusCode': 400}
+
+def channel_url(channel_id):
+    return "https://halibutthatbass.slack.com/archives/{}".format(channel_id)
+
+def puzzle_block(puzzle):
+    name = puzzle['name']
+    status = puzzle['status']
+    solution = puzzle['solution']
+    channel_id = puzzle['channel_id']
+    url = puzzle.get('url', None)
+    sheet_url = puzzle.get('sheet_url', None)
+    state = puzzle.get('state', None)
+    status_emoji = ''
+    solution_str = ''
+
+    if status == 'solved':
+        status_emoji = ":ballot_box_with_check:"
+    else:
+        status_emoji = ":white_square:"
+
+    if len(solution):
+        solution_str = "*`" + '`, `'.join(solution) + "`*"
+
+    links = []
+    if url:
+        links.append("<{}|Puzzle>".format(url))
+    if sheet_url:
+        links.append("<{}|Sheet>".format(sheet_url))
+
+    state_str = ''
+    if state:
+        state_str = "\n{}".format(state)
+
+    puzzle_text = "{}{} <{}|{}> ({}){}".format(
+        status_emoji, solution_str,
+        channel_url(channel_id), name,
+        ', '.join(links), state_str
+    )
+
+    return section_block(text_block(puzzle_text))
+
+def hunt_block(turb, hunt):
     name = hunt['name']
+    hunt_id = hunt['hunt_id']
     channel_id = hunt['channel_id']
 
-    text = "{}: ".format(name)
+    response = turb.db.Table(hunt_id).scan()
+    puzzles = response['Items']
 
-    if (channel_id.startswith("placeholder-")):
-        text += "[Slack channel is still being created. Please wait.]"
-    else:
-        text += "<#{}>".format(channel_id)
+    hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
 
-    return section_block(text_block(text))
+    return [
+        section_block(text_block(hunt_text)),
+        *[puzzle_block(puzzle) for puzzle in puzzles],
+        divider_block()
+    ]
 
-def home(turb, user_id, body):
+def home(turb, user_id):
     """Returns a view to be published as the turbot home tab for user_id
 
-    The body argument is a dictionary as provided by the Slack request.
     The return value is a dictionary suitable to be published to the
     Slack views_publish API."""
 
-    # Behave cleanly if there is not hunts table at all yet.
+    # Behave cleanly if there is no hunts table at all yet.
     try:
         response = turb.db.Table("hunts").scan()
         hunts = response['Items']
-    except:
+    except Exception:
         hunts = []
 
+    hunt_blocks = []
+    for hunt in hunts:
+        if not hunt['active']:
+            continue
+        if user_id not in slack_channel_members(turb.slack_client,
+                                                hunt['channel_id']):
+            continue
+        hunt_blocks += hunt_block(turb, hunt)
+
     return {
         "type": "home",
         "blocks": [
-            section_block(text_block("*Active hunts*")),
-            *[hunt_block(hunt) for hunt in hunts if hunt['active']],
+            section_block(text_block("*Hunts you belong to*")),
+            divider_block(),
+            * hunt_blocks,
             actions_block(button_block("New hunt", "new_hunt"))
         ]
     }
 
-def app_home_opened(turb, body):
-    user_id = body['event']['user']
-    view = home(turb, user_id, body)
+def app_home_opened(turb, event):
+    """Handler for the app_home_opened event
+
+    This event occurs when a user visits the home tab for the turbot app.
+    In response to this event we need to publish a view for the user."""
+
+    user_id = event['user']
+    view = home(turb, user_id)
     turb.slack_client.views_publish(user_id=user_id, view=view)
-    return "OK"
+    return lambda_success
+
+events['app_home_opened'] = app_home_opened
+
+def hunt_channel_created(turb, channel_name, channel_id):
+    """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
+
+    # First see if we can find an entry for this hunt in the database.
+    # If not, simply return an error and let Slack retry
+    hunts_table = turb.db.Table("hunts")
+    response = hunts_table.get_item(
+        Key={'channel_id': channel_id},
+        ConsistentRead=True
+    )
+    if 'Item' not in response:
+        print("Warning: Cannot find channel_id {} in hunts table. "
+              .format(channel_id) + "Letting Slack retry this event")
+        return lambda_error
+
+    item = response['Item']
+
+    if 'sheet_url' in item:
+        print("Info: channel_id {} already has sheet_url {}. Exiting."
+              .format(channel_id, item['sheet_url']))
+        return lambda_success
+
+    # Remove any None items from our item before updating
+    if not item['url']:
+        del item['url']
+
+    # Before launching into sheet creation, indicate that we're doing this
+    # in the database. This way, if we take too long to create the sheet
+    # and Slack retries the event, that next event will see this 'pending'
+    # string and cleanly return (eliminating all future retries).
+    item['sheet_url'] = 'pending'
+    hunts_table.put_item(Item=item)
+
+    # Also, let the channel users know what we are up to
+    slack_send_message(
+        turb.slack_client, channel_id,
+        "Welcome to the channel for the {} hunt! ".format(item['name'])
+        + "Please wait a minute or two while I create some backend resources.")
+
+    # Create a sheet for the hunt
+    sheet = turbot.sheets.sheets_create(turb, item['name'])
+
+    # Update the database with the URL of the sheet
+    item['sheet_url'] = sheet['url']
+    hunts_table.put_item(Item=item)
+
+    # Message the channel with the URL of the sheet
+    slack_send_message(turb.slack_client, channel_id,
+                       "Sheet created for this hunt: {}".format(sheet['url']))
+
+    # Create a database table for this hunt's puzzles
+    table = turb.db.create_table(
+        TableName=channel_name,
+        KeySchema=[
+            {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
+        ],
+        AttributeDefinitions=[
+            {'AttributeName': 'channel_id', 'AttributeType': 'S'}
+        ],
+        ProvisionedThroughput={
+            'ReadCapacityUnits': 5,
+            'WriteCapacityUnits': 5
+        }
+    )
+
+    # Wait until the table exists
+    table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
+
+    # Mark the hunt as active in the database
+    item['active'] = True
+    hunts_table.put_item(Item=item)
+
+    # Message the hunt channel that the database is ready
+    slack_send_message(
+        turb.slack_client, channel_id,
+        "Thank you for waiting. This hunt is now ready to begin! "
+        + "Use `/puzzle` to create puzzles for the hunt.")
+
+    return lambda_success
+
+def set_channel_description(turb, puzzle):
+    channel_id = puzzle['channel_id']
+    description = puzzle['name']
+    url = puzzle.get('url', None)
+    sheet_url = puzzle.get('sheet_url', None)
+
+    links = []
+    if url:
+        links.append("<{}|Puzzle>".format(url))
+    if sheet_url:
+        links.append("<{}|Sheet>".format(sheet_url))
+
+    if len(links):
+        description += "({})".format(', '.join(links))
+
+    turb.slack_client.conversations_setPurpose(channel=channel_id,
+                                               purpose=description)
+    turb.slack_client.conversations_setTopic(channel=channel_id,
+                                             topic=description)
+
+def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
+    """Creates sheet and invites user for a newly-created puzzle channel"""
+
+    hunt_id = puzzle_channel_name.split('-')[0]
+
+    # First see if we can find an entry for this puzzle in the database.
+    # If not, simply return an error and let Slack retry
+    puzzle_table = turb.db.Table(hunt_id)
+    response = puzzle_table.get_item(
+        Key={'channel_id': puzzle_channel_id},
+        ConsistentRead=True
+    )
+    if 'Item' not in response:
+        print("Warning: Cannot find channel_id {} in {} table. "
+              .format(puzzle_channel_id, hunt_id)
+              + "Letting Slack retry this event")
+        return lambda_error
+
+    item = response['Item']
+
+    if 'sheet_url' in item:
+        print("Info: channel_id {} already has sheet_url {}. Exiting."
+              .format(puzzle_channel_id, item['sheet_url']))
+        return lambda_success
+
+    # Remove any None items from our item before updating
+    if not item['url']:
+        del item['url']
+
+    # Before launching into sheet creation, indicate that we're doing this
+    # in the database. This way, if we take too long to create the sheet
+    # and Slack retries the event, that next event will see this 'pending'
+    # string and cleanly return (eliminating all future retries).
+    item['sheet_url'] = 'pending'
+    item['channel_url'] = channel_url(puzzle_channel_id)
+    puzzle_table.put_item(Item=item)
+
+    # Create a sheet for the puzzle
+    sheet = turbot.sheets.sheets_create_for_puzzle(turb, item)
+
+    # Update the database with the URL of the sheet
+    item['sheet_url'] = sheet['url']
+    puzzle_table.put_item(Item=item)
+
+    # Get the new sheet_url into the channel description
+    set_channel_description(turb, item)
+
+    # Finally, lookup and invite all users from this hunt to this new puzzle
+    hunts_table = turb.db.Table('hunts')
+    response = hunts_table.scan(
+        FilterExpression='hunt_id = :hunt_id',
+        ExpressionAttributeValues={':hunt_id': hunt_id}
+    )
+
+    if 'Items' in response:
+
+        hunt_channel_id = response['Items'][0]['channel_id']
+
+        # Find all members of the hunt channel
+        members = turbot.slack.slack_channel_members(turb.slack_client,
+                                                     hunt_channel_id)
+
+        # Filter out Turbot's own ID to avoid inviting itself
+        members = [m for m in members if m != TURBOT_USER_ID]
+
+        slack_send_message(
+            turb.slack_client, puzzle_channel_id,
+            "Inviting all members from the hunt channel:  {}"
+            .format(hunt_id))
+
+        # Invite those members to the puzzle channel (in chunks of 500)
+        cursor = 0
+        while cursor < len(members):
+            turb.slack_client.conversations_invite(
+                channel=puzzle_channel_id,
+                users=members[cursor:cursor + 500])
+            cursor += 500
+
+    return lambda_success
+
+def channel_created(turb, event):
+    print("In channel_created with event: {}".format(str(event)))
+
+    channel = event['channel']
+    channel_id = channel['id']
+    channel_name = channel['name']
+    creator = channel['creator']
+
+    # Ignore any channels that turbot didn't create
+    if creator != TURBOT_USER_ID:
+        print("channel_created: Not a turbot-created channel. Exiting.")
+        return lambda_success
+
+    # The presence of a hyphen determines whether this is a puzzle
+    # channel or a hunt channel.
+    if '-' in channel_name:
+        return puzzle_channel_created(turb, channel_name, channel_id)
+    else:
+        return hunt_channel_created(turb, channel_name, channel_id)
 
-events = {
-    "app_home_opened": app_home_opened
-}
+events['channel_created'] = channel_created