forked from tsukasa-au/ncss-coffeerun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coffeebot.py
316 lines (261 loc) · 9.59 KB
/
coffeebot.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# vim: set et nosi ai ts=2 sts=2 sw=2:
# coding: utf-8
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pprint
import random
import re
import time
from slackclient import SlackClient
from application import app, db, events
from application.models import Run, User, Coffee, Event, sydney_timezone_now
import flask_babel
import coffeespecs
import utils
TOKEN = None
USER_ID = None
TEAM_ID = None
MENTION_RE = re.compile(r'<@([A-Z0-9]+)\|?[^>]*>:?')
EMOJI_RE = re.compile(r':[a-z]+:')
DISPATCH = {}
ORDERS_DISPATCH = {}
TRIGGERS = {}
def list_runs(slackclient, user, channel, match):
"""Handle the 'open runs' command.
This command only displays the open runs. If there are multiple runs
currently open, it orders them by time (on the assumption that you want
things in the first available run).
Args:
slackclient: the slackclient.SlackClient object for the current
connection to Slack.
user: the slackclient.User object for the user who send the
message to us.
channel: the slackclient.Channel object for the channel the
message was received on.
match: the object returned by re.match (an _sre.SRE_Match object).
"""
now = sydney_timezone_now()
q = Run.query.filter_by(is_open=True).order_by('time').all()
if not q:
channel.send_message('No open runs')
return (True, None)
for run in q:
person = User.query.filter_by(id=run.person).first()
time_to_run = run.time - now
channel.send_message(
'Run {}: {} is going to {} in {} (at {})'.format(
run.id, person.name, run.cafe.name,
flask_babel.format_timedelta(time_to_run), run.time))
return (True, None)
def order_coffee(slackclient, user, channel, match):
"""Handle adding coffee to existing orders.
Args:
slackclient: the slackclient.SlackClient object for the current
connection to Slack.
user: the slackclient.User object for the user who send the
message to us.
channel: the slackclient.Channel object for the channel the
message was received on.
match: the object returned by re.match (an _sre.SRE_Match object).
"""
logger = logging.getLogger('order_coffee')
logger.info('Matches: %s', pprint.pformat(match.groupdict()))
runid = match.groupdict().get('runid', None)
run = None
if runid and runid.isdigit():
run = Run.query.filter_by(id=int(runid)).first()
if not run:
# Pick a run
runs = Run.query.filter_by(is_open=True).order_by('time').all()
if len(runs) > 1:
def resolve_run_feedback():
channel.send_message(
'More than one open run, please specify by adding run=<id> on the end.')
list_runs(slackclient, user, channel, match=None)
return (False, resolve_run_feedback)
if len(runs) == 0:
def resolve_closed_feedback():
channel.send_message('No open runs')
return (False, resolve_closed_feedback)
run = runs[0]
# Create the coffee
c = coffeespecs.Coffee(match.groupdict().get('order', None))
validation_errors = list(c.validation_errors())
if validation_errors:
def resolve_validation_feedback():
channel.send_message(
'That coffee is not valid missing the following specs: {}. Got: {}'.format(
', '.join(spec.name for spec in validation_errors),
c,
))
return (False, resolve_validation_feedback)
coffee = Coffee(c, 0, run.id)
# Find the user that requested this
dbuser = utils.get_or_create_user(user.id, TEAM_ID, user.name)
logger.info('User: %s', dbuser)
# Put it all together
coffee.person = dbuser.id
db.session.add(coffee)
db.session.commit()
events.coffee_added(run.id, coffee.id)
# Write the event
event = Event(coffee.person, "created", "coffee", coffee.id)
event.time = sydney_timezone_now()
db.session.add(event)
db.session.commit()
logger.info('Parsed coffee: %s', coffee)
runuser = User.query.filter_by(id=run.person).first()
if runuser.slack_user_id:
mention_runner = '<@{}>'.format(runuser.slack_user_id)
else:
mention_runner = runuser.name
channel.send_message(
'That\'s a {} for {} (added to {}\'s run.)'.format(
coffee.pretty_print(),
mention(user),
mention_runner))
return (True, None)
def set_up_orders():
ORDERS_DISPATCH[re.compile('(?:(?:open|list) )?runs')] = list_runs
ORDERS_DISPATCH[re.compile('order(?: an?)? (?P<order>[^\=]+)(?: run=(?P<runid>[0-9]+))?')] = order_coffee
ORDERS_DISPATCH[re.compile('(?P<order>[^\=]+) (?:plz|pls|please|plox|cheers)(?: run=(?P<runid>[0-9]+))?')] = order_coffee
ORDERS_DISPATCH[re.compile('(?:plz|pls|please|plox) (?P<order>[^\=]+)(?: run=(?P<runid>[0-9]+))?')] = order_coffee
def load_triggers(filename):
"""Parse the sass file, loading them into the TRIGGERS global.
"""
trigger = None
for line in open(filename):
if not line.strip():
continue
if line.startswith('@@@ '):
trigger = re.compile(line[4:].strip())
if trigger not in TRIGGERS:
TRIGGERS[trigger] = []
elif trigger:
TRIGGERS[trigger].append(line.strip())
def trigger_check(slackclient, user, channel, text):
"""Check if we need to sass the user.
Args:
slackclient: the slackclient.SlackClient object for the current
connection to Slack.
user: the slackclient.User object for the user who send the
message to us.
channel: the slackclient.Channel object for the channel the
message was received on.
match: the object returned by re.match (an _sre.SRE_Match object).
"""
text = text.lower()
for trigger in TRIGGERS:
if trigger.match(text):
msg = random.choice(TRIGGERS[trigger])
msg = mention(user) + ': ' + msg
channel.send_message(msg)
return True
else:
# No triggers matched. Inform our caller so they can decide what to do.
return False
def mention(user):
"""Generate a mention for the given user.
Args:
user: a slackclient.User object for the user to mention.
"""
return '<@{}|{}>'.format(user.id, user.name)
def clean_text(text):
# Remove @mentions and emoji
text = MENTION_RE.sub('', text)
text = EMOJI_RE.sub('', text)
text = text.lower()
return text.strip()
def handle_mention_message(slackclient, user, channel, text):
"""We were mentioned in a message, dispatch it to the method.
Args:
slackclient: the slackclient.SlackClient object for the current
connection to Slack.
user: the slackclient.User object for the user who send the
message to us.
channel: the slackclient.Channel object for the channel the
message was received on.
text: the raw text that was sent to us.
"""
clean = clean_text(text)
message_processed = False
error_resolver = None
for order_re in ORDERS_DISPATCH:
# Go through each command regex
# If the command errors then store the error
# Keep going until a command matches successfully or we run out of commands
# If no command matches, resolve the stored error
# If a command succeeds don't resolve the stored error
match = order_re.match(clean)
if match:
success, resolver = ORDERS_DISPATCH[order_re](slackclient, user, channel, match)
message_processed = True
if success:
error_resolver = resolver
break
else:
error_resolver = resolver
if error_resolver is not None:
error_resolver()
if trigger_check(slackclient, user, channel, clean):
message_processed = True
if not message_processed:
# We were mentioned, but we don't know what to do... Say
# something back to them.
channel.send_message('I am sorry {}, I can\'t do that.'.format(
mention(user)))
def handle_message(slackclient, event):
logger = logging.getLogger('handle_message')
logger.debug('message event: %s', event)
channel = slackclient.server.channels.find(event['channel'])
# If the user edits their message, we treat it as if it were a new
# message from that person.
if 'subtype' in event and event['subtype'] == 'message_changed':
event = event['message']
if 'user' not in event:
# Ignore events from non-users (i.e. coffebot app messages)
return
user = slackclient.server.users.find(event['user'])
text = event['text']
mentions = MENTION_RE.findall(text)
logger.info('Mentions: %s', mentions)
# Behaviours:
if USER_ID in mentions:
handle_mention_message(slackclient, user, channel, text)
elif ':coffee:' in text:
msg = 'Mmmm... :coffee:' + ':coffee:' * random.randint(0, 7)
channel.send_message(msg)
def register_handlers():
DISPATCH['message'] = [handle_message]
def main():
logger = logging.getLogger('main')
load_triggers('sass.txt')
set_up_orders()
register_handlers()
client = SlackClient(TOKEN)
res = client.rtm_connect()
logger.debug('Connection result: %r', res)
if not res:
logger.error('Connection Failed.')
return
logger.info('Users: %s', client.server.users)
logger.info('Channels: %s', client.server.channels)
while True:
for event in client.rtm_read():
logger.debug('Event: %s', event)
if 'type' in event:
# Call all handlers for the given event type.
for handler in DISPATCH.get(event['type'], []):
handler(client, event)
time.sleep(0.1)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
TOKEN = app.config['SLACK_API_TOKEN']
USER_ID = app.config['SLACK_BOT_USER_ID']
TEAM_ID = app.config['SLACK_TEAM_ID']
if not TOKEN or not USER_ID:
logging.error('Missing slack token or slack user id')
# FIXME: This is a hack... But I can't think of anything better.
# Add a test request context so that babel will work.
app.test_request_context().push()
main()