1 from urllib.parse import parse_qs
2 from slack import WebClient
8 from types import SimpleNamespace
9 from google.auth.transport.requests import Request
10 from googleapiclient.discovery import build
12 import turbot.interaction
15 ssm = boto3.client('ssm')
17 # Note: Late import here to have the environment variable above available
18 from turbot.slack import slack_is_valid_request # noqa
20 response = ssm.get_parameter(Name='SLACK_BOT_TOKEN', WithDecryption=True)
21 slack_bot_token = response['Parameter']['Value']
22 slack_client = WebClient(slack_bot_token)
24 response = ssm.get_parameter(Name='GSHEETS_PICKLE_BASE64', WithDecryption=True)
25 gsheets_pickle_base64 = response['Parameter']['Value']
26 gsheets_pickle = base64.b64decode(gsheets_pickle_base64)
27 gsheets_creds = pickle.loads(gsheets_pickle)
29 if gsheets_creds.valid:
30 print("Loaded valid GSheets credentials from SSM")
32 gsheets_creds.refresh(Request())
33 gsheets_pickle = pickle.dumps(gsheets_creds)
34 gsheets_pickle_base64_bytes = base64.b64encode(gsheets_pickle)
35 gsheets_pickle_base64 = gsheets_pickle_base64_bytes.decode('us-ascii')
36 print("Storing refreshed GSheets credentials into SSM")
37 ssm.put_parameter(Name='GSHEETS_PICKLE_BASE64',
39 Value=gsheets_pickle_base64,
41 service = build('sheets',
43 credentials=gsheets_creds,
44 cache_discovery=False)
45 sheets = service.spreadsheets()
47 db = boto3.resource('dynamodb')
49 turb = SimpleNamespace()
50 turb.slack_client = slack_client
55 """Generate an error response for a Slack request
57 This will print the error message (so that it appears in CloudWatch
58 logs) and will then return a dictionary suitable for returning
59 as an error response."""
61 print("Error: {}.".format(message))
68 def turbot_lambda(event, context):
69 """Top-level entry point for our lambda function.
71 This function first verifies that the request actually came from
72 Slack, (by means of the SLACK_SIGNING_SECRET SSM parameter), and
73 refuses to do anything if not.
75 Then this defers to either turbot_event_handler or
76 turbot_slash_command to do any real work.
79 headers = requests.structures.CaseInsensitiveDict(event['headers'])
81 signature = headers['X-Slack-Signature']
82 timestamp = headers['X-Slack-Request-Timestamp']
84 if not slack_is_valid_request(signature, timestamp, event['body']):
85 return error("Invalid Slack signature")
87 # It's a bit cheesy, but we'll just use the content-type header to
88 # determine if we're being called from a Slack event or from a
89 # slash command or other interactivity. (The more typical way to
90 # do this would be to have different URLs for each Slack entry
91 # point, but it's simpler to have our Slack app implemented as a
92 # single AWS Lambda, (which can only have a single entry point).
93 content_type = headers['content-type']
95 if (content_type == "application/json"):
96 return turbot_event_handler(turb, event, context)
97 if (content_type == "application/x-www-form-urlencoded"):
98 return turbot_interactive_or_slash_command(turb, event, context)
99 return error("Unknown content-type: {}".format(content_type))
101 def turbot_event_handler(turb, event, context):
102 """Handler for all subscribed Slack events"""
104 body = json.loads(event['body'])
108 if type == 'url_verification':
109 return url_verification_handler(turb, body)
110 if type == 'event_callback':
111 return event_callback_handler(turb, body)
112 return error("Unknown event type: {}".format(type))
114 def url_verification_handler(turb, body):
116 # First, we have to properly respond to url_verification
117 # challenges or else Slack won't let us configure our URL as an
119 challenge = body['challenge']
126 def event_callback_handler(turb, body):
127 event = body['event']
130 if type in turbot.events.events:
131 return turbot.events.events[type](turb, event)
132 return error("Unknown event type: {}".format(type))
134 def turbot_interactive_or_slash_command(turb, event, context):
135 """Handler for Slack interactive things (buttons, shortcuts, etc.)
136 as well as slash commands.
138 This function simply makes a quiuck determination of what we're looking
139 at and then defers to either turbot_interactive or turbot_slash_command."""
141 # Both interactives and slash commands have a urlencoded body
142 body = parse_qs(event['body'])
144 # The difference is that an interactive thingy has a 'payload'
145 # while a slash command has a 'command'
146 if 'payload' in body:
147 return turbot_interactive(turb, json.loads(body['payload'][0]))
148 if 'command' in body:
149 return turbot_slash_command(turb, body)
150 return error("Unrecognized event (neither interactive nor slash command)")
152 def turbot_interactive(turb, payload):
153 """Handler for Slack interactive requests
155 These are the things that come from a user interacting with a button
156 a shortcut or some other interactive element that our app has made
157 available to the user."""
159 type = payload['type']
161 if type == 'block_actions':
162 return turbot_block_action(turb, payload)
163 if type == 'view_submission':
164 return turbot.interaction.view_submission(turb, payload)
165 if type == 'shortcut':
166 return turbot_shortcut(turb, payload)
167 return error("Unrecognized interactive type: {}".format(type))
169 def turbot_block_action(turb, payload):
170 """Handler for Slack interactive block actions
172 Specifically, those that have a payload type of 'block_actions'"""
174 actions = payload['actions']
176 if len(actions) != 1:
177 return error("No support for multiple actions ({}) in a single request"
178 .format(len(actions)))
182 atype = action['type']
183 avalue = action['value']
186 atype in turbot.interaction.actions
187 and avalue in turbot.interaction.actions[atype]
189 return turbot.interaction.actions[atype][avalue](turb, payload)
190 return error("Unknown action of type/value: {}/{}".format(atype, avalue))
192 def turbot_shortcut(turb, payload):
193 """Handler for Slack shortcuts
195 These are invoked as either global or message shortcuts by a user."""
197 print("In turbot_shortcut, payload is: {}".format(str(payload)))
199 return error("Shortcut interactions not yet implemented")
201 def turbot_slash_command(turb, body):
202 """Implementation for Slack slash commands.
204 This parses the request and arguments and farms out to
205 supporting functions to implement all supported slash commands.
208 command = body['command'][0]
210 args = body['text'][0]
214 if command in turbot.interaction.commands:
215 return turbot.interaction.commands[command](turb, body, args)
217 return error("Command {} not implemented".format(command))