-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
294 lines (248 loc) · 7.21 KB
/
app.py
File metadata and controls
294 lines (248 loc) · 7.21 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import random
import re
from functools import wraps
import arrow
import redis
import requests
from flask import abort, Flask, jsonify, request
from simpleflake import simpleflake
CHIKKA_API_URL = "https://post.chikka.com/smsapi/request"
DEFAULT_MEAL_USERS = set([
"U025XRFHC", # Marte
])
USER_PAT = re.compile("\<@([A-Z0-9]+)\>")
app = Flask(__name__)
app.config.from_object("config")
db = redis.StrictRedis(host="redis")
def key(*args):
return ":".join(map(str, args))
def get_users():
return {
user["id"]: user for user in requests.get(
"https://slack.com/api/users.list",
params=dict(token=app.config["SLACK_API_TOKEN"]),
).json()["members"]
}
def get_channels():
return {
channel["name"]: channel for channel in requests.get(
"https://slack.com/api/channels.list",
params=dict(token=app.config["SLACK_API_TOKEN"]),
).json()["channels"]
}
def send_sms(mobile_number, message):
requests.post(
CHIKKA_API_URL,
data=dict(
message_type="SEND",
mobile_number=mobile_number,
shortcode=app.config["CHIKKA_SHORTCODE"],
message_id=str(simpleflake()),
message=message + '\n\n*',
client_id=app.config["CHIKKA_CLIENT_ID"],
secret_key=app.config["CHIKKA_SECRET_KEY"],
)
)
def slack_hook(mapping):
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
tokens = app.config["SLACK_TOKENS"]
if request.form["token"] != tokens[f.__name__.upper()]:
abort(403)
words = []
for word in request.form["text"].lower().split():
words.append(re.sub("[^a-z0-9'_\-\+]", "", word))
kwargs["words"] = words
# Get events from triggers
events = set()
for event, keywords in mapping.items():
if set(keywords.split(",")) & set(words):
events.add(event)
kwargs["events"] = events
# Get tagged users
users = get_users()
kwargs["tagged_users"] = [
users[user_id] for user_id in USER_PAT.findall(
request.form["text"]
)
]
return f(*args, **kwargs)
return wrapped
return wrapper
@app.route("/report/<type>", methods=["POST"])
def report(type):
day = arrow.now().floor("day")
if day.weekday() > 3 and day.weekday() < 6:
return jsonify(ok=True)
weekday = arrow.locales.get_locale('en_us').day_name(
day.replace(days=1).isoweekday()
)
timestamp = day.timestamp
if type == "meals":
message = "{}\n\n".format(weekday)
for meal in "lunch", "merienda", "dinner":
meal_users = db.smembers(key(meal, timestamp)) | DEFAULT_MEAL_USERS
message += "{}: {}\n".format(
meal.capitalize(),
len(meal_users),
)
for mobile_number in app.config["MEALS_REPORT_NUMBERS"]:
send_sms(mobile_number, message)
return jsonify(ok=True)
@app.route("/meals", methods=["POST"])
@slack_hook(dict(
count="ilan,bilang,count,sino",
lunch="lunch,l,tanghalian",
merienda="merienda,m",
dinner="dinner,d,hapunan",
cancel="hindi,not",
))
def meals(events, **kwargs):
day = arrow.now().floor("day")
weekday = arrow.locales.get_locale('en_us').day_name(
day.replace(days=1).isoweekday()
)
timestamp = day.timestamp
if "count" in events:
reply = "*{}*\n\n".format(weekday)
users = get_users()
for meal in "lunch", "merienda", "dinner":
meal_users = db.smembers(key(meal, timestamp)) | DEFAULT_MEAL_USERS
reply += "{}: {}\n".format(
meal.capitalize(),
len(meal_users),
)
names = [
users[user_id]["profile"]["first_name"]
for user_id in meal_users if user_id in users
]
reply += " {}\n".format(", ".join(sorted(names)))
return jsonify(text=reply)
user_id = request.form["user_id"]
for meal in "lunch", "merienda", "dinner":
if meal in events:
if "cancel" in events:
db.srem(key(meal, timestamp), user_id)
else:
db.sadd(key(meal, timestamp), user_id)
return jsonify(text="")
@app.route("/listahan", methods=["POST"])
@slack_hook(dict(
owe="owe,owes,utang",
self="sakin,me",
others="ako,ko,i",
))
def listahan(words, events, tagged_users):
amounts = []
for word in words:
try:
amounts.append(float(word))
except ValueError:
pass
user_id = request.form["user_id"]
if not events:
reply = ""
for tagged_user in tagged_users:
for amount in amounts:
div_amount = amount / len(tagged_users)
total_amount = db.incrbyfloat(
key("listahan", user_id, tagged_user["id"]),
div_amount,
)
reply += "{}: {}\n".format(
tagged_user["profile"]["first_name"],
total_amount,
)
return jsonify(text=reply)
if "owe" in events:
users = get_users()
if "self" in events:
reply = ""
for user in users.values():
amount = db.get(key("listahan", user_id, user["id"]))
if amount and float(amount):
reply += "{} owes you {}\n".format(
user["profile"]["first_name"],
amount,
)
return jsonify(text=reply or "No one")
if "others" in events:
reply = ""
for user in users.values():
amount = db.get(key("listahan", user["id"], user_id))
if amount and float(amount):
reply += "You owe {} {}\n".format(
user["profile"]["first_name"],
amount,
)
return jsonify(text=reply or "No one")
return jsonify(text="")
@app.route("/monito_monita", methods=["POST"])
@slack_hook(dict(
set_number="number",
draw="draw,bunot",
send="send",
))
def monito_monita(words, events, **kwargs):
if "set_number" in events:
user_id = request.form["user_id"]
number = None
for word in words:
try:
if word.startswith("63"):
number = int(word)
break
except ValueError:
pass
if number:
db.set(
key("monito_monita", "number", user_id),
number,
)
return jsonify(text="Saved your number")
if "draw" in events:
channels = get_channels()
pot = channels["monito_monita"]["members"]
random.shuffle(pot)
users = get_users()
# Check numbers
for user_id in pot:
if not db.exists(
key("monito_monita", "number", user_id)
):
user = users[user_id]
return jsonify(
text="I don't have {}'s number yet".format(
user["profile"]["first_name"],
),
)
# Clear previous draw
db.delete(key("monito_monita"))
# Draw
for pair in [
"{}:{}".format(
user_id,
pot[(i + 1) % len(pot)],
) for i, user_id in enumerate(pot)
]:
db.sadd(key("monito_monita"), pair)
return jsonify(text="Drawn!")
if "send" in events:
pairs = db.smembers(key("monito_monita"))
users = get_users()
if pairs:
for pair in pairs:
giver_id, givee_id = pair.split(":")
givee = users[givee_id]
mobile_number = db.get(
key("monito_monita", "number", giver_id),
)
message = "Monito Monita\n\nYou drew {}!".format(
givee["profile"]["first_name"],
)
send_sms(mobile_number, message)
return jsonify(text="Sent!")
return jsonify(text="")
if __name__ == "__main__":
app.run(host="0.0.0.0")