]> git.cworth.org Git - turbot/blob - turbot.py
Add a route to implement a /rot slash command
[turbot] / turbot.py
1 #!/usr/bin/env python3
2
3 from flask import Flask, request
4
5 from slackeventsapi import SlackEventAdapter
6 from slack import WebClient
7 from slack.errors import SlackApiError
8 import os
9 import requests
10 import re
11
12 app = Flask(__name__)
13
14 slack_signing_secret = os.environ['SLACK_SIGNING_SECRET']
15 slack_bot_token = os.environ['SLACK_BOT_TOKEN']
16
17 slack_events = SlackEventAdapter(slack_signing_secret, "/slack/events", app)
18 slack_client = WebClient(slack_bot_token)
19
20 def rot_string(str, n=13):
21     result = ''
22     for letter in str:
23         if letter.isupper():
24             result += chr(ord("A") + (ord(letter) - ord("A") + n) % 26)
25         else:
26             result += letter
27     return result
28
29 @app.route('/rot', methods = ['POST'])
30 def rot():
31     response_url = request.form.get('response_url')
32     channel_name = request.form.get('channel_name')
33     channel = request.form.get('channel_id')
34     query = request.form.get('text')
35
36     match = re.match('^([0-9]+|\*) (.*)$', query)
37     if (match):
38         try:
39             count = int(match.group(1))
40         except:
41             count = None
42         text = match.group(2)
43     else:
44         count = None
45         text = query
46
47     text = text.upper()
48
49     reply = "```/rot {} {}\n".format(count if count else '*', text)
50
51     if count:
52         reply += rot_string(text, count)
53     else:
54         reply += "\n".join(["{:02d} ".format(count) + rot_string(text, count) for count in range(1,26)])
55
56     reply += "```"
57
58     if (channel_name == "directmessage"):
59         resp = requests.post(response_url,
60                              json = {"text": reply},
61                              headers = {"Content-type": "application/json"})
62         if (resp.status_code != 200):
63             app.logger.error("Error posting request to Slack: " + resp.text)
64     else:
65         try:
66             slack_client.chat_postMessage(channel=channel, text=reply)
67         except SlackApiError as e:
68             app.logger.error("Slack API error: " + e.response["error"])
69     return ""
70
71 @slack_events.on("error")
72 def handle_error(error):
73     app.logger.error("Error from Slack: " + str(error))
74
75 if __name__ == '__main__':
76     app.run(debug=True)