-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
80 lines (71 loc) · 2.59 KB
/
app.py
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
from flask import Flask, redirect, request, session, render_template, jsonify, Response
import json
import requests
import binascii
import os
import random
app = Flask(__name__)
app.secret_key = os.environ["SECRET_KEY"]
CLIENT_ID = os.environ["CLIENT_ID"]
CLIENT_SECRET = os.environ["CLIENT_SECRET"]
REDIRECT_URI = os.environ["REDIRECT_URI"]
# Global state lol
tokens = dict()
active_quizzes = dict()
users = dict()
def slackRequest(method, params={}):
r = requests.post("https://slack.com/api/" + method, params=params)
return r.json()
@app.route("/")
def index():
# I'm so sorry
return '<a href="https://slack.com/oauth/authorize?scope=commands,users:read&client_id=%s"><img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/[email protected] 2x"></a> Talk to @raphael if this breaks!' % CLIENT_ID
@app.route("/oauth")
def oauth():
code = request.args.get("code")
j = slackRequest("oauth.access", {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"code": code,
"redirect_uri": REDIRECT_URI,
"state": binascii.b2a_hex(os.urandom(15))
})
print j
if j["ok"] != True or "access_token" not in j:
return "Error logging in :("
tokens[j["team_id"]] = j["access_token"]
return "All set up, now just try /facequiz in your Slack!"
@app.route("/facequiz", methods=["GET", "POST"])
def facequiz():
team_id = request.form.get("team_id")
text = request.form.get("text").strip()
user_id = request.form.get("user_id")
token = tokens[team_id]
if user_id in active_quizzes:
answer = active_quizzes[user_id]
del active_quizzes[user_id]
if text.lower() == answer.lower():
return "Hooray, you got it - that's *%s*! Run `/facequiz` again for a new quiz!" % answer
else:
return "Whoops, that's actually *%s*. Run `/facequiz` again for a new quiz!" % answer
if team_id not in users:
users[team_id] = slackRequest("users.list", {
"token": token
})
while True:
pick = random.choice(users[team_id]["members"])
if "first_name" in pick["profile"]:
break
active_quizzes[user_id] = pick["profile"]["first_name"].strip()
res = json.dumps({
"text": "What's this person's first name? Respond with `/facequiz [name]`!",
"attachments": [
{
"fallback": "(Image of the person).",
"image_url": pick["profile"]["image_192"]
}
]
})
return Response(res, mimetype="application/json")
if __name__ == "__main__":
app.run("0.0.0.0", port=5000)