]> git.cworth.org Git - turbot/blob - lambda/lambda_function.py
fe545b8eed418176f9f877877991144eeb8de825
[turbot] / lambda / lambda_function.py
1 import re
2
3 def rot_string(str, n=13):
4     """Return a rotated version of a string
5
6     Specifically, this functions returns a version of the input string
7     where each uppercase letter has been advanced 'n' positions in the
8     alphabet (wrapping around). Lowercase letters and any non-alphabetic
9     characters will be unchanged."""
10
11     result = ''
12     for letter in str:
13         if letter.isupper():
14             result += chr(ord("A") + (ord(letter) - ord("A") + n) % 26)
15         else:
16             result += letter
17     return result
18
19 def rot(args):
20     """Implements logic for /rot slash command in Slack, returning a string
21
22     This implements the /rot command of our Slack bot. The format of this
23     command is as follows:
24
25         /rot [count|*] String to be rotated
26
27     The optional count indicates an amount to rotate each character in the
28     string. If the count is '*' or is not present, then the string will
29     be rotated through all possible 25 values.
30
31     The result of the rotation is returned as a string (with Slack
32     formatting)."""
33
34     match = re.match(r'^([0-9]+|\*) (.*)$', args)
35     if (match):
36         try:
37             count = int(match.group(1))
38         except ValueError:
39             count = None
40         text = match.group(2)
41     else:
42         count = None
43         text = args
44
45     text = text.upper()
46
47     reply = "```/rot {} {}\n".format(count if count else '*', text)
48
49     if count:
50         reply += rot_string(text, count)
51     else:
52         reply += "\n".join(["{:02d} ".format(count) + rot_string(text, count)
53                             for count in range(1, 26)])
54
55     reply += "```"
56
57     return reply
58
59 def lambda_handler(event, context):
60     """Top-level entry point for our lambda function.
61
62     Currently only calls into the rot() function but may become more
63     sophisticated later on."""
64
65     result = rot(event['args'])
66
67     return {
68         'statusCode': 200,
69         'body': result
70     }