]> git.cworth.org Git - turbot/commitdiff
Start implementing code intended to be deployed to AWS Lambda
authorCarl Worth <cworth@cworth.org>
Sun, 11 Oct 2020 17:35:45 +0000 (10:35 -0700)
committerCarl Worth <cworth@cworth.org>
Sun, 11 Oct 2020 17:49:44 +0000 (10:49 -0700)
Here, lambda/rot.py is a copy of the turbot/rot.py code, but massaged
into the calling conventions of AWS Lambda (and without yet any actual
code to integrate with Slack in either direction).

lambda/lambda_function.py [new file with mode: 0644]

diff --git a/lambda/lambda_function.py b/lambda/lambda_function.py
new file mode 100644 (file)
index 0000000..fe545b8
--- /dev/null
@@ -0,0 +1,70 @@
+import re
+
+def rot_string(str, n=13):
+    """Return a rotated version of a string
+
+    Specifically, this functions returns a version of the input string
+    where each uppercase letter has been advanced 'n' positions in the
+    alphabet (wrapping around). Lowercase letters and any non-alphabetic
+    characters will be unchanged."""
+
+    result = ''
+    for letter in str:
+        if letter.isupper():
+            result += chr(ord("A") + (ord(letter) - ord("A") + n) % 26)
+        else:
+            result += letter
+    return result
+
+def rot(args):
+    """Implements logic for /rot slash command in Slack, returning a string
+
+    This implements the /rot command of our Slack bot. The format of this
+    command is as follows:
+
+        /rot [count|*] String to be rotated
+
+    The optional count indicates an amount to rotate each character in the
+    string. If the count is '*' or is not present, then the string will
+    be rotated through all possible 25 values.
+
+    The result of the rotation is returned as a string (with Slack
+    formatting)."""
+
+    match = re.match(r'^([0-9]+|\*) (.*)$', args)
+    if (match):
+        try:
+            count = int(match.group(1))
+        except ValueError:
+            count = None
+        text = match.group(2)
+    else:
+        count = None
+        text = args
+
+    text = text.upper()
+
+    reply = "```/rot {} {}\n".format(count if count else '*', text)
+
+    if count:
+        reply += rot_string(text, count)
+    else:
+        reply += "\n".join(["{:02d} ".format(count) + rot_string(text, count)
+                            for count in range(1, 26)])
+
+    reply += "```"
+
+    return reply
+
+def lambda_handler(event, context):
+    """Top-level entry point for our lambda function.
+
+    Currently only calls into the rot() function but may become more
+    sophisticated later on."""
+
+    result = rot(event['args'])
+
+    return {
+        'statusCode': 200,
+        'body': result
+    }