1 from urllib.parse import parse_qs
2 from slack import WebClient
13 ssm = boto3.client('ssm')
15 response = ssm.get_parameter(Name='SLACK_SIGNING_SECRET', WithDecryption=True)
16 slack_signing_secret = response['Parameter']['Value']
17 os.environ['SLACK_SIGNING_SECRET'] = slack_signing_secret
19 # Note: Late import here to have the environment variable above available
20 from turbot.slack import slack_is_valid_request # noqa
22 response = ssm.get_parameter(Name='SLACK_BOT_TOKEN', WithDecryption=True)
23 slack_bot_token = response['Parameter']['Value']
24 slack_client = WebClient(slack_bot_token)
27 """Generate an error response for a Slack request
29 This will print the error message (so that it appears in CloudWatch
30 logs) and will then return a dictionary suitable for returning
31 as an error response."""
33 print("Error: {}.".format(message))
40 def turbot_lambda(event, context):
41 """Top-level entry point for our lambda function.
43 This function first verifies that the request actually came from
44 Slack, (by means of the SLACK_SIGNING_SECRET SSM parameter), and
45 refuses to do anything if not.
47 Then this defers to either turbot_event_handler or
48 turbot_slash_command to do any real work.
51 headers = requests.structures.CaseInsensitiveDict(event['headers'])
53 signature = headers['X-Slack-Signature']
54 timestamp = headers['X-Slack-Request-Timestamp']
56 if not slack_is_valid_request(signature, timestamp, event['body']):
57 return error("Invalid Slack signature")
59 # It's a bit cheesy, but we'll just use the content-type header to
60 # determine if we're being called from a Slack event or from a
61 # slash command or other interactivity. (The more typical way to
62 # do this would be to have different URLs for each Slack entry
63 # point, but it's simpler to have our Slack app implemented as a
64 # single AWS Lambda, (which can only have a single entry point).
65 content_type = headers['content-type']
67 if (content_type == "application/json"):
68 return turbot_event_handler(event, context)
69 if (content_type == "application/x-www-form-urlencoded"):
70 return turbot_interactive_or_slash_command(event, context)
71 return error("Unknown content-type: {}".format(content_type))
73 def turbot_event_handler(event, context):
74 """Handler for all subscribed Slack events"""
76 body = json.loads(event['body'])
80 if type == 'url_verification':
81 return url_verification_handler(body)
82 if type == 'event_callback':
83 return event_callback_handler(body)
84 return error("Unknown event type: {}".format(type))
86 def url_verification_handler(body):
88 # First, we have to properly respond to url_verification
89 # challenges or else Slack won't let us configure our URL as an
91 challenge = body['challenge']
98 def event_callback_handler(body):
99 type = body['event']['type']
101 if type == 'app_home_opened':
102 return turbot.events.app_home_opened(slack_client, body)
103 return error("Unknown event type: {}".format(type))
105 def turbot_interactive_or_slash_command(event, context):
106 """Handler for Slack interactive things (buttons, shortcuts, etc.)
107 as well as slash commands.
109 This function simply makes a quiuck determination of what we're looking
110 at and then defers to either turbot_interactive or turbot_slash_command."""
112 # Both interactives and slash commands have a urlencoded body
113 body = parse_qs(event['body'])
115 # The difference is that an interactive thingy has a 'payload'
116 # while a slash command has a 'command'
117 if 'payload' in body:
118 return turbot_interactive(json.loads(body['payload'][0]))
119 if 'command' in body:
120 return turbot_slash_command(body)
121 return error("Unrecognized event (neither interactive nor slash command)")
123 def turbot_interactive(payload):
124 """Handler for Slack interactive requests
126 These are the things that come from a user interacting with a button
127 a shortcut or some other interactive element that our app has made
128 available to the user."""
130 type = payload['type']
132 if type == 'block_actions':
133 return turbot_block_action(payload)
134 return error("Unrecognized interactive type: {}".format(type))
136 def turbot_block_action(payload):
137 """Handler for Slack interactive block actions
139 Specifically, those that have a payload type of 'block_actions'"""
141 actions = payload['actions']
143 if len(actions) != 1:
144 return error("No support for multiple actions ({}) in a single request"
145 .format(len(actions)))
149 atype = action['type']
150 avalue = action['value']
153 atype in turbot.actions.actions
154 and avalue in turbot.actions.actions[atype]
156 return turbot.actions.actions[atype][avalue](payload)
157 return error("Unknown action of type/value: {}/{}".format(atype, avalue))
159 def turbot_slash_command(body):
160 """Implementation for Slack slash commands.
162 This parses the request and arguments and farms out to
163 supporting functions to implement all supported slash commands.
166 command = body['command'][0]
167 args = body['text'][0]
169 if command in turbot.commands.commands:
170 return turbot.commands.commands[command](slack_client, body, args)
172 return error("Command {} not implemented".format(command))