-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
153 lines (123 loc) · 4.58 KB
/
app.py
File metadata and controls
153 lines (123 loc) · 4.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import os
import sys
import re
import json
import hmac
import hashlib
import logging
import requests
from flask import Flask, request, make_response
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
slack_signing_secret = os.environ.get("SLACK_SIGNING_SECRET")
slack_bot_token = os.environ.get("SLACK_BOT_TOKEN")
js_auth_token = os.environ.get("JS_AUTH_TOKEN")
WATCHED_CHANNELS = os.environ.get("SLACK_ANNOUNCEMENT_CHANNELS").split(",")
slack_client = WebClient(token=slack_bot_token)
emoji_list = {}
try:
emoji_call = slack_client.emoji_list()
if emoji_call["ok"]:
emoji_list = emoji_call["emoji"]
except SlackApiError as e:
logging.warning(f"Could not fetch emojis")
def clean_text(raw):
"""Strip Slack mrkdwn, HTML entities, and formatting characters."""
text = re. sub (r"<[^>]+>", "", str(raw), flags=re.IGNORECASE)
text = re.sub(r"<.*?>", "", text, flags=re.IGNORECASE)
return text. replace("*", ""). replace("_", ""). replace("`", "").strip()
@app.route("/", methods=["GET"])
def index():
return "Works"
@app.route("/slack/events", methods=["POST"])
def slack_events():
if request.content_type == "application/json":
body = request.get_json()
if body and body.get("type") == "url_verification":
return make_response(body["challenge"], 200)
body = request.get_json(force=True)
if not body:
return make_response(body["challenge"], 200)
logging.info(body)
event = body.get("event", {})
if event.get("type") != "message":
return make_response("", 200)
channel = event.get("channel", "")
subtype = event.get("subtype")
user_id = event.get("user")
raw_text = event.get("text", "")
if subtype is not None:
return make_response("", 200)
if not any(ch in channel for ch in WATCHED_CHANNELS):
return make_response("", 200)
cleaned = clean_text(raw_text)
payload_value = json.dumps({"text": cleaned, "user": user_id})
blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"Would you like to post this message to Jumpstart?\n\n{cleaned}",
},
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "Yes"},
"style": "primary",
"action_id": "yes_j",
"value": payload_value,
},
{
"type": "button",
"text": {"type": "plain_text", "text": "No"},
"style": "danger",
"action_id": "no_j",
"value": "no",
},
],
},
]
try:
slack_client.chat_postMessage(channel=user_id, text="Would you like to post this message to Jumpstart?", blocks=blocks)
except SlackApiError as e:
logging.error(f"Failed to DM user {user_id}: {e}")
return make_response("", 200)
@app.route("/slack/message_actions", methods=["POST"])
def message_actions():
form_json = json.loads(request.form["payload"])
logging.info(form_json)
if form_json.get("type") != "block_actions":
return make_response("", 200)
action = form_json["actions"][0]
action_id = action.get("action_id")
response_url = form_json.get("response_url")
if action_id == "yes_j":
value = json.loads(action.get("value", "{}"))
text = value.get("text", "")
user = value.get("user", "")
headers = {
"content-type": "application/json",
"authorization": js_auth_token,
}
announcement = {
"ann_body": text,
"emoji_list": emoji_list,
"name": user,
}
logging.info(announcement)
res = requests.post("https://jumpstart.csh.rit.edu/update-announcement", json=announcement, headers=headers)
logging.info(f"Jumpstart response: {res.status_code}")
if response_url:
requests.post(response_url, json={"text": "Posting right now :^)", "replace_original": True})
return make_response("", 200)
elif action_id == "no_j":
if response_url:
requests.post(response_url, json={"text": "Okay :( maybe next time", "replace_original": True})
return make_response("", 200)
logging.warning(f"Unknown action_id: {action_id}")
return make_response("", 200)