]> git.cworth.org Git - turbot/blob - turbot_flask/turbot.py
Share the rot() implementation between both Lambda and Flask implementations
[turbot] / turbot_flask / turbot.py
1 #!/usr/bin/env python3
2
3 from flask import Flask, request
4 from slackeventsapi import SlackEventAdapter
5 from turbot.slack import slack_is_valid_request, slack_send_reply
6 import os
7 import threading
8 from turbot.rot import rot
9 from turbot.slack import slack_send_message
10 from turbot.sheets import sheets_create
11
12 app = Flask(__name__)
13
14 slack_signing_secret = os.environ['SLACK_SIGNING_SECRET']
15 slack_events = SlackEventAdapter(slack_signing_secret, "/slack/events", app)
16
17 @app.route('/rot', methods = ['POST'])
18 def rot_route():
19     """Implements the /rot slash command for Slack replying in Slack
20
21     The format of this command is as follows:
22
23         /rot [count|*] String to be rotated
24
25     The optional count indicates an amount to rotate each character in the
26     string. If the count is '*' or is not present, then the string will
27     be rotated through all possible 25 values.
28
29     The result of the rotation is provided as a message in Slack. If the
30     slash command was issued in a direct message, the response is made by
31     using the "response_url" from the request. This allows the bot to reply
32     in a direct message that it is not a member of. Otherwise, if the slash
33     command was issued in a channel, the bot will reply in that channel."""
34
35     if not slack_is_valid_request(request):
36         return make_response("invalid request", 403)
37
38     text = request.form.get('text')
39
40     reply = rot(text)
41
42     slack_send_reply(request, reply)
43
44     return ""
45
46
47 @slack_events.on("channel_created")
48 def handle_channel_created(event_data):
49     def later(channel):
50         sheet_url = sheets_create(channel["name"])
51         slack_send_message(channel["id"],
52                            "Auto-created a sheet for this channel: {}"
53                            .format(sheet_url))
54
55     event = event_data["event"]
56     channel = event["channel"]
57     thread = threading.Thread(target=later, kwargs={'channel': channel})
58     thread.start()
59     return
60
61 @slack_events.on("error")
62 def handle_error(error):
63     app.logger.error("Error from Slack: " + str(error))