def register(self, bot, passwd): """ register a bot to nickserv. """ if self.has_key(bot.name) and self.has_key2(bot.name, 'nickserv'): bot.sendraw('PRIVMSG %s :%s %s' % (self.get(bot.name, \ 'nickserv'), 'REGISTER', passwd)) rlog(10, 'nickserv', 'register sent on %s' % bot.server)
def gcollect(): rlog(1, 'gcollect', 'running collector') gc.collect() time.sleep(5) gc.collect() time.sleep(5) gc.collect()
def add(self, session, item, value): item = item.lower() karma = Karma(item, value) session.add(karma) session.commit() rlog(10, 'karma', 'added %s: %s' % (item, value)) return 1
def handle_json(event): """ dispatch web request .. return json """ input = unquote_plus(event.path) bot = fleet.getfirstbot() ievent = Ircevent() try: what = input.split('?', 1)[1] except IndexError: return ["dispatch what ?", ] if what.startswith("command="): what = what[8:] ievent.txt = what ievent.nick = 'web' ievent.userhost = 'web@web' ievent.channel = 'web' q = Queue.Queue() ievent.queues.append(q) ievent.speed = 3 ievent.bot = bot result = [] if plugins.woulddispatch(bot, ievent): start_new_thread(plugins.trydispatch, (bot, ievent)) else: return ["can't dispatch %s" % ievent.txt, ] result = waitforqueue(q, 3) rlog(10, 'json', str(result)) try: res = dumps(result) except Exception, ex: handle_exception() res = []
def do(self, request): """ do a request """ path = request.path.split('?')[0] if path.endswith('/'): path = path[:-1] splitted = [] for i in path.split('/'): if i: splitted.append(i) splitted = tuple(splitted) for i in self.state['disable']: if i in splitted: rlog(10, self.name, 'denied disabled %s' % i) request.send_error(404) return request.splitted = splitted request.value = None type = request.command try: func = self.handlers[splitted][type] except (KeyError, ValueError): try: func = self.handlers[splitted[:-1]][type] request.value = splitted[-1] except (KeyError, ValueError): request.send_error(404) return result = func(self, request) return result
def connect(self, reconnect=True): """ connect to server/port using nick .. connect can timeout so catch exception .. reconnect if enabled. """ res = 0 try: res = self._connect() if res: self.connectok.wait() self._onconnect() self.connecting = False self.connected = True rlog(10, self.name, 'logged on !') except AlreadyConnecting: return 0 except AlreadyConnected: return 0 except Exception, ex: self.connectlock.release() if self.stopped: return 0 rlog(10, self.name, 'connecting error: %s' % str(ex)) if reconnect: self.reconnect() return raise
def sendraw(self, txt): """ send raw text to the server. """ if self.stopped: return rlog(2, self.name + '.sending', txt) self._raw(txt)
def init(): global perm, db perm = 'USER' db = {} db['file'] = datadir + os.sep + name + '.sqlite' db['url'] = "http://ams-9.net/data/" + name + '.sqlite' db['refresh'] = 86400 # read config if config[name + '_perm']: perm = config[name + '_perm'] rlog(10, name, 'perm set to: %s' % perm) if config[name + '_database']: db['file'] = config[name + '_database'] rlog(10, name, 'database set to: %s' % db['file']) # update the database if not os.path.exists(db['file']): db['age'] = '' else: age = os.stat(db['file'])[ST_MTIME] db['age'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(age)) fetch_database() db['jid'] = periodical.addjob(db['refresh'], 0, fetch_database, name) # register commands cmnds.add("route", handle_addr, perm) examples.add("route", 'lookup an IP', name + ' 66.66.66.66')
def scan(self, name): """ scan a rss url for used xml items """ try: result = self.getdata(name) except RssException, ex: rlog(10, 'rss', '%s error: %s' % (name, str(ex))) return
def fakein(self, txt): """ do a fake ircevent. """ if not txt: return rlog(10, self.name + '.fakein', txt) self.handle_ievent(Ircevent().parse(self, txt))
def handlesocket(self, sock, addr): while 1: time.sleep(0.001) try: input = sock.recv(4096) if not input: return except socket.timeout: continue except Exception, ex: try: (errno, errstr) = ex except ValueError: errno = 0 errstr = str(ex) if errno == 4: rlog(10, self.name, str(ex)) break if errno == 35: continue else: handle_exception() break if self.stop: break self.queue.put((input, addr))
def save(self): """ save karma data """ try: self.lock.acquire() karmafile = open(self.datadir + os.sep + 'karma', 'w') pickle.dump(self.karma, karmafile) karmafile.close() rlog(1, 'karma', '%s karma saved' % self.datadir) reasonupfile = open(self.datadir + os.sep + 'reasonup', 'w') pickle.dump(self.reasonup, reasonupfile) reasonupfile.close() rlog(1, 'karma', '%s reasonup saved' % self.datadir) reasondownfile = open(self.datadir + os.sep + 'reasondown', 'w') pickle.dump(self.reasondown, reasondownfile) reasondownfile.close() rlog(1, 'karma', '%s reasondown saved' % self.datadir) whoupfile = open(self.datadir + os.sep + 'whoup', 'w') pickle.dump(self.whoup, whoupfile) whoupfile.close() rlog(1, 'karma', '%s whoup saved' % self.datadir) whodownfile = open(self.datadir + os.sep + 'whodown', 'w') pickle.dump(self.whoup, whodownfile) whodownfile.close() rlog(1, 'karma', '%s whodown saved' % self.datadir) finally: self.lock.release()
def doscan(self, scanlist): for botname, channel, name, node in scanlist: try: result = geturl('http://%s/7.html' % node) except Exception, ex: rlog(10, 'shoutcast', "can't get %s shoutcast data: %s" % \ (node, str(ex))) continue try: res = result.split(',')[6] except IndexError: rlog(10, 'shoutcast', "can't match %s shoutcast data" % node) continue song = striphtml(res).strip().replace('\n', '') bot = fleet.byname(botname) if bot and channel in bot.state['joinedchannels']: got = False for ttime, played in self.songsplayed: if played == song: got = True if not got: self.songsplayed.append((time.time(), song)) bot.say(channel, "now playing on %s: %s" % (name, song)) else: for ttime, played in self.songsplayed: if time.time() - ttime > 1800: self.songsplayed.remove((ttime, played))
def geturl_title(url): """ fetch title of url """ try: result = geturl2(url) except urllib2.HTTPError, ex: rlog(10, 'snarf', str(ex)) return False
def __init__(self, ddir): rlog(0, 'karma', 'reading %s' % datadir + os.sep + 'karma') self.datadir = ddir self.lock = thread.allocate_lock() try: karmafile = open(ddir + os.sep + 'karma', 'r') self.karma = pickle.load(karmafile) karmafile.close() except: self.karma = {} try: reasonupfile = open(ddir + os.sep + 'reasonup', 'r') self.reasonup = pickle.load(reasonupfile) reasonupfile.close() except: self.reasonup = {} try: reasondownfile = open(ddir + os.sep + 'reasondown', 'r') self.reasondown = pickle.load(reasondownfile) reasondownfile.close() except: self.reasondown = {} try: whoupfile = open(ddir + os.sep + 'whoup', 'r') self.whoup = pickle.load(whoupfile) whoupfile.close() except: self.whoup = {} try: whodownfile = open(ddir + os.sep + 'whodown', 'r') self.whodown = pickle.load(whodownfile) whodownfile.close() except: self.whodown = {}
def scan(self, name): """ scan a rss url for used xml items """ try: result = self.getdata(name) except RssException, ex: rlog(10, "rss", "%s error: %s" % (name, str(ex))) return
def allowed(self, userhost, perms, log=True): """ check if user with userhosts is allowed to execute perm command """ if not type(perms) == types.ListType: perms = [ perms, ] if 'ANY' in perms: return 1 res = None name = self.getname(userhost) if not name: if log: rlog(10, 'users', '%s userhost denied' % userhost) return res result = self.db.execute( """ SELECT perm FROM perms WHERE \ name = %s """, name) if result: for i in result: if i[0] in perms: res = 1 if not res: if log: rlog(10, 'users', "%s perm %s denied" % (userhost, perms)) return res
def cb(client, result): if result.error: rlog(10, url, "can't sync: %s" % result.error) return for node in result.data: gnode = self.add(node[0], node[1]) gnode.synced = time.time()
def log(self, printto, txt): """ do the actual logging """ try: res = db.execute("""INSERT into tcplog(time,printto,txt) values(%s,%s,%s) """, (time.time(), printto, txt)) except Exception, ex: rlog(10, 'tcp', 'failed to log to db: %s' % str(ex))
def identify(self, bot): """ identify a bot to nickserv. """ if self.has_key(bot.name) and self.has_key2(bot.name, 'nickserv'): bot.say(self.get(bot.name, 'nickserv', ), '%s %s' % (self.get(bot.name, 'identify'), self.get(bot.name, 'password')), speed=9) rlog(10, 'nickserv', 'identify sent on %s' % bot.server)
def testasync(self, txt, timeout=0, kw={}): """ run txt with test ievent. don't close queues on exit.""" txt = txt.strip() ievent = Ircevent() ievent.bot = self ievent.cmnd = 'PRIVMSG' ievent.nick = 'test' ievent.userhost = 'test@test' ievent.origtxt = txt ievent.txt = ievent.origtxt ievent.channel = '#test' ievent.allowqueue = False ievent.closequeue = False if kw: for i, j in kw.iteritems(): setattr(ievent, i, j) if timeout: result = plugins.cmnd(self, ievent, timeout) else: result = plugins.cmnd(self, ievent, 10) rlog(100, self.name, str(result)) return result
def handle_join(self, ievent): """ handle joins. """ if ievent.nick in self.nicks401: rlog(10, self.name, "%s is available again" % ievent.nick) self.nicks401.remove(ievent.nick) chan = ievent.channel.lower() nick = ievent.nick.lower() # see if its the bot who is joining if nick == self.nick.lower(): # check if we already have a channels object, if not init it if not self.channels.has_key(chan): self.channels[chan] = {} self.channels[chan]['cc'] = self.cfg['defaultcc'] or '!' if not chan in self.state['joinedchannels']: self.state['joinedchannels'].append(chan) self.state.save() if chan in self.state['opchan']: self.state['opchan'].remove(chan) self.state.save() time.sleep(0.5) periodical.addjob(10, 1, self.who, self, chan) return # sync joined user with userhosts cache self.userhosts[nick] = ievent.userhost self.userchannels.adduniq(nick, chan)
def stop(self): """ stop the bot. """ self.stopped = 1 # shut down handlers rlog(10, self.name, 'stopped')
def iqHandler(self, conn, node): """ handle iq stanza's. """ rlog(5, self.name, str(node)) iq = Jabberiq(node) iq.toirc(self) jcallbacks.check(self, iq)
def add(self, name, url): """ add rss item """ rlog(10, 'rss', 'adding %s %s' % (name, url)) self.data[name] = Rssitem(name, url, [ 'title', ]) self.save()
def domail(mailto, txt, fromm=None, mailserver=None, subject=None): """ sent the mail """ if not txt: rlog(10, 'mail', 'no text to send') return if fromm: fromaddr = fromm else: fromaddr = config['mailfrom'] if not fromaddr: fromaddr = '*****@*****.**' if not mailserver: mailserver = config['mailserver'] if not mailserver: raise Mailservernotset if type(txt) != types.ListType: txt = [ txt, ] msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % \ (fromaddr, mailto, subject)) for i in txt: msg += "%s\r\n" % i server = smtplib.SMTP(mailserver) server.sendmail(fromaddr, mailto, msg)
def addemail(self, session, userhost, email): """ add an email address to the userhost. """ user = getuser(userhost, session) if user: user.email.append(email) rlog(10, 'users', '%s (%s) added to email' % (email, userhost)) return 1
def handle_001(self, bot, ievent): self.identify(bot) try: for i in self.data[bot.name]['nickservtxt']: self.sendstring(bot, i) rlog(10, 'nickserv', 'sent %s' % i) except: pass
def delallemail(self, session, name): """ Delete all emails for the specified user. """ user = byname(name, session) if user: user.email = [] rlog(10, 'users', '%s emails deleted' % (name, )) return 1
def addstatus(self, session, userhost, status): """ add status to given userhost. """ user = getuser(userhost, session) if user: user.statuses.append(status.upper()) rlog(10, 'users', '%s status %s added' % (name, status)) return 1
def _outloop(self): rlog(5, 'tcp', 'starting outloop') while not self.stop: (printto, txt) = self.outqueue.get() if self.stop: return self.dosay(printto, txt) rlog(5, 'tcp', 'stopping outloop')
def addperm(self, session, userhost, perm): """ add the specified perm to the userhost. """ user = getuser(userhost, session) if user: user.perms.append(perm.upper()) rlog(10, 'users', '%s perm %s added' % (userhost, perm)) return 1
def adduseremail(self, session, name, email): """ add email to specified user. """ user = byname(name, session) if user: user.email.append(email) rlog(10, 'users', '%s email %s added' % (name, email)) return 1
def handle_error(self, ievent): """ show error. """ if ievent.txt.startswith('Closing'): rlog(10, self.name, ievent.txt) else: rlog(10, self.name + '.ERROR', "%s - %s" % (ievent.arguments, \ ievent.txt))
def delallemail(self, name): """ Delete all emails for the specified user """ user = self.byname(name) if user: user.email = [] self.save() rlog(10, 'users', '%s emails deleted' % (name, )) return 1
def adduseremail(self, name, email): """ add email to specified user """ user = self.byname(name) if user: user.email.append(email) self.save() rlog(10, 'users', '%s email %s added' % (name, email)) return 1
def adduserstatus(self, name, status): """ add status to given user""" user = byname(name) if user: user.status.append(status.upper()) self.save() rlog(10, 'users', '%s status %s added' % (name, status)) return 1
def merge(self, name, userhost): """ add userhosts to user with name """ user = self.byname(name) if user: user.userhosts.append(userhost) self.save() rlog(10, 'users', "%s merged with %s" % (userhost, name)) return 1
def handle_700(self, ievent): """ handle 700 .. encoding request of the server. """ try: self.encoding = ievent.arguments[1] rlog(10, self.name, '700 encoding now is %s' % self.encoding) except: pass
def addperm(self, userhost, perm): """ add the specified perm to the userhost """ user = self.getuser(userhost) if user: user.perms.append(perm.upper()) self.save() rlog(10, 'users', '%s perm %s added' % (userhost, perm)) return 1
def addstatus(self, userhost, status): """ add status to given userhost""" user = self.getuser(userhost) if user: user.status.append(status.upper()) self.save() rlog(10, 'users', '%s status %s added' % (name, status)) return 1
def quit(self, reason='http://gozerbot.org'): """ send quit message. """ rlog(10, self.name, 'sending quit') try: self._raw('QUIT :%s' % reason) except IOError: pass
def addemail(self, userhost, email): """ add an email address to the userhost """ user = self.getuser(userhost) if user: user.email.append(email) self.save() rlog(10, 'users', '%s (%s) added to email' % (email, userhost)) return 1