forked from oliveratgithub/q
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq
436 lines (385 loc) · 15.4 KB
/
q
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012, 2013 Alexander Berntsen <[email protected]>
# Copyright (C) 2012, 2013 Stian Ellingsen <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Simple quizbot that asks questions and awards points."""
import config
import sqlite3
from getpass import getpass
from operator import itemgetter
from random import choice, shuffle
from sys import argv
from time import time
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor
import strings
import questions as q
class Bot(irc.IRCClient):
"""The bot procedures go here."""
def _get_nickname(self):
"""Sets Bot nick to our chosen nick instead of defaultnick."""
return self.factory.nickname
nickname = property(_get_nickname)
def connectionMade(self):
"""Overrides CONNECTIONMADE."""
# Identifies with nick services if password is set.
if config.password:
self.password = self.factory.password
self.username = self.factory.username
self.quizzers = {}
self.minplayernum = 2 if config.minplayers is None else config.minplayers
self.hint_patience = 6 if config.hintpatience is None else config.hintpatience
self.last_decide = 10
self.answered = 5
self.winner = ''
self.question = ''
if config.qrecyclethreshold is None:
self.recently_asked_threshold = ((20*len(q.questions))/100.0)
else:
self.recently_asked_threshold = ((config.qrecyclethreshold*len(q.questions))/100.0)
self.recently_asked = []
self.db = sqlite3.connect(config.hiscoresdb, isolation_level=None)
self.dbcur = self.db.cursor()
try:
self.dbcur.execute('CREATE TABLE IF NOT EXISTS hiscore (quizzer TEXT unique, wins INTEGER)')
except self.db.IntegrityError as e:
print('sqlite error: ', e.args[0])
self.db.commit()
self.hunger = 0
self.stamina = 6 if config.stamina is None else config.stamina
self.complained = False
irc.IRCClient.connectionMade(self)
def signedOn(self):
"""Overrides SIGNEDON."""
self.join(self.factory.channel)
print "signed on as %s" % (self.nickname)
def joined(self, channel):
"""Overrides JOINED."""
print "joined %s" % channel
self.op(self.nickname)
# Get all users in the chan.
self.sendLine("NAMES %s" % self.factory.channel)
reactor.callLater(5, self.reset)
reactor.callLater(5, self.decide)
def userJoined(self, user, channel):
"""Overrides USERJOINED."""
name = self.clean_nick(user)
self.add_quizzer(name)
self.complained = False
def userLeft(self, user, channel):
"""Overrides USERLEFT."""
self.del_quizzer(user)
def userQuit(self, user, channel):
"""Overrides USERQUIT."""
self.del_quizzer(user)
def userRenamed(self, oldname, newname):
"""Overrides USERRENAMED."""
self.del_quizzer(oldname)
self.add_quizzer(newname)
# Change quizzer name in DB to keep score.
if config.keepscore:
self.dbcur.execute('SELECT * FROM hiscore WHERE quizzer=?',
(oldname,))
row = self.dbcur.fetchone()
if row is not None:
self.dbcur.execute('UPDATE hiscore SET quizzer=? WHERE quizzer=?',
(newname, oldname))
self.db.commit()
def irc_RPL_NAMREPLY(self, prefix, params):
"""Overrides RPL_NAMEREPLY."""
# Add all users in the channel to quizzers.
for i in params[3].split():
if i != self.nickname:
self.add_quizzer(i)
def privmsg(self, user, channel, msg):
"""Overrides PRIVMSG."""
name = self.clean_nick(user)
# Check for answers.
if not self.answered:
if self.quizzers[name] is None:
self.quizzers[name] = 0
if str(self.answer).lower() in msg.lower():
self.award(name)
# Check if it's a command for the bot.
if msg.startswith('!help'):
try:
# !help user
self.help(msg.split()[1])
except:
# !help
self.help(name)
elif msg.startswith('!reload'):
self.reload_questions(name)
elif msg.startswith('!botsnack'):
self.feed()
elif msg.startswith('!op'):
self.op(name)
elif msg.startswith('!deop'):
self.deop(name)
elif msg.startswith('!score'):
self.print_score()
elif msg.startswith('!hiscore'):
self.print_hiscore()
# Unknown command.
elif msg[0] == '!':
self.msg(self.factory.channel if channel != self.nickname else
name, strings.unknowncmd)
def decide(self):
"""Wait for enough players."""
numPlayers = len(self.quizzers)
if numPlayers < self.minplayernum:
self.msg(self.factory.channel, strings.waiting)
reactor.callLater(30, self.decide)
return
else:
numPlayers += 1
if numPlayers >= self.minplayernum:
"""Figure out whether to post a question or a hint."""
t = time()
f, dt = ((self.ask, self.answered + 5 - t) if self.answered else
(self.hint, self.last_decide + self.hint_patience - t))
if dt < 0.5:
f()
self.last_decide = t
dt = 5
reactor.callLater(min(5, dt), self.decide)
def ask(self):
"""Make bot hungy."""
self.hunger += 1
if self.hunger > self.stamina:
if not self.complained:
self.msg(self.factory.channel,
strings.botsnack)
self.complained = True
return
"""Ask a question."""
# Make sure there have been ten questions in between this question.
while self.question in self.recently_asked or not self.question:
cqa = choice(q.questions)
self.question = cqa[1]
self.category = cqa[0]
# Clear recently asked questions when threshold is reached
if len(self.recently_asked) >= self.recently_asked_threshold:
self.recently_asked.pop(0)
self.recently_asked.append(self.question)
self.answer = cqa[2]
self.msg(self.factory.channel, strings.question %
(self.category, self.question))
if config.verbose:
print '%s - %s - %s' % (self.category, self.question, self.answer)
# Make list of hidden parts of the answer.
self.answer_masks = range(len(str(self.answer)))
# Set how many characters are revealed per hint.
self.difficulty = max(len(str(self.answer)) / 6, 1)
if isinstance(self.answer, str):
# Shuffle them around to reveal random parts of it.
shuffle(self.answer_masks)
else:
# Reveal numbers from left to right.
self.answer_masks = self.answer_masks[::-1]
# Number of hints given.
self.hint_num = 0
# Time of answer. 0 means no answer yet.
self.answered = 0
def hint(self):
"""Give a hint."""
# Max 5 hints, and don't give hints when the answer is so short.
if len(str(self.answer)) <= self.hint_num + 1 or self.hint_num >= 5:
if (len(str(self.answer)) == 1 and self.hint_num == 0):
self.msg(self.factory.channel, strings.hintone)
self.hint_num += 1
else:
self.fail()
return
# Reveal difficulty amount of characters in the answer.
for i in range(self.difficulty):
try:
# If hint is ' ', pop again.
while self.answer_masks.pop() == ' ':
pass
except:
pass
self.answer_hint = ''.join(
'*' if idx in self.answer_masks and c is not ' ' else c for
idx, c in enumerate(str(self.answer)))
self.msg(self.factory.channel, strings.hint % self.answer_hint)
self.hint_num += 1
def fail(self):
"""Timeout/giveup on answer."""
self.msg(self.factory.channel, strings.rightanswer % self.answer)
self.msg(self.factory.channel, strings.wishluck)
self.answered = time()
def award(self, awardee):
"""Gives a point to awardee."""
self.quizzers[awardee] += 1
self.msg(self.factory.channel, strings.correctanswer %
(self.answer, awardee))
if self.quizzers[awardee] == self.target_score:
self.win(awardee)
self.hunger = max(0, self.hunger - 1)
self.answered = time()
def win(self, winner):
"""Is called when target score is reached."""
numAnswerers = 0
quizzersByPoints = sorted(self.quizzers.iteritems(), key=itemgetter(1),
reverse=True)
for numAnswerers, (quizzer, points) in enumerate(quizzersByPoints):
if points is None:
break
else:
numAnswerers += 1
if numAnswerers > 1:
winner = quizzersByPoints[0][0]
self.dbcur.execute('SELECT * FROM hiscore WHERE quizzer=?',
(winner,))
wins = 1
row = self.dbcur.fetchone()
if row is not None:
wins = row[1] + 1
sql = 'UPDATE hiscore SET wins=? WHERE quizzer=?'
else:
sql = 'INSERT INTO hiscore (wins, quizzer) VALUES (?, ?)'
try:
self.dbcur.execute(sql, (wins, winner))
except self.db.IntegrityError as e:
print('sqlite error: ', e.args[0])
self.db.commit()
self.winner = winner
self.msg(self.factory.channel,
strings.winner % self.winner)
self.reset()
def help(self, user):
"""Message help message to the user."""
# Prevent spamming to non-quizzers, AKA random Freenode users.
if user not in self.quizzers:
return
self.msg(user, strings.help_channelinfo % self.factory.channel)
self.msg(user, strings.help_botinfo % self.nickname)
for msgline in strings.help:
self.msg(user, msgline)
def reload_questions(self, user):
"""Reload the question/answer list."""
if self.is_p(user, self.factory.masters):
reload(q)
self.msg(self.factory.channel, 'reloaded questions.')
def feed(self):
"""Feed quizbot."""
self.hunger = 0
self.complained = False
self.msg(self.factory.channel, strings.thanks)
def op(self, user):
"""OP a master."""
if self.is_p(user, self.factory.masters):
self.msg('CHANSERV', 'op %s %s' % (self.factory.channel, user))
def deop(self, user):
"""DEOP a master."""
if self.is_p(user, self.factory.masters):
self.msg('CHANSERV', 'deop %s %s' % (self.factory.channel, user))
def print_score(self):
"""Print the top five quizzers."""
prev_points = -1
for i, (quizzer, points) in enumerate(
sorted(self.quizzers.iteritems(), key=itemgetter(1),
reverse=True)[:5], 1):
if points:
if points != prev_points:
j = i
self.msg(self.factory.channel, strings.score %
(j, quizzer, points))
prev_points = points
def print_hiscore(self):
"""Print the top five quizzers of all time."""
self.dbcur.execute('SELECT * FROM hiscore ORDER by wins DESC LIMIT 5')
hiscore = self.dbcur.fetchall()
for i, (quizzer, wins) in enumerate(hiscore):
self.msg(self.factory.channel, strings.score %
(i + 1, quizzer.encode('UTF-8'), wins))
def set_topic(self):
self.dbcur.execute('SELECT * FROM hiscore ORDER by wins DESC LIMIT 1')
alltime = self.dbcur.fetchone()
if alltime is None:
alltime = ["no one", 0]
self.topic(
self.factory.channel, strings.channeltopic %
(self.target_score, self.winner, alltime[0].encode('UTF-8'),
alltime[1]))
def reset(self):
"""Set all quizzers' points to 0 and change topic."""
for i in self.quizzers:
self.quizzers[i] = None
self.target_score = 1 + len(self.quizzers) / 2
self.set_topic()
def add_quizzer(self, quizzer):
"""Add quizzer from quizzers."""
if quizzer == self.nickname or quizzer == '@' + self.nickname:
return
if quizzer not in self.quizzers:
self.quizzers[quizzer] = 0
def del_quizzer(self, quizzer):
"""Remove quizzer from quizzers."""
if quizzer == self.nickname or quizzer == '@' + self.nickname:
return
if quizzer in self.quizzers:
del self.quizzers[quizzer]
def is_p(self, name, role):
"""Check if name is role."""
try:
if name in role:
return True
except:
if name == role:
return True
if role == self.quizzers:
return False
self.msg(self.factory.channel, strings.invalidname % name)
self.kick(self.factory.channel, name, strings.kickmsg)
self.del_quizzer(name)
return False
def clean_nick(self, nick):
"""Cleans the nick if we get the entire name from IRC."""
nick = nick.split('!')[0]
if nick[0] == '~':
nick = nick.split('~')[1]
return nick
class BotFactory(protocol.ClientFactory):
"""The bot factory."""
protocol = Bot
def __init__(self, channel):
self.channel = channel
self.nickname = config.nickname
self.username = config.username
if config.password and isinstance(config.password, str):
self.password = config.password
elif config.password and config.password is True:
self.password = getpass('enter password (will not be echoed): ')
self.masters = config.masters
def clientConnectionLost(self, connector, reason):
print "connection lost: (%s)\nreconnecting..." % reason
connector.connect()
def clientConnectionFailed(self, connector, reason):
print "couldn't connect: %s" % reason
if __name__ == "__main__":
if len(argv) > 1:
print """
edit config.py.
start program with:
$ ./q
if you have set password in config, it will ask for it.
"""
else:
reactor.connectTCP(config.network, config.port,
BotFactory('#' + config.chan))
reactor.run()