1 from flask import current_app
2 from slack import WebClient
3 from slack.signature import SignatureVerifier
7 slack_signing_secret = os.environ['SLACK_SIGNING_SECRET']
8 slack_bot_token = os.environ['SLACK_BOT_TOKEN']
10 signature_verifier = SignatureVerifier(slack_signing_secret)
11 slack_client = WebClient(slack_bot_token)
13 def slack_is_valid_request(request):
14 """Returns true if request actually came from Slack.
16 By means of checking the requests signature together with the slack
19 Note: If flask is in debug mode, this function will always return true."""
24 data = request.get_data()
25 headers = request.headers
27 return signature_verifier.is_valid_request(data, headers)
29 def slack_send_reply(request, text):
30 """Send a Slack message as a reply to a specified request.
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.
36 Note: If flask is in debug mode, this function will just print the
40 channel_name = request.form.get('channel_name')
41 response_url = request.form.get('response_url')
42 channel = request.form.get('channel_id')
45 print("Sending message to channel '{}': {}".format(channel, text))
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)
55 slack_send_message(channel, text)
57 def slack_send_message(channel, text):
58 """Send a Slack message to a specified channel."""
60 slack_client.chat_postMessage(channel=channel, text=text)