]> git.cworth.org Git - turbot/blob - turbot/slack.py
Fix several problems pointed out by flake8
[turbot] / turbot / slack.py
1 from flask import current_app
2 from slack import WebClient
3 from slack.signature import SignatureVerifier
4 import os
5 import requests
6
7 slack_signing_secret = os.environ['SLACK_SIGNING_SECRET']
8 slack_bot_token = os.environ['SLACK_BOT_TOKEN']
9
10 signature_verifier = SignatureVerifier(slack_signing_secret)
11 slack_client = WebClient(slack_bot_token)
12
13 def slack_is_valid_request(request):
14     """Returns true if request actually came from Slack.
15
16     By means of checking the requests signature together with the slack
17     signing key.
18
19     Note: If flask is in debug mode, this function will always return true."""
20
21     if current_app.debug:
22         return True
23
24     data = request.get_data()
25     headers = request.headers
26
27     return signature_verifier.is_valid_request(data, headers)
28
29 def slack_send_reply(request, text):
30     """Send a Slack message as a reply to a specified request.
31
32     If the request is associated with a direct message, the reply is
33     made by using the "response_url" from the request. Otherwise, the
34     reply will be sent to the channel associated with the request.
35
36     Note: If flask is in debug mode, this function will just print the
37     text to stdout."""
38
39     app = current_app
40     channel_name = request.form.get('channel_name')
41     response_url = request.form.get('response_url')
42     channel = request.form.get('channel_id')
43
44     if (app.debug):
45         print("Sending message to channel '{}': {}".format(channel, text))
46         return
47
48     if (channel_name == "directmessage"):
49         resp = requests.post(response_url,
50                              json = {"text": text},
51                              headers = {"Content-type": "application/json"})
52         if (resp.status_code != 200):
53             app.logger.error("Error posting request to Slack: " + resp.text)
54     else:
55         slack_send_message(channel, text)
56
57 def slack_send_message(channel, text):
58     """Send a Slack message to a specified channel."""
59
60     slack_client.chat_postMessage(channel=channel, text=text)