fact module. gets a random line out of the file, still needs search support, adding, whatever else

This commit is contained in:
Brian S. Stephan 2010-07-26 18:14:33 -05:00
parent c8e3a4354b
commit 8fba54e33d
1 changed files with 44 additions and 0 deletions

View File

@ -511,6 +511,49 @@ class IrcAdmin(Module):
else:
connection.privmsg(replypath, replystr)
class FactFile(Module):
"""Returns a random fact/quote/whatever from one or more files
"""
def __init__(self, config, server, modlist):
super(FactFile, self).__init__(config, server, modlist)
modlist.append(self)
def register_handlers(self, server):
server.add_global_handler('pubmsg', self.on_pubmsg)
server.add_global_handler('privmsg', self.on_privmsg)
def do(self, connection, event, nick, userhost, replypath, what, admin_unlocked):
whats = what.split(' ')
try:
filename = self.config.get('fact', whats[0])
if replypath is not None:
what = self.try_recursion(connection, event, nick, userhost, replypath, what, admin_unlocked)
whats = what.split(' ')
# open file
if os.path.isfile(filename):
# http://www.regexprn.com/2008/11/read-random-line-in-large-file-in.html
file = open(filename, 'r')
count = 0
to_print = cur = file.readline()
while cur:
cur = file.readline()
count += 1
if random.randint(0, count) == 0:
# 1/count chance to replace
to_print = cur
# return text
if replypath is None:
return to_print.rstrip()
else:
connection.privmsg(replypath, to_print.rstrip())
else:
print('filename in config file for \'' + whats[0] + '\' is wrong')
except NoOptionError: pass
#####
# init
#####
@ -545,6 +588,7 @@ modlist = []
count = Countdown(config, server, modlist)
dice = Dice(config, server, modlist)
fact = FactFile(config, server, modlist)
admin = IrcAdmin(config, server, modlist)
gt = GoogleTranslate(config, server, modlist)
seen = Seen(config, server, modlist)