def reconnect(self): """ reconnect to the irc server. """ try: if self.stopped: return 0 # determine how many seconds to sleep if self.reconnectcount > 0: reconsleep = self.reconnectcount * 15 rlog(10, self.name, 'sleeping %s seconds for reconnect' % \ reconsleep) time.sleep(reconsleep) if self.stopped: rlog(10, self.name, 'stopped.. not reconnecting') return 1 if self.connected: rlog(10, self.name, 'already connected .. not reconnecting') return 1 self.reconnectcount += 1 self.exit() rlog(10, self.name, 'reconnecting') result = self.connect() return result except Exception, ex: handle_exception()
def shutdown(): """ shutdown the cloud plugin """ try: stopcloud() stopserver() except Exception, ex: handle_exception()
def upgrade(): teller = 0 oldfile = datadir + os.sep + 'old' dbdir = datadir + os.sep + 'db' + os.sep + 'karma.db' if os.path.exists(dbdir): try: from gozerbot.database.db import Db db = Db(dbtype='sqlite') db.connect('db/karma.db') result = db.execute(""" SELECT * FROM karma """) if result: for i in result: try: karma.add(i[0], i[1]) except sa.exc.IntegrityError: pass teller += 1 result = db.execute(""" SELECT * FROM whokarma """) if result: for i in result: if i[2] == 'up': karma.setwhoup(i[0], i[1]) else: karma.setwhodown(i[0], i[1]) result = db.execute(""" SELECT * FROM whykarma """) if result: for i in result: karma.addwhy(*i) except Exception, ex: handle_exception() return teller
def dotest(testnr): exs = examples.getexamples() random.shuffle(exs) teller = 0 for i in exs: no = 0 for zz in donot: if i.find(zz) != -1: no = 1 break if no: continue teller += 1 try: ievent = Ircevent() ievent.nick = 'test' ievent.userhost = 'test@test' q = Queue.Queue() ievent.queues.append(q) ievent.channel = '#dunkbots' ievent.txt = i queues.append((testnr, teller, i, q)) if not plugins.trydispatch(bot, ievent): print "\ncan't execute %s\n" % i queues.remove((testnr, teller, i, q)) except: handle_exception()
def handle_listsglobal(bot, ievent): """ lists <listname> [',' <item>] .. global lists""" if not ievent.rest: ievent.missing("<listname> [',' <item>]") return try: listname, item = ievent.rest.split(',', 1) except ValueError: l = getlist('all', ievent.rest) if not l: ievent.reply('no %s list available' % ievent.rest) return result = [] for i in l: result.append("%s) %s" % (i.indx, i.item)) ievent.reply(result) return listname = listname.strip().lower() item = item.strip() if not listname or not item: ievent.missing("<listname> [',' <item>]") return result = 0 try: result = addtolist('all', listname, item) except Exception, ex: handle_exception() ievent.reply('ERROR: %s' % str(ex)) return
def handle_listsdel(bot, ievent): """ lists-del <listname> ',' <listofnrs> .. remove items with indexnr \ from list """ if not ievent.rest: ievent.missing('<listofnrs>') return try: nrs = [] for i in ievent.rest.split(): nrs.append(int(i)) except ValueError: ievent.reply('%s is not an integer' % i) return username = users.getname(ievent.userhost) nrs.sort() failed = [] itemsdeleted = 0 try: for i in nrs: result = delfromlist(username, i) if not result: failed.append(str(i)) else: itemsdeleted += 1 except Exception, ex: handle_exception() ievent.reply('ERROR: %s' % str(ex)) return
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 handle_alarmadd(bot, ievent): """ alarm <txt-with-time> | <+delta> <txt> .. add an alarm """ #if ievent.cmnd == 'DCC': # ievent.reply("sorry can't run alarm from dcc chat") # return if not ievent.rest: ievent.reply('alarm <txt-with-time> or alarm <+delta> <txt>') return else: alarmtxt = ievent.rest # see if alarm time is given as delta aka starts with + if alarmtxt[0] == '+': try: sec = int(ievent.args[0][1:]) # get nr of seconds to sleep except ValueError: ievent.reply('use +nrofsecondstosleep') return if len(ievent.args) < 2: ievent.reply('i need txt to remind you') return try: ttime = time.time() + sec # check for time overflow if ttime > 2**31: ievent.reply("time overflow") return # add alarm nrid = alarms.add(bot.name, ievent.nick, ttime, \ ' '.join(ievent.args[1:]), ievent.printto) ievent.reply("alarm %s set at %s" % (nrid, time.ctime(ttime))) return except Exception, ex: handle_exception(ievent) return
def reconnect(self): """ reconnect to the irc server. """ try: if self.stopped: return 0 # determine how many seconds to sleep if self.reconnectcount > 0: reconsleep = self.reconnectcount*15 rlog(10, self.name, 'sleeping %s seconds for reconnect' % \ reconsleep) time.sleep(reconsleep) if self.stopped: rlog(10, self.name, 'stopped.. not reconnecting') return 1 if self.connected: rlog(10, self.name, 'already connected .. not reconnecting') return 1 self.reconnectcount += 1 self.exit() rlog(10, self.name, 'reconnecting') result = self.connect() return result except Exception, ex: handle_exception()
def handle_installupdate(bot, ievent): """ update command for remote installed plugins """ updating = update() update_pass = [] update_fail = [] plugs = [] installer = Installer() if updating: updating.sort() ievent.reply('updating: %s' % ', '.join(updating)) for release in updating: parts = urlparse.urlparse(release) what = parts[2].split('/')[-1].replace('.py', '') try: installer.install(what) update_pass.append(what) except Exception, ex: handle_exception() update_fail.append(release) update_pass.sort() update_fail.sort() if update_fail: ievent.reply("failed updating %s" % " .. ".join(update_fail)) if update_pass: plugs = ['myplugs/%s.py' % plug for plug in update_pass] ievent.reply("reloading %s" % " .. ".join(plugs)) failed = plugins.listreload(plugs) if failed: ievent.reply("failed to reload %s" % ' .. '.join(failed)) return else: ievent.reply('done')
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 makeresult(request): try: result = request.server.do(request) except: handle_exception() return if result: return result
def rawsend(self, what): """ do a direct send. """ try: rlog(2, self.name, u"rawsend: %s" % unicode(jabberstrip(what))) if self.connection.isConnected(): self.connection.send(what) except: handle_exception()
def shutdown(self): try: self.stop = True self.socket.shutdown(2) self.socket.close() time.sleep(2) self.server_close() except Exception, ex: handle_exception()
def listen(): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((listenip, int(port))) s.listen(1) except Exception, e: handle_exception() os._exit(1)
def listen(): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((listenip, int(port))) s.listen(1) except Exception,e: handle_exception() os._exit(1)
def serve(self): rlog(10, self.name, 'starting server') while not self.stop: self.running = True try: got = self.poll.poll(100) except Exception, ex: handle_exception() if got: self.handle_request()
def run(self): """ run the thread """ try: if self.name not in dontshowthreads: rlog(-4, 'thr', 'running thread %s' % self.name) stats.up('threads', self.name) threading.Thread.run(self) except Exception, ex: handle_exception() time.sleep(0.1)
def found_terminator(self): if self.reading_headers: try: self.headers = self.buffer.split('\r\n') self.status = int(self.headers[0].split()[1]) except (ValueError, IndexError): handle_exception() self.buffer = '' self.reading_headers = False rlog(5, self.name, 'headers: %s' % self.headers)
def sendresult(self): try: result = self.server.do(self) if not result: return self.size = len(result) except Exception, ex: handle_exception() self.send_error(501) return
def stopserver(): try: if not server: rlog(10, 'cloud', 'server is already stopped') return server.stop = True server.server_close() time.sleep(3) except Exception, ex: handle_exception() pass
def startcloud(): global cloud try: cloud = Cloud() cloud.start(cfg.get('name'), cfg.get('port'), cfg.get('booturl')) aggregator.start() cloud.joinall(cfg.get('name'), cfg.get('port')) cloud.add(cfg.get('name'), url) rlog(10, 'cloud', 'total of %s nodes' % cloud.size()) return cloud except Exception, ex: handle_exception()
def getwikidata(url, ievent): """ fetch wiki data """ try: result = fromenc(geturl(url)) except IOError, ex: try: errno = ex[0] except IndexError: handle_exception(ievent=ievent) return ievent.reply('invalid option') return
def geturl_validate(url): """ validate url """ url = urlvalidate % urllib.urlencode({'uri': url}) try: result = geturl(url) except IOError, ex: try: errno = ex[0] except IndexError: handle_exception() return return False
def sendraw(self, msg): """ send a msg directly on the socket or connection. """ rlog(2, self.name, u"sendraw: %s" % unicode(msg)) if self.connection: try: if self.connection.__dict__.has_key('TCPsocket'): self.connection.TCPsocket.send(msg) else: self.connection.Connection.send(msg) except: handle_exception()
def shutdown(): """ shutdown webserver plugin """ global httpd if not httpd: return 1 try: httpd.stop = True httpd.server_close() except: handle_exception() pass time.sleep(3) return 1
def serve(insocket): global commandsdone f = insocket.makefile() while (1): try: r = f.readline() if not r: break rlog(100, 'DCC', r.strip()) commandsdone += 1 except Exception, ex: handle_exception() return
def run(self): """ run the bot command """ try: rlog(10, 'thr', 'running bot command thread %s' % self.name) stats.up('threads', self.name) result = threading.Thread.run(self) if self.ievent.closequeue: rlog(4, 'thr', 'closing queue for %s' % self.ievent.userhost) for i in self.ievent.queues: i.put_nowait(None) except Exception, ex: handle_exception(self.ievent) time.sleep(0.1)
def serve(insocket): global commandsdone f = insocket.makefile() while(1): try: r = f.readline() if not r: break rlog(100, 'DCC', r.strip()) commandsdone += 1 except Exception, ex: handle_exception() return
def urlcb(bot, ievent): if not state: return try: test_urls = re_url_match.findall(ievent.txt) for i in test_urls: if not state['urls'].has_key(bot.name): state['urls'][bot.name] = {} if not state['urls'][bot.name].has_key(ievent.channel): state['urls'][bot.name][ievent.channel] = [] if not i in state['urls'][bot.name][ievent.channel]: state['urls'][bot.name][ievent.channel].append(i) except Exception, ex: handle_exception()
def handle_webreload(bot, ievent): """ web-reload <handler> """ if not httpd: ievent.reply('webserver is not running') return try: what = ievent.args[0] except IndexError: ievent.missing('<handler>') return try: httpd.reloadhandler(what) except Exception, ex: handle_exception(ievent) return
def handle_cloudjoinall(bot, ievent): if not cfg.get('enable'): ievent.reply('cloud is not enabled') return def cb(client, result): if result.error: ievent.reply("%s: %s" %(client.name, result.error)) else: ievent.reply("%s: %s" % (client.name, result.data)) try: cloud.joinall(cfg.get('name'), cfg.get('port'), cb) except Exception, ex: handle_exception() ievent.reply('error joining %s: %s' % (ievent.rest, str(ex))) return
def upgrade(): rlog(10, 'infoitem', 'upgrading') teller = 0 dbdir = datadir + os.sep + 'db' + os.sep + 'infoitem.db' if os.path.exists(dbdir): try: from gozerbot.database.db import Db db = Db(dbtype='sqlite') db.connect('db/infoitem.db') result = db.execute(""" SELECT * FROM infoitems """) if result: for i in result: info.add(*i[1:]) teller += 1 except Exception, ex: handle_exception()
def connect(self, reconnect=True): """ connect to the server. """ res = 0 try: res = self._connect(reconnect) #except AttributeError: # rlog(10, self.name, "%s denied the connection" % self.host) # return except Exception, ex: if self.stopped: return 0 handle_exception() if reconnect: return self.reconnect()
def dohammer(): for j in range(nrtimes): try: ievent = Ircevent() ievent.nick = 'test' ievent.userhost = 'test@test' q = Queue.Queue() ievent.queue = q ievent.channel = '#dunkbots' ievent.txt = nail queues.append((nail, q)) if not plugins.trydispatch(ievent): print "\ncan't execute %s\n" % nail queues.remove((nail, q)) except: handle_exception()
def start_new_thread(func, arglist, kwargs=None): """ start a new thread .. set name to function/method name""" if not kwargs: kwargs = {} try: name = getname(func) if not name: name = 'noname' thread = Thr(None, target=func, name=name, args=arglist, \ kwargs=kwargs) rlog(-15, 'thr', 'starting %s thread' % str(func)) thread.start() return thread except: handle_exception() time.sleep(0.1)