3 from flask import Flask, request, make_response
5 from slackeventsapi import SlackEventAdapter
6 from slack import WebClient
7 from slack.errors import SlackApiError
8 from slack.signature import SignatureVerifier
15 slack_signing_secret = os.environ['SLACK_SIGNING_SECRET']
16 slack_bot_token = os.environ['SLACK_BOT_TOKEN']
18 slack_events = SlackEventAdapter(slack_signing_secret, "/slack/events", app)
19 signature_verifier = SignatureVerifier(slack_signing_secret)
20 slack_client = WebClient(slack_bot_token)
22 def slack_is_valid_request(request):
23 """Returns true if request actually came from Slack.
25 By means of checking the requests signature together with the slack
28 Note: If flask is in debug mode, this function will always return true."""
33 data = request.get_data()
34 headers = request.headers
36 return signature_verifier.is_valid_request(data, headers)
38 def slack_send_reply(request, text):
39 """Send a Slack message as a reply to a specified request.
41 If the request is associated with a direct message, the reply is
42 made by using the "response_url" from the request. Otherwise, the
43 reply will be sent to the channel associated with the request.
45 Note: If flask is in debug mode, this function will just print the
48 channel_name = request.form.get('channel_name')
49 response_url = request.form.get('response_url')
50 channel = request.form.get('channel_id')
53 print("Sending message to channel '{}': {}".format(channel, text))
56 if (channel_name == "directmessage"):
57 resp = requests.post(response_url,
58 json = {"text": text},
59 headers = {"Content-type": "application/json"})
60 if (resp.status_code != 200):
61 app.logger.error("Error posting request to Slack: " + resp.text)
64 slack_client.chat_postMessage(channel=channel, text=text)
65 except SlackApiError as e:
66 app.logger.error("Slack API error: " + e.response["error"])
68 def rot_string(str, n=13):
69 """Return a rotated version of a string
71 Specifically, this functions returns a version of the input string
72 where each uppercase letter has been advanced 'n' positions in the
73 alphabet (wrapping around). Lowercase letters and any non-alphabetic
74 characters will be unchanged."""
79 result += chr(ord("A") + (ord(letter) - ord("A") + n) % 26)
84 @app.route('/rot', methods = ['POST'])
86 """Implements the /rot route for the /rot slash command in Slack
88 This implements the /rot command of our Slack bot. The format of this
89 command is as follows:
91 /rot [count|*] String to be rotated
93 The optional count indicates an amount to rotate each character in the
94 string. If the count is '*' or is not present, then the string will
95 be rotated through all possible 25 values.
97 The result of the rotation is provided as a message in Slack. If the
98 slash command was issued in a direct message, the response is made by
99 using the "response_url" from the request. This allows the bot to reply
100 in a direct message that it is not a member of. Otherwise, if the slash
101 command was issued in a channel, the bot will reply in that channel."""
103 if not slack_is_valid_request(request):
104 return make_response("invalid request", 403)
106 query = request.form.get('text')
107 match = re.match(r'^([0-9]+|\*) (.*)$', query)
110 count = int(match.group(1))
113 text = match.group(2)
120 reply = "```/rot {} {}\n".format(count if count else '*', text)
123 reply += rot_string(text, count)
125 reply += "\n".join(["{:02d} ".format(count) + rot_string(text, count)
126 for count in range(1, 26)])
130 slack_send_reply(request, reply)
134 @slack_events.on("error")
135 def handle_error(error):
136 app.logger.error("Error from Slack: " + str(error))