1 from flask import current_app
2 from slack import WebClient
3 from slack.errors import SlackApiError
4 from slack.signature import SignatureVerifier
8 slack_signing_secret = os.environ['SLACK_SIGNING_SECRET']
9 slack_bot_token = os.environ['SLACK_BOT_TOKEN']
11 signature_verifier = SignatureVerifier(slack_signing_secret)
12 slack_client = WebClient(slack_bot_token)
14 def slack_is_valid_request(request):
15 """Returns true if request actually came from Slack.
17 By means of checking the requests signature together with the slack
20 Note: If flask is in debug mode, this function will always return true."""
25 data = request.get_data()
26 headers = request.headers
28 return signature_verifier.is_valid_request(data, headers)
30 def slack_send_reply(request, text):
31 """Send a Slack message as a reply to a specified request.
33 If the request is associated with a direct message, the reply is
34 made by using the "response_url" from the request. Otherwise, the
35 reply will be sent to the channel associated with the request.
37 Note: If flask is in debug mode, this function will just print the
41 channel_name = request.form.get('channel_name')
42 response_url = request.form.get('response_url')
43 channel = request.form.get('channel_id')
46 print("Sending message to channel '{}': {}".format(channel, text))
49 if (channel_name == "directmessage"):
50 resp = requests.post(response_url,
51 json = {"text": text},
52 headers = {"Content-type": "application/json"})
53 if (resp.status_code != 200):
54 app.logger.error("Error posting request to Slack: " + resp.text)
56 slack_send_message(channel, text)
58 def slack_send_message(channel, text):
59 """Send a Slack message to a specified channel.
61 Note: If flask is in debug mode, this function will just print the
67 print("Sending message to channel '{}': {}".format(channel, text))
71 slack_client.chat_postMessage(channel=channel, text=text)
72 except SlackApiError as e:
73 app.logger.error("Slack API error: " + e.response["error"])