[Otfbot-svn] r111 - in trunk: . modules

cato- at BerliOS cato-
Do Jun 14 19:48:29 CEST 2007


Author: cato-
Date: 2007-06-14 19:48:28 +0200 (Thu, 14 Jun 2007)
New Revision: 111

Modified:
   trunk/config.py
   trunk/control.py
   trunk/modules/controlTCPMod.py
   trunk/modules/identifyMod.py
   trunk/modules/logMod.py
   trunk/modules/nobodyisperfectMod.py
   trunk/modules/rdfMod.py
   trunk/otfbot.py
   trunk/scheduler.py
Log:
* restructured Bot and BotFactory to use the framework in the correct way

Modified: trunk/config.py
===================================================================
--- trunk/config.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/config.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -184,6 +184,11 @@
 				ret.append(network)
 		return ret
 	def getChannels(self, network):
+		#TODO: Return only channels, which are active
+		# code from otfbot.py
+		#	for channel in channels:
+        #        if(not getBoolConfig('enabled','unset','main', network)):
+        #            channels.remove(channel)
 		if network in self.channel_options.keys():
 			try:
 				return self.channel_options[network].keys()

Modified: trunk/control.py
===================================================================
--- trunk/control.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/control.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -133,19 +133,19 @@
                 module.append(mod.name)
             return str(module)
         elif command == "stop" or command == "quit":
-            conns=self.bot.getConnections()
+            conns=self.bot.factory._getnetworkslist()
             for c in conns:
-                conns[c].disconnect()
+                self.bot.factory._getnetwork(c).quit()
+            #self.bot.getReactor().stop()
             return "Disconnecting from all networks und exiting ..."                
         elif command == "disconnect":
-            args = argument.split(" ")
-            conns=self.bot.getConnections()
-            if len(args) == 2:
-                if conns.has_key(args[1]):
-                    conns[args[1]].disconnect()
-                    return "Disconnecting from "+str(conns[args[1]].getDestination())
+            conns=self.bot.factory._getnetworkslist()
+            if argument != "":
+                if argument in conns:
+                    self.bot.factory._getnetwork(argument).quit()
+                    return "Disconnecting from "+str(argument)
                 else:
-                    return "Not connected to "+str(args[1])
+                    return "Not connected to "+str(argument)
             else:
                 self.bot.quit("Bye.")
                 return "Disconnecting from current network. Bye."                
@@ -155,19 +155,20 @@
                 return "Usage: connect irc.network.tld [port]"
             else:
                 if len(args) == 2:
-                    port=args[2]
+                    port=args[1]
                 else:
                     port=6667
-                self.bot.addConnection(args[1],port)
-                return "Connecting to "+str(self.bot.getConnections()[args[1]].getDestination())
+                c = self.bot.getReactor().connectTCP(args[0],port,self.bot.factory)
+                #self.bot.addConnection(args[1],port)
+                return "Connecting to "+str(c)
         elif command == "listnetworks":
-            ne=""
-            for n in self.bot.getConnections():
-                ne=ne+" "+n
-            return "Currently connected to:"+unicode(ne).encode("utf-8")
+            #ne=""
+            #for n in self.bot.getConnections():
+            #    ne=ne+" "+n
+            return "Currently connected to:"+unicode(self.bot.factory._getnetworkslist()).encode("utf-8")
         elif command == "listchannels":
             ch=""
-            for c in self.bot.channel:
+            for c in self.bot.channels:
                 ch=ch+" "+c
             return "Currently in:"+unicode(ch).encode("utf-8")
         elif command == "changenick":

Modified: trunk/modules/controlTCPMod.py
===================================================================
--- trunk/modules/controlTCPMod.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/modules/controlTCPMod.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -21,7 +21,7 @@
 #       * configuring point of listening (TCP, SSL, Socket)
 #       * clientapp
 
-from twisted.internet import reactor, protocol
+from twisted.internet import protocol, error
 from twisted.protocols import basic
 import chatMod
 from control import configShell, controlInterface
@@ -30,7 +30,11 @@
     def dataReceived(self, data):
         self.sendLine(self.control.input(data))
     def connectionMade(self):
-        self.control=controlInterface(self.factory.bot)
+        if self.transport.client[0] == "127.0.0.1":
+            self.control=controlInterface(self.factory.bot)
+        else:
+            self.sendLine("Connection not allowed")
+            self.transport.loseConnection()
 
 class BotProtocolFactory(protocol.ServerFactory):
     def __init__(self, bot):
@@ -42,5 +46,8 @@
         self.bot=bot
     def start(self):
         f=BotProtocolFactory(self.bot)
-        reactor.listenTCP(5022, f)
+        try:
+            self.bot.getReactor().listenTCP(5022, f)
+        except (error.CannotListenError):
+            pass
 

Modified: trunk/modules/identifyMod.py
===================================================================
--- trunk/modules/identifyMod.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/modules/identifyMod.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -45,7 +45,7 @@
 		if self.password != "":
 			self.logger.info("identifying to nickserv")
 			self.bot.sendmsg("nickserv", "identify "+self.password)
-			Thread(target=self.dowhois).start()
+			Thread(target=self.dowhois,name="identify").start()
 			self.whois=True
 		if self.bot.getBoolConfig("setBotFlag", "True", "identifyMod", self.bot.network):
 			self.logger.info("setting usermode +b")

Modified: trunk/modules/logMod.py
===================================================================
--- trunk/modules/logMod.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/modules/logMod.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -42,7 +42,7 @@
 		self.day=self.ts("%d") #saves the hour, to detect daychanges
 		#self.timer=threading.Timer(self.secsUntilDayChange(), self.dayChange)
 		#self.timer.start()
-		for c in self.bot.channel:
+		for c in self.bot.channels:
 			self.setNetwork()
 			self.joined(c)
 	

Modified: trunk/modules/nobodyisperfectMod.py
===================================================================
--- trunk/modules/nobodyisperfectMod.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/modules/nobodyisperfectMod.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -38,6 +38,7 @@
 		self.function=function
 		self.delay=delay
 	def run(self):
+		self.setName("nobodyisperfect")
 		self.end=False
 		while not self.end and self.delay >0:
 			time.sleep(1)

Modified: trunk/modules/rdfMod.py
===================================================================
--- trunk/modules/rdfMod.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/modules/rdfMod.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -44,6 +44,7 @@
 
 				
 	def run(self):
+		self.setName("identify")
 		while(not self.end):
 			#splits the waittime, to support stop()
 			#can be at end, too

Modified: trunk/otfbot.py
===================================================================
--- trunk/otfbot.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/otfbot.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -176,7 +176,6 @@
     #    file.write(option+"="+config[option]+"\n")
     file.write(theconfig.exportxml())
     file.close()
-
 schedulethread=scheduler.Schedule()
 schedulethread.start()
 
@@ -190,7 +189,7 @@
         #you may need to configure them first
         self.classes = classes
         self.users={}
-        self.channel=[]
+        self.channels=[]
         self.network=None
     
         self.mods = []
@@ -247,14 +246,8 @@
         return self.users
     def addScheduleJob(self, time, function):
         return addScheduleJob(time, function)
-    def getConnections(self):
-        return connections
-    def addConnection(self,address,port):
-        f = BotFactory(address,[])
-        connections[address]=reactor.connectTCP(unicode(address).encode("iso-8859-1"),port,f)
     def getReactor(self):
         return reactor
-
     def auth(self, user):
         """test if the user is privileged"""
         level=0
@@ -304,8 +297,10 @@
     
     # Callbacks
     def connectionMade(self):
-        self.network=self.factory.network
-        self.channels=self.factory.channels
+        self.network=self.transport.addr[0]
+        tmp=self.getChannels(self.network)
+        if tmp:
+            self.channels=tmp
         self.nickname=unicode(self.getConfig("nickname", "OtfBot", 'main', self.network)).encode("iso-8859-1")
         if len(self.network.split(".")) < 2:
             nw = self.network
@@ -327,21 +322,21 @@
     def signedOn(self):
         self.logger.info("signed on "+self.network+" as "+self.nickname)
 
-        for channel in self.factory.channels:
-            if(getBoolConfig("enabled", "false", "main", self.factory.network, channel)):
+        for channel in self.channels:
+            if(getBoolConfig("enabled", "false", "main", self.network, channel)):
                 self.join(unicode(channel).encode("iso-8859-1"))
         self._apirunner("signedOn")
 
     def joined(self, channel):
         self.logger.info("joined "+channel)
-        self.channel.append(channel)
+        self.channels.append(channel)
         self.users[channel]={}
         self._apirunner("joined",{"channel":channel})
 
     def left(self, channel):
         self.logger.info("left "+channel)
         del self.users[channel]
-        self.channel.remove(channel)
+        self.channels.remove(channel)
         self._apirunner("left",{"channel":channel})
 
     def privmsg(self, user, channel, msg):
@@ -415,7 +410,6 @@
     #    if answer: 
     #        self.ctcpMakeReply(user.split("!")[0], [(query,answer)])
     #        self.logger.info("Answered to CTCP "+query+" Request from "+user.split("!")[0])
-
         
     def userRenamed(self, oldname, newname):
         for chan in self.users:
@@ -439,30 +433,51 @@
             self.userQuit(line[1:].split(" ")[0],line.split("QUIT :")[1])
         else:
             irc.IRCClient.lineReceived(self,line)
-            
+
 class BotFactory(protocol.ReconnectingClientFactory):
     """The Factory for the Bot"""
     protocol = Bot
+    instances = {}
 
-    def __init__(self, networkname, channels):
-        self.network=networkname
-        self.channels = channels
+    def _addnetwork(self,addr,nw):
+        self.instances[addr] = nw
 
+    def _removenetwork(self,addr):
+        if self.instances.has_key(addr):
+            del self.instances[addr]
+    
+    def _getnetwork(self,addr):
+        return self.instances[addr]
+
+    def _getnetworkslist(self):
+        return self.instances.keys()
+
+    def _checkforshutdown(self):
+        if len(self.instances)==0:
+            corelogger.info("Not Connected to any network. Shutting down.")
+            schedulethread.stop()
+            #TODO: add sth to stop modules
+            reactor.stop()
+    
     def clientConnectionLost(self, connector, reason):
         clean = error.ConnectionDone()
         if reason.getErrorMessage() == str(clean):
-            del connections[self.network]
-            corelogger.info("Disconnected from "+self.network)
-            if (len(connections) == 0):
-                corelogger.info("Not Connected to any network. Shutting down.")
-                schedulethread.stop() #for stopping, comment out, if you use autoreconnect
-                #TODO: add sth to stop modules
-                reactor.stop()
-        #else:
-        #    corelogger.error("Disconnected: "+str(reason.getErrorMessage())+". Trying to reconnect")
+            self._removenetwork(connector.host)
+            self._checkforshutdown()
+            corelogger.info("Cleanly disconnected from "+connector.host)
+        else:
+            corelogger.error("Disconnected from "+connector.host+": "+str(reason.getErrorMessage())+".")
         #    connector.connect()
-    #def clientConnectionFailed(self, connector, reason):
-    #    reactor.stop()
+        
+    def clientConnectionFailed(self, connector, reason):
+        corelogger.error("Connection to "+connector.host+" failed: "+str(reason.getErrorMessage()))
+        self._removenetwork(connector.host)
+        self._checkforshutdown()
+    
+    def buildProtocol(self,addr):
+        proto=protocol.ReconnectingClientFactory.buildProtocol(self,addr)
+        self._addnetwork(addr.host, proto)
+        return proto
 
 try:
     configfile=parser.configfile
@@ -482,18 +497,18 @@
 networks=theconfig.getNetworks()
 connections={}
 if networks:
+    f = BotFactory()
     for network in networks:
         if(getBoolConfig('enabled', 'unset', 'main', network)):
-            channels=theconfig.getChannels(network)
-            if not channels:
-                channels=[]
-            for channel in channels:
-                if(not getBoolConfig('enabled','unset','main', network)):
-                    channels.remove(channel)
-            f = BotFactory(network, channels)
+            #channels=theconfig.getChannels(network)
+            #if not channels:
+            #    channels=[]
+            #for channel in channels:
+            #    if(not getBoolConfig('enabled','unset','main', network)):
+            #        channels.remove(channel)
             if (getBoolConfig('ssl','False','main',network)):
                 s = ssl.ClientContextFactory()
                 connections[network]=reactor.connectSSL(unicode(network).encode("iso-8859-1"), int(getConfig('port','6697','main',network)), f,s);
             else:
                 connections[network]=reactor.connectTCP(unicode(network).encode("iso-8859-1"), int(getConfig('port','6667','main',network)), f)
-    reactor.run()
+    reactor.run()
\ No newline at end of file

Modified: trunk/scheduler.py
===================================================================
--- trunk/scheduler.py	2007-06-13 23:21:02 UTC (rev 110)
+++ trunk/scheduler.py	2007-06-14 17:48:28 UTC (rev 111)
@@ -30,6 +30,7 @@
 		self.stopme=True
 
 	def run(self):
+		self.setName("schedular")
 		while not self.stopme:
 			time.sleep(60)
 			toremove=[]




Mehr Informationen über die Mailingliste Otfbot-dev