]> git.cworth.org Git - turbot/blob - turbot/slack.py
Add a listener for the Slack "channel_created" event
[turbot] / turbot / slack.py
1 from flask import current_app
2 from slack import WebClient
3 from slack.errors import SlackApiError
4 from slack.signature import SignatureVerifier
5 import os
6 import requests
7
8 slack_signing_secret = os.environ['SLACK_SIGNING_SECRET']
9 slack_bot_token = os.environ['SLACK_BOT_TOKEN']
10
11 signature_verifier = SignatureVerifier(slack_signing_secret)
12 slack_client = WebClient(slack_bot_token)
13
14 def slack_is_valid_request(request):
15     """Returns true if request actually came from Slack.
16
17     By means of checking the requests signature together with the slack
18     signing key.
19
20     Note: If flask is in debug mode, this function will always return true."""
21
22     if current_app.debug:
23         return True
24
25     data = request.get_data()
26     headers = request.headers
27
28     return signature_verifier.is_valid_request(data, headers)
29
30 def slack_send_reply(request, text):
31     """Send a Slack message as a reply to a specified request.
32
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.
36
37     Note: If flask is in debug mode, this function will just print the
38     text to stdout."""
39
40     app = current_app
41     channel_name = request.form.get('channel_name')
42     response_url = request.form.get('response_url')
43     channel = request.form.get('channel_id')
44
45     if (app.debug):
46         print("Sending message to channel '{}': {}".format(channel, text))
47         return
48
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)
55     else:
56         slack_send_message(channel, text)
57
58 def slack_send_message(channel, text):
59     """Send a Slack message to a specified channel.
60
61     Note: If flask is in debug mode, this function will just print the
62     text to stdout."""
63
64     app = current_app
65
66     if (app.debug):
67         print("Sending message to channel '{}': {}".format(channel, text))
68         return
69
70     try:
71         slack_client.chat_postMessage(channel=channel, text=text)
72     except SlackApiError as e:
73         app.logger.error("Slack API error: " + e.response["error"])