~ubuntu-branches/ubuntu/utopic/gozerbot/utopic

« back to all changes in this revision

Viewing changes to build/lib/gplugs/olddb/quote.py

  • Committer: Package Import Robot
  • Author(s): Jeremy Malcolm
  • Date: 2012-04-03 21:58:28 UTC
  • mfrom: (3.1.11 sid)
  • Revision ID: package-import@ubuntu.com-20120403215828-6mik0tzug5na93la
Tags: 0.99.1-2
* Removes logfiles on purge (Closes: #668767)
* Reverted location of installed files back to /usr/lib/gozerbot.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# plugs/quote.py
 
2
#
 
3
#
 
4
 
 
5
""" quotes plugin """
 
6
 
 
7
__copyright__ = 'this file is in the public domain'
 
8
 
 
9
from gozerbot.persist.persist import Persist
 
10
from gozerbot.utils.nextid import nextid
 
11
from gozerbot.commands import cmnds
 
12
from gozerbot.examples import examples
 
13
from gozerbot.datadir import datadir
 
14
from gozerbot.generic import lockdec, rlog
 
15
from gozerbot.plughelp import plughelp
 
16
from gozerbot.aliases import aliases
 
17
from gozerbot.config import config
 
18
if not config['nodb']:
 
19
    from gozerbot.database.db import db
 
20
from gplugs.olddb.karma import karma
 
21
import random, re, time, thread, os
 
22
 
 
23
plughelp.add('quote', 'manage quotes')
 
24
 
 
25
class Quoteitem(object):
 
26
 
 
27
    """ object representing a quote """
 
28
 
 
29
    def __init__(self, idnr, txt, nick=None, userhost=None, ttime=None):
 
30
        self.id = idnr
 
31
        self.txt = txt
 
32
        self.nick = nick
 
33
        self.userhost = userhost
 
34
        self.time = ttime
 
35
 
 
36
quoteslock = thread.allocate_lock()
 
37
locked = lockdec(quoteslock)
 
38
 
 
39
class Quotes(Persist):
 
40
 
 
41
    """ list of quotes """
 
42
 
 
43
    @locked
 
44
    def __init__(self, fname):
 
45
        Persist.__init__(self, fname)
 
46
        if not self.data:
 
47
            self.data = []
 
48
 
 
49
    def size(self):
 
50
        """ return nr of quotes """
 
51
        return len(self.data)
 
52
 
 
53
    @locked
 
54
    def add(self, nick, userhost, quote):
 
55
        """ add a quote """
 
56
        id = nextid.next('quotes')
 
57
        item = Quoteitem(id, quote, nick, userhost, \
 
58
time.time())
 
59
        self.data.append(item)
 
60
        self.save()
 
61
        return id
 
62
 
 
63
    @locked
 
64
    def addnosave(self, nick, userhost, quote, ttime):
 
65
        """ add quote but don't call save """
 
66
        id = nextid.next('quotes')
 
67
        item = Quoteitem(nextid.next('quotes'), quote, nick, userhost, ttime)
 
68
        self.data.append(item)
 
69
        return id
 
70
 
 
71
    @locked
 
72
    def delete(self, quotenr):
 
73
        """ delete quote with id == nr """
 
74
        for i in range(len(self.data)):
 
75
            if self.data[i].id == quotenr:
 
76
                del self.data[i]
 
77
                self.save()
 
78
                return 1
 
79
 
 
80
    def random(self):
 
81
        """ get random quote """
 
82
        if not self.data:
 
83
            return None
 
84
        quotenr = random.randint(0, len(self.data)-1)
 
85
        return self.data[quotenr]
 
86
 
 
87
    def idquote(self, quotenr):
 
88
        """ get quote by id """
 
89
        for i in self.data:
 
90
            if i.id == quotenr:
 
91
                return i
 
92
 
 
93
    def whoquote(self, quotenr):
 
94
        """ get who quoted the quote """
 
95
        for i in self.data:
 
96
            if i.id == quotenr:
 
97
                return (i.nick, i.time)
 
98
 
 
99
    def last(self, nr=1):
 
100
        """ get last quote """
 
101
        return self.data[len(self.data)-nr:]
 
102
 
 
103
    def search(self, what):
 
104
        """ search quotes """
 
105
        if not self.data:
 
106
            return []
 
107
        result = []
 
108
        andre = re.compile('and', re.I)
 
109
        ands = re.split(andre, what)
 
110
        got = 0
 
111
        for i in self.data:
 
112
            for item in ands:
 
113
                if i.txt.find(item.strip()) == -1:
 
114
                    got = 0
 
115
                    break  
 
116
                got = 1
 
117
            if got:                  
 
118
                result.append(i)
 
119
        return result
 
120
 
 
121
    def searchlast(self, what, nr=1):
 
122
        """ search quotes backwards limit to 1"""
 
123
        if not self.data:
 
124
            return []
 
125
        result = []
 
126
        andre = re.compile('and', re.I)
 
127
        ands = re.split(andre, what)
 
128
        got = 0
 
129
        for i in self.data[::-1]:
 
130
            for item in ands:
 
131
                if i.txt.find(item.strip()) == -1:
 
132
                    got = 0
 
133
                    break  
 
134
                got = 1
 
135
            if got:                  
 
136
                result.append(i)
 
137
                got = 0
 
138
        return result
 
139
 
 
140
class QuotesDb(object):
 
141
 
 
142
    """ quotes db interface """
 
143
 
 
144
    def size(self):
 
145
        """ return nr of quotes """
 
146
        result = db.execute(""" SELECT COUNT(*) FROM quotes """)
 
147
        return result[0][0]
 
148
 
 
149
    def add(self, nick, userhost, quote):
 
150
        """ add a quote """
 
151
        result = db.execute(""" INSERT INTO quotes(quote, userhost, \
 
152
createtime, nick) VALUES (%s, %s, %s, %s) """, (quote, userhost, \
 
153
time.time(), nick))
 
154
        return result
 
155
 
 
156
    def delete(self, quotenr):
 
157
        """ delete quote with id == nr """
 
158
        result = db.execute(""" DELETE FROM quotes WHERE indx = %s """, \
 
159
(quotenr, ))
 
160
        return result
 
161
 
 
162
    def random(self):
 
163
        """ get random quote """
 
164
        result = db.execute(""" SELECT indx FROM quotes """)
 
165
        indices = []
 
166
        if not result:
 
167
            return None
 
168
        for i in result:
 
169
            indices.append(i[0])
 
170
        if indices:
 
171
            idnr = random.choice(indices)
 
172
            return self.idquote(idnr)
 
173
 
 
174
    def idquote(self, quotenr):
 
175
        """ get quote by id """
 
176
        if quotenr == 0:
 
177
            return None
 
178
        result = db.execute(""" SELECT indx, quote FROM quotes WHERE \
 
179
indx = %s """, quotenr)
 
180
        if result:
 
181
            return Quoteitem(*result[0])
 
182
 
 
183
    def whoquote(self, quotenr):
 
184
        """ get who quoted the quote """
 
185
        result = db.execute(""" SELECT nick, createtime FROM quotes WHERE \
 
186
indx = %s """, (quotenr, ))
 
187
        if result:
 
188
            return result[0]
 
189
 
 
190
    def last(self, nr=1):
 
191
        """ get last quote """
 
192
        result = db.execute(""" SELECT indx, quote FROM quotes ORDER BY \
 
193
indx DESC LIMIT %s """, (nr, ))
 
194
        res = []
 
195
        if result:
 
196
            for i in result:
 
197
                res.append(Quoteitem(*i))
 
198
        return res
 
199
 
 
200
    def search(self, what):
 
201
        """ search quotes """
 
202
        result = db.execute(""" SELECT indx, quote FROM quotes WHERE \
 
203
quote LIKE %s """, '%%%s%%' % what)
 
204
        res = []
 
205
        if result:
 
206
            for i in result:
 
207
                res.append(Quoteitem(*i))
 
208
        return res
 
209
 
 
210
    def searchlast(self, what, nr):
 
211
        """ search quotes """
 
212
        result = db.execute(""" SELECT indx, quote FROM quotes WHERE \
 
213
quote LIKE %s ORDER BY indx DESC LIMIT %s """, ('%%%s%%' % what, nr))
 
214
        res = []
 
215
        if result:
 
216
            for i in result:
 
217
                res.append(Quoteitem(*i))
 
218
        return res
 
219
 
 
220
if not config['nodb']:
 
221
    quotes = QuotesDb()
 
222
else:
 
223
    quotes = Quotes(datadir + os.sep + 'quotes')
 
224
assert(quotes)
 
225
 
 
226
def size():
 
227
    """ return number of quotes """
 
228
    return quotes.size()
 
229
 
 
230
def search(what, queue):
 
231
    """ search the quotes """
 
232
    rlog(10, 'quote', 'searched for %s' % what)
 
233
    result = quotes.search(what)
 
234
    for i in result:
 
235
        queue.put_nowait("#%s %s" % (i.id, i.txt))
 
236
 
 
237
def handle_quoteadd(bot, ievent):
 
238
    """ quote-add <txt> .. add a quote """
 
239
    if not ievent.rest:
 
240
        ievent.missing("<quote>")
 
241
        return
 
242
    idnr = quotes.add(ievent.nick, ievent.userhost, ievent.rest)
 
243
    ievent.reply('quote %s added' % idnr)
 
244
 
 
245
cmnds.add('quote-add', handle_quoteadd, ['USER', 'QUOTEADD'], allowqueue=False)
 
246
examples.add('quote-add', 'quote-add <txt> .. add quote', 'quote-add mekker')
 
247
aliases.data['aq'] = 'quote-add'
 
248
 
 
249
def handle_quotewho(bot, ievent):
 
250
    """ quote-who <nr> .. show who added a quote """
 
251
    try:
 
252
        quotenr = int(ievent.args[0])
 
253
    except IndexError:
 
254
        ievent.missing("<nr>")
 
255
        return
 
256
    except ValueError:
 
257
        ievent.reply("argument must be an integer")
 
258
        return
 
259
    result = quotes.whoquote(quotenr)
 
260
    if not result or not result[0] or not result[1]:
 
261
        ievent.reply('no who quote data available')
 
262
        return
 
263
    print result
 
264
    ievent.reply('quote #%s was made by %s on %s' % (quotenr, result[0], result[1]))
 
265
 
 
266
cmnds.add('quote-who', handle_quotewho, ['USER', 'WEB', 'ANON', 'ANONQUOTE'])
 
267
examples.add('quote-who', 'quote-who <nr> .. show who quote <nr>', \
 
268
'quote-who 1')
 
269
aliases.data['wq'] = 'quote-who'
 
270
 
 
271
def handle_quotedel(bot, ievent):
 
272
    """ quote-del <nr> .. delete quote by id """
 
273
    try:
 
274
        quotenr = int(ievent.args[0])
 
275
    except IndexError:
 
276
        ievent.missing('<nr>')
 
277
        return
 
278
    except ValueError:
 
279
        ievent.reply('argument needs to be an integer')
 
280
        return
 
281
    if quotes.delete(quotenr):
 
282
        ievent.reply('quote deleted')
 
283
    else:
 
284
        ievent.reply("can't delete quote with nr %s" % quotenr)
 
285
 
 
286
cmnds.add('quote-del', handle_quotedel, ['QUOTEDEL', 'OPER', 'QUOTE'])
 
287
examples.add('quote-del', 'quote-del <nr> .. delete quote', 'quote-del 2')
 
288
aliases.data['dq'] = 'quote-del'
 
289
 
 
290
def handle_quotelast(bot, ievent):
 
291
    """ quote-last .. show last quote """
 
292
    search = ""
 
293
    try:
 
294
        (nr, search) = ievent.args
 
295
        nr = int(nr)  
 
296
    except ValueError:
 
297
        try:
 
298
            nr = ievent.args[0]
 
299
            nr = int(nr)
 
300
        except (IndexError, ValueError):
 
301
            nr = 1
 
302
            try:
 
303
                search = ievent.args[0]
 
304
            except IndexError:
 
305
                search = ""
 
306
    if nr < 1 or nr > 4:
 
307
        ievent.reply('nr needs to be between 1 and 4')
 
308
        return
 
309
    search = re.sub('^d', '', search)
 
310
    if search:
 
311
        quotelist = quotes.searchlast(search, nr)
 
312
    else:
 
313
        quotelist = quotes.last(nr)
 
314
    if quotelist != None:
 
315
        for quote in quotelist:
 
316
            qkarma = karma.get('quote %s' % quote.id)
 
317
            if qkarma:
 
318
                ievent.reply('#%s (%s) %s' % (quote.id, qkarma, quote.txt))
 
319
            else:
 
320
                ievent.reply('#%s %s' % (quote.id, quote.txt))
 
321
    else:
 
322
        ievent.reply("can't fetch quote")
 
323
 
 
324
cmnds.add('quote-last', handle_quotelast, ['USER', 'WEB', 'ANON', 'ANONQUOTE'])
 
325
examples.add('quote-last', 'show last quote', 'quote-last')
 
326
aliases.data['lq'] = 'quote-last'
 
327
 
 
328
def handle_quote2(bot, ievent):
 
329
    """ quote-2 .. show 2 random quotes """
 
330
    quote = quotes.random()
 
331
    if quote != None:
 
332
        qkarma = karma.get('quote %s' % quote.id)
 
333
        if qkarma:
 
334
            ievent.reply('#%s (%s) %s' % (quote.id, qkarma, quote.txt))
 
335
        else:
 
336
            ievent.reply('#%s %s' % (quote.id, quote.txt))
 
337
    else:
 
338
        ievent.reply('no quotes yet')
 
339
        return
 
340
    quote = quotes.random()
 
341
    if quote != None:
 
342
        qkarma = karma.get('quote %s' % quote.id)
 
343
        if qkarma:
 
344
            ievent.reply('#%s (%s) %s' % (quote.id, qkarma, quote.txt))
 
345
        else:
 
346
            ievent.reply('#%s %s' % (quote.id, quote.txt))
 
347
 
 
348
cmnds.add('quote-2', handle_quote2, ['USER', 'WEB', 'ANON', 'ANONQUOTE'])
 
349
examples.add('quote-2', 'quote-2 .. show 2 random quotes', 'quote-2')
 
350
aliases.data['2q'] = 'quote-2'
 
351
 
 
352
def handle_quoteid(bot, ievent):
 
353
    """ quote-id <nr> .. show quote by id """
 
354
    try:
 
355
        quotenr = int(ievent.args[0])
 
356
    except IndexError:
 
357
        ievent.missing('<nr>')
 
358
        return
 
359
    except ValueError:
 
360
        ievent.reply('argument must be an integer')
 
361
        return
 
362
    quote = quotes.idquote(quotenr)
 
363
    if quote != None:
 
364
        qkarma = karma.get('quote %s' % quote.id)
 
365
        if qkarma:
 
366
            ievent.reply('#%s (%s) %s' % (quote.id, qkarma, quote.txt))
 
367
        else:
 
368
            ievent.reply('#%s %s' % (quote.id, quote.txt))
 
369
    else:
 
370
        ievent.reply("can't fetch quote with id %s" % quotenr)
 
371
 
 
372
cmnds.add('quote-id', handle_quoteid, ['USER', 'WEB', 'ANON', 'ANONQUOTE'])
 
373
examples.add('quote-id', 'quote-id <nr> .. get quote <nr>', 'quote-id 2')
 
374
aliases.data['iq'] = 'quote-id'
 
375
 
 
376
def handle_quote(bot, ievent):
 
377
    """ quote .. show random quote """
 
378
    quote = quotes.random()
 
379
    if quote != None:
 
380
        qkarma = karma.get('quote %s' % quote.id)
 
381
        if qkarma:
 
382
            ievent.reply('#%s (%s) %s' % (quote.id, qkarma, quote.txt))
 
383
        else:
 
384
            ievent.reply('#%s %s' % (quote.id, quote.txt))
 
385
    else:
 
386
        ievent.reply('no quotes yet')
 
387
 
 
388
cmnds.add('quote', handle_quote, ['USER', 'WEB', 'ANON', 'ANONQUOTE'])
 
389
examples.add('quote', 'show random quote', 'quote')
 
390
aliases.data['q'] = 'quote'
 
391
 
 
392
def handle_quotesearch(bot, ievent):
 
393
    """ quote-search <txt> .. search quotes """
 
394
    if not ievent.rest:
 
395
        ievent.missing('<item>')
 
396
        return
 
397
    else:
 
398
        what = ievent.rest
 
399
        nrtimes = 3
 
400
    result = quotes.search(what)
 
401
    if result:
 
402
        if ievent.queues:
 
403
            res = []
 
404
            for quote in result:
 
405
                res.append('#%s %s' % (quote.id, quote.txt))
 
406
            ievent.reply(res)
 
407
            return            
 
408
        if nrtimes > len(result):
 
409
            nrtimes = len(result)
 
410
        randquotes = random.sample(result, nrtimes)
 
411
        for quote in randquotes:
 
412
            qkarma = karma.get('quote %s' % quote.id)
 
413
            if qkarma:
 
414
                ievent.reply('#%s (%s) %s' % (quote.id, qkarma, quote.txt))
 
415
            else:
 
416
                ievent.reply("#%s %s" % (quote.id, quote.txt))
 
417
    else:
 
418
        ievent.reply('no quotes found with %s' % what)
 
419
 
 
420
cmnds.add('quote-search', handle_quotesearch, ['USER', 'WEB', 'ANON', \
 
421
'ANONQUOTE'])
 
422
examples.add('quote-search', 'quote-search <txt> .. search quotes for <txt>'\
 
423
, 'quote-search bla')
 
424
aliases.data['sq'] = 'quote-search'
 
425
 
 
426
def handle_quotescount(bot, ievent):
 
427
    """ quote-count .. show number of quotes """
 
428
    ievent.reply('quotes count is %s' % quotes.size())
 
429
 
 
430
cmnds.add('quote-count', handle_quotescount, ['USER', 'WEB', 'ANON', \
 
431
'ANONQUOTE'])
 
432
examples.add('quote-count', 'count nr of quotes', 'quote-count')
 
433
aliases.data['cq'] = 'quote-count'
 
434
 
 
435
def handle_quotegood(bot, ievent):
 
436
    """ show top ten positive karma """
 
437
    result = karma.quotegood(limit=10)
 
438
    if result:
 
439
        resultstr = ""
 
440
        for i in result:
 
441
            if i[1] > 0:
 
442
                resultstr += "%s: %s " % (i[0], i[1])
 
443
        ievent.reply('quote goodness: %s' % resultstr)
 
444
    else:
 
445
        ievent.reply('quote karma void')
 
446
 
 
447
cmnds.add('quote-good', handle_quotegood, ['USER', 'WEB', 'ANON', 'ANONQUOTE'])
 
448
examples.add('quote-good', 'show top 10 quote karma', 'quote-good')
 
449
 
 
450
def handle_quotebad(bot, ievent):
 
451
    """ show top ten negative karma """
 
452
    result = karma.quotebad(limit=10)
 
453
    if result:
 
454
        resultstr = ""
 
455
        for i in result:
 
456
            if i[1] < 0:
 
457
                resultstr += "%s: %s " % (i[0], i[1])
 
458
        ievent.reply('quote badness: %s' % resultstr)
 
459
    else:
 
460
        ievent.reply('quote karma void')
 
461
 
 
462
cmnds.add('quote-bad', handle_quotebad, ['USER', 'WEB', 'ANON', 'ANONQUOTE'])
 
463
examples.add('quote-bad', 'show lowest 10 quote karma', 'quote-bad')