From 9b570c69c799bc2442d712507474c803f7a571bf Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Thu, 22 Oct 2020 02:37:04 -0700 Subject: [PATCH] Create the hunts table if it doesn't already exist I just realized I was probably missing a necessary index on the hunts table, meaning I need to destroy it ad recreate it. But I don't want to do that manually without any code to capture what I did. And if I'm going to write code, I might as well have that code called implcitly as needed. So that's what's present here, the code necessary to create the hunts table if it doesn't already exist. --- turbot/events.py | 8 ++++++-- turbot/interaction.py | 31 ++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/turbot/events.py b/turbot/events.py index 8cb6d1e..32d061a 100644 --- a/turbot/events.py +++ b/turbot/events.py @@ -22,8 +22,12 @@ def home(turb, user_id, body): The return value is a dictionary suitable to be published to the Slack views_publish API.""" - response = turb.db.Table("hunts").scan() - hunts = response['Items'] + # Behave cleanly if there is not hunts table at all yet. + try: + response = turb.db.Table("hunts").scan() + hunts = response['Items'] + except: + hunts = [] return { "type": "home", diff --git a/turbot/interaction.py b/turbot/interaction.py index 947a01f..f634cbc 100644 --- a/turbot/interaction.py +++ b/turbot/interaction.py @@ -6,6 +6,7 @@ import turbot.slack import json import re import requests +from botocore.exceptions import ClientError TURBOT_USER_ID = 'U01B9QM4P9R' @@ -95,6 +96,33 @@ def new_hunt_submission(turb, payload, metadata): "Hunt ID can only contain letters, " + "numbers, and underscores") + # Check to see if the hunts table exists + hunts_table = turb.db.Table("hunts") + + 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.") + # Create a channel for the hunt try: response = turb.slack_client.conversations_create(name=hunt_id) @@ -114,8 +142,9 @@ def new_hunt_submission(turb, payload, metadata): # 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") hunts_table.put_item( Item={ 'channel_id': channel_id, -- 2.45.2