-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathseen.py
More file actions
338 lines (303 loc) · 11.7 KB
/
Copy pathseen.py
File metadata and controls
338 lines (303 loc) · 11.7 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
"""
seen.py - A simple willie module to track nicks
Copyright 2013, Tim Dreyer
Licensed under the Eiffel Forum License 2.
http://bitbucket.org/tdreyer/fineline
"""
from time import time
import threading
import os
import re
import json
from pytz import timezone
from types import *
from datetime import timedelta, datetime
import imp
import sys
from willie.tools import Nick
from willie.module import commands, example, priority, rule
try:
import imp
import sys
from permissions import perm_chk
except:
try:
ffp, pathname, description = imp.find_module('permissions',['/home/dropbox/Dropbox/WillieBot'])
permissions = imp.load_source('permissions', pathname, ffp)
sys.modules['permissions'] = permissions
finally:
if ffp:
ffp.close()
from permissions import perm_chk
log_dir = u''
log_regex = re.compile(u'^#reddit-mlpds_\d{8}\.log$')
line_regex = re.compile(u'^\[(\d\d:\d\d:\d\d)\] <([^>]+)> (.*)$')
chan_regex = re.compile(u'^(.*?)_\d{8}$')
cen = timezone(u"US/Central") #log timezone
def escape(ucode):
escaped = ucode
escaped = re.sub(u'"', u'"', escaped)
escaped = re.sub(u"'", u''', escaped)
return escaped
def unescape(ucode):
unescaped = ucode
unescaped = re.sub(u'"', u'"', unescaped)
unescaped = re.sub(u''', u"'", unescaped)
return unescaped
# Bot framework is stupid about importing, so we need to override so that
# the colors module is always available for import.
try:
import colors
except:
try:
fp, pathname, description = imp.find_module('colors',
['./.willie/modules/']
)
colors = imp.load_source('colors', pathname, fp)
sys.modules['colors'] = colors
finally:
if fp:
fp.close()
def setup(willie):
global log_dir
if willie.config.has_option('seen', 'log_dir'):
log_dir = willie.config.seen.log_dir
willie.debug(u'seen:logdir', u'found dir %s' % log_dir, u'verbose')
if 'seen_lock' not in willie.memory:
willie.memory['seen_lock'] = threading.Lock()
if willie.db and not willie.db.check_table('seen',
['nick', 'data'],
'nick'
):
willie.db.add_table('seen', ['nick', 'data'], 'nick')
# TODO Initialize preference table for those who wish to not be recorded
seen_reload(willie)
def seen_reload(willie):
willie.memory['seen_lock'].acquire()
try:
willie.memory['seen'] = {}
for row in willie.db.seen.keys('nick'):
nick, json_data = willie.db.seen.get(
row[0], # We're getting back ('x',) when we need 'x'
('nick', 'data'),
'nick'
)
nn = Nick(nick)
data = json.loads(unescape(json_data))
time = float(data['time'])
assert type(time) is FloatType, u'%r is not float' % time
chan = data['channel']
msg = data['message']
r_tup = (time, chan, msg)
willie.memory['seen'][nn.lower()] = r_tup
finally:
willie.memory['seen_lock'].release()
def seen_insert(willie, nick, data):
# TODO change data imput to dict
# TODO Just pass data through to databasae
assert isinstance(nick, basestring)
assert type(data) is TupleType
assert len(data) == 3
assert type(data[0]) is FloatType, u'%r is not float' % data[0]
assert isinstance(data[1], basestring)
assert isinstance(data[2], basestring)
nn = Nick(nick)
dict = {}
dict['time'] = str(data[0])
dict['channel'] = data[1] # data[1] should be unicode
dict['message'] = data[2]
willie.memory['seen'][nn] = data
#willie.debug('to insert', '%s, %r' % (nn.lower(), dict) ,'verbose')
willie.db.seen.update(nn.lower(), {'data': escape(json.dumps(dict))})
'''
# TODO
#def seen_delete()
willie.memory['seen_lock'].acquire()
try:
finally:
willie.memory['seen_lock'].release()
# TODO
#def seen_ignore()
willie.memory['seen_lock'].acquire()
try:
finally:
willie.memory['seen_lock'].release()
'''
@commands(u'seen_load_logs')
def load_from_logs(willie, trigger):
if perm_chk(trigger.hostmask, "Ow", willie):
willie.reply(u"Alright, I'll start looking through the logs, " +
u"but this is going to take a while..."
)
willie.memory['seen_lock'].acquire()
try:
willie.debug(u'load_from_logs', u'=' * 25, u'verbose')
willie.debug(u'load_from_logs', u'Starting', u'verbose')
filelist = []
for f in os.listdir(log_dir):
if log_regex.match(f) and os.path.isfile(log_dir + f):
filelist.append(log_dir + f)
filelist.sort()
for log in filelist:
willie.debug(u'%f load_from_logs' % time(),
u'opening %s' % log,
u'verbose'
)
with open(log, 'r') as file:
file_list = []
for l in file:
# omfg took me way too long to figure out 'replace'
file_list.append(l.decode('utf-8', 'replace'))
willie.debug(u'%f' % time(),
u'finished loading file',
u'verbose'
)
for line in file_list:
#line = line.decode('utf-8', 'replace')
#willie.debug('load_from_logs: line', line,'verbose')
willie.debug(u'%f' % time(),
u'checking line',
u'verbose'
)
m = line_regex.search(line)
if m:
'''willie.debug(
'load_from_logs',
'line is message',
'verbose'
)'''
'''willie.debug(
'line',
'%s %s %s' % (
m.group(1),
m.group(2),
m.group(3)
),
'verbose'
)'''
nn = Nick(m.group(2))
msg = m.group(3)
log_name = os.path.splitext(
os.path.basename(log)
)
chan = chan_regex.search(log_name[0]).group(1)
chan = chan.decode('utf-8', 'replace')
last = m.group(1) # 00:00:00
date = log_name[0][-8:] # 20001212
dt = datetime(
int(date[:4]),
int(date[4:6]),
int(date[6:]),
int(last[:2]),
int(last[3:5]),
int(last[6:])
)
utc_dt = cen.normalize(cen.localize(dt))
timestamp = float(utc_dt.strftime(u'%s'))
'''willie.debug(
'logname',
'utc timestamp is %f' % timestamp,
'verbose'
)'''
data = (timestamp, chan, msg)
seen_insert(willie, nn.lower(), data)
finally:
willie.memory['seen_lock'].release()
willie.debug(u'', u'done', u'verbose')
willie.reply(u"Okay, I'm done reading the logs!")
@commands('nuke')
@priority('low')
def seen_nuke(willie, trigger):
'''ADMIN: Nuke the seen database'''
if perm_chk(trigger.hostmask, "Ow", willie):
willie.reply(u"[](/ppsalute) Aye aye, nuking it from orbit.")
willie.memory['seen_lock'].acquire()
try:
willie.memory['seen'] = {} # NUKE IT FROM ORBIT
for row in willie.db.seen.keys('nick'):
willie.db.seen.delete(row[0], 'nick')
willie.reply(u"Done!")
finally:
willie.memory['seen_lock'].release()
else:
willie.debug(
u'seen.py:nuke',
u'%s just tried to use the !nuke command!' % trigger.nick,
u'always'
)
@priority(u'low')
@rule(u'.*')
def seen_recorder(willie, trigger):
if not trigger.args[0].startswith(u'#'):
return # ignore priv msg
nn = Nick(trigger.nick)
now = time()
msg = trigger.args[1].strip().encode('utf-8', 'replace')
chan = trigger.args[0].encode('utf-8', 'replace')
data = (now, chan, msg)
willie.memory['seen_lock'].acquire()
try:
seen_insert(willie, nn.lower(), data)
finally:
willie.memory['seen_lock'].release()
@commands('seen')
@example(u'!seen tdreyer1')
def seen(willie, trigger):
'''Reports the last time a nick was seen.'''
willie.debug(u'seen:seen', u'triggered custom module', u'verbose')
if not perm_chk(trigger.hostmask, "Bc", willie):
return
if len(trigger.args[1].split()) == 1:
willie.reply(u"Seen who?")
return
nn = Nick(trigger.args[1].split()[1])
chan = trigger.args[0]
willie.memory['seen_lock'].acquire()
try:
if nn.lower() == willie.nick.lower():
willie.reply(u"[](/ohcomeon \"I'm right here!\")")
elif nn.lower() == trigger.nick.lower():
willie.reply(u"What am I, blind?")
elif nn in willie.memory['seen']:
last = willie.memory['seen'][nn][0]
chan = willie.memory['seen'][nn][1]
msg = willie.memory['seen'][nn][2]
td = timedelta(seconds=(time() - float(last)))
if td.total_seconds() < (60):
t = u'less than a minute ago'
elif td.total_seconds() < (3600):
min = td.total_seconds() / 60
if min != 1:
t = u'%i minutes ago' % min
else:
t = u'1 minute ago'
elif td.total_seconds() < (60 * 60 * 48):
hr = td.total_seconds() / 60 / 60
if hr != 1:
t = u'%i hours ago' % hr
else:
t = u'about an hour ago' % hr
else:
dt = datetime.utcfromtimestamp(last)
f_datetime = dt.strftime('%b %d, %Y at %H:%M')
t = u'on %s UTC ' % f_datetime
type = "saying"
msgtemp = re.sub(u"\u0001ACTION", nn, msg, 1)
if msgtemp != msg:
type = "doing"
msg = msgtemp
msg = re.sub(u"[\u0000-\u001F\u007F-\u009F]", "", msg)
willie.reply(u'I last saw %s in %s %s %s, "%s"' % (
colors.colorize(nn, [u'purple']),
chan,
t,
type,
colors.colorize(msg, [u'blue'])
))
return
else:
willie.reply(u"I've not seen '%s'." % nn)
finally:
willie.memory['seen_lock'].release()
if __name__ == "__main__":
print __doc__.strip()