]> git.cworth.org Git - turbot/blob - turbot/rot.py
e991941d313b9f66bd4e8b81825e0d315590fe9b
[turbot] / turbot / rot.py
1 from flask import Blueprint, request, make_response
2 from turbot.slack import slack_is_valid_request, slack_send_reply
3 import re
4
5 rot_route = Blueprint('rot_route', __name__)
6
7 def rot_string(str, n=13):
8     """Return a rotated version of a string
9
10     Specifically, this functions returns a version of the input string
11     where each uppercase letter has been advanced 'n' positions in the
12     alphabet (wrapping around). Lowercase letters and any non-alphabetic
13     characters will be unchanged."""
14
15     result = ''
16     for letter in str:
17         if letter.isupper():
18             result += chr(ord("A") + (ord(letter) - ord("A") + n) % 26)
19         else:
20             result += letter
21     return result
22
23 @rot_route.route('/rot', methods = ['POST'])
24 def rot():
25     """Implements the /rot route for the /rot slash command in Slack
26
27     This implements the /rot command of our Slack bot. The format of this
28     command is as follows:
29
30         /rot [count|*] String to be rotated
31
32     The optional count indicates an amount to rotate each character in the
33     string. If the count is '*' or is not present, then the string will
34     be rotated through all possible 25 values.
35
36     The result of the rotation is provided as a message in Slack. If the
37     slash command was issued in a direct message, the response is made by
38     using the "response_url" from the request. This allows the bot to reply
39     in a direct message that it is not a member of. Otherwise, if the slash
40     command was issued in a channel, the bot will reply in that channel."""
41
42     if not slack_is_valid_request(request):
43         return make_response("invalid request", 403)
44
45     query = request.form.get('text')
46     match = re.match(r'^([0-9]+|\*) (.*)$', query)
47     if (match):
48         try:
49             count = int(match.group(1))
50         except ValueError:
51             count = None
52         text = match.group(2)
53     else:
54         count = None
55         text = query
56
57     text = text.upper()
58
59     reply = "```/rot {} {}\n".format(count if count else '*', text)
60
61     if count:
62         reply += rot_string(text, count)
63     else:
64         reply += "\n".join(["{:02d} ".format(count) + rot_string(text, count)
65                             for count in range(1, 26)])
66
67     reply += "```"
68
69     slack_send_reply(request, reply)
70
71     return ""