]> git.cworth.org Git - turbot/blob - turbot_lambda/turbot_lambda.py
turbot_lambda: Inject /rot response into the same channel as the command
[turbot] / turbot_lambda / turbot_lambda.py
1 from urllib.parse import parse_qs
2 from turbot.rot import rot
3 from slack import WebClient
4 import boto3
5 import requests
6
7 ssm = boto3.client('ssm')
8 response = ssm.get_parameter(Name='SLACK_BOT_TOKEN', WithDecryption=True)
9 slack_bot_token = response['Parameter']['Value']
10 slack_client = WebClient(slack_bot_token)
11
12 def turbot_lambda(event, context):
13     """Top-level entry point for our lambda function.
14
15     This parses the request and arguments and farms out to supporting
16     functions to implement all supported slash commands."""
17
18     body = parse_qs(event['body'])
19     command = body['command'][0]
20     args = body['text'][0]
21
22     if (command == "/rotlambda" or command == "/rot"):
23         return rot_slash_command(body, args)
24
25     error = "Command {} not implemented.".format(command)
26
27     print("Error: {}".format(error))
28
29     return {
30         'statusCode': 404,
31         'body': error
32     }
33
34 def rot_slash_command(body, args):
35     """Implementation of the /rot command
36
37     The args string should be as follows:
38
39         [count|*] String to be rotated
40
41     That is, the first word of the string is an optional number (or
42     the character '*'). If this is a number it indicates an amount to
43     rotate each character in the string. If the count is '*' or is not
44     present, then the string will be rotated through all possible 25
45     values.
46
47     The result of the rotation is returned (with Slack formatting) in
48     the body of the response so that Slack will provide it as a reply
49     to the user who submitted the slash command."""
50
51     channel_name = body['channel_name'][0]
52     response_url = body['response_url'][0]
53     channel_id = body['channel_id'][0]
54
55     result = rot(args)
56
57     if (channel_name == "directmessage"):
58         requests.post(response_url,
59                       json = {"text": result},
60                       headers = {"Content-type": "application/json"})
61     else:
62         slack_client.chat_postMessage(channel=channel_id, text=result)
63
64     return {
65         'statusCode': 200,
66         'body': ""
67     }