[Otfbot-svn] r123 - in trunk: . helpers modules

cato- at BerliOS cato-
Mo Jun 25 23:01:17 CEST 2007


Author: cato-
Date: 2007-06-25 23:01:16 +0200 (Mon, 25 Jun 2007)
New Revision: 123

Modified:
   trunk/TODO
   trunk/control.py
   trunk/helpers/TCPclient.py
   trunk/modules/controlTCPMod.py
   trunk/otfbot.py
Log:
* corrected object-orientation

Modified: trunk/TODO
===================================================================
--- trunk/TODO	2007-06-24 11:36:42 UTC (rev 122)
+++ trunk/TODO	2007-06-25 21:01:16 UTC (rev 123)
@@ -13,6 +13,7 @@
 * limit the commands processed (maybe put some users temporarily on ignore) and limit the lines sent per minute
 modules:
 * extent modules-api
+* http://peak.telecommunity.com/DevCenter/PythonEggs
 logMod:
 * make logfilerotation working (should work, if needed more exactly use scheduler)
 rdfMod:

Modified: trunk/control.py
===================================================================
--- trunk/control.py	2007-06-24 11:36:42 UTC (rev 122)
+++ trunk/control.py	2007-06-25 21:01:16 UTC (rev 123)
@@ -128,7 +128,7 @@
 		elif command == "set":
 			return self._set(argument)
 		else:
-			return "Some helpful text"
+			return "config shell: '"+command+"' is not a valid command"
 			#self.bot.sendmsg(nick, "Syntax: config [get <key> [modul] [network] [channel]|set <key=value>]")
 
 
@@ -137,21 +137,17 @@
 	
 		this class only does the work, you need another class, most suitable is a bot-module, to have a userinterface
 	"""
-	MODUS_DEFAULT=0
-	MODUS_CONFIGSHELL=1
 	def __init__(self, bot):
 		"""
 			@type bot: a L{Bot} Instance
 		"""
 		self.bot=bot
-		self.modus=self.MODUS_DEFAULT
 		self.configshell=None
-		self.prompt=""
 	
 	def _output(self, string):
 		""" helper function which set the encoding to utf8
 		"""
-		return unicode(self.prompt+string).encode("utf-8")
+		return unicode(string).encode("utf-8")
 	
 	def input(self, request):
 		""" Pass your command to this function and get the output
@@ -166,98 +162,101 @@
 			argument=""
 		else:
 			(command, argument) = tmp
-		if command == "config":
-			self.configshell=configShell(self.bot)
-			return self._output("Entering configshell ...")
-		elif self.configshell:
+		if self.configshell:
 			output = self.configshell.input(request)
 			if (output == self.configshell.DESTROY_ME):
 				self.configshell=None
 				return self._output("Leaving configshell ...")
 			else:
 				return self._output(output)
-		elif command == "help":
-			return self._output("Available commands: reload, stop|quit, disconnect [network], connect network [port], listnetworks, currentnetwork, changenetwork network, changenick newnick, join channel, part channel [message], listchannels")
-		elif command == "shell":
-			if argument == "telnet":
-				self.prompt=self.bot.network+"> "
-			elif argument == "readline":
-				return self._output("01 +channels,"+",".join(self.bot.channels)+":+networks,"+",".join(self.bot.factory._getnetworkslist())+":config:help:reload:listmodules:stop:quit:disconnect,+networks:connect:listnetworks:currentnetwork:changenetwork,+networks:listchannels:changenick:join:part,+channels:kick")
-			elif argument == "prompt":
-				return self._output("02 "+self.bot.network)
-		elif command == "reload":
-			self.bot.reloadModules()
-			return self._output("Reloading all modules ...")
-		elif command == "listmodules":
-			module=[]
-			for mod in self.bot.mods:
-				module.append(mod.name)
-			return self._output(" ".join(module))
-		elif command == "stop" or command == "quit":
-			conns=self.bot.factory._getnetworkslist()
-			for c in conns:
-				self.bot.factory._getnetwork(c).quit()
-			return self._output("Disconnecting from all networks und exiting ...")
-		elif command == "disconnect":
-			conns=self.bot.factory._getnetworkslist()
-			if argument != "":
-				if argument in conns:
-					self.bot.factory._getnetwork(argument).quit()
-					return self._output("Disconnecting from "+str(argument))
-				else:
-					return self._output("Not connected to "+str(argument))
+		else:
+			try:
+				return self._output(getattr(self,"_cmd_"+command)(argument))
+			except AttributeError, e:
+				return self._output("no such command: "+str(command))
+			
+	def _cmd_config(self,argument):
+		self.configshell=configShell(self.bot)
+		return "Entering configshell ..."
+	def _cmd_help(self,argument):
+		commands = []
+		for c in dir(self):
+			if c[:5] == "_cmd_":
+				commands.append(c[5:])
+		return "Available commands: "+" ".join(commands)
+	def _cmd_reload(self,argument):
+		self.bot.reloadModules()
+		return "Reloading all modules ..."
+	def _cmd_listmodules(self,argument):
+		module=[]
+		for mod in self.bot.mods:
+			module.append(mod.name)
+		return " ".join(module)
+	def _cmd_stop(self,argument):
+		conns=self.bot.factory._getnetworkslist()
+		for c in conns:
+			self.bot.factory._getnetwork(c).quit()
+		return "Disconnecting from all networks und exiting ..."
+	def _cmd_disconnect(self,argument):
+		conns=self.bot.factory._getnetworkslist()
+		if argument != "":
+			if argument in conns:
+				self.bot.factory._getnetwork(argument).quit()
+				return "Disconnecting from "+str(argument)
 			else:
-				self.bot.quit("Bye.")
-				return self._output("Disconnecting from current network. Bye.")
-		elif command == "connect":
-			args = argument.split(" ")
-			if len(args) < 1 or len(args) > 2:
-				return self._output("Usage: connect irc.network.tld [port]")
+				return "Not connected to "+str(argument)
+		else:
+			self.bot.quit("Bye.")
+			return "Disconnecting from current network. Bye."
+	def _cmd_connect(self,argument):
+		args = argument.split(" ")
+		if len(args) < 1 or len(args) > 2:
+			return "Usage: connect irc.network.tld [port]"
+		else:
+			if len(args) == 2:
+				port=args[1]
 			else:
-				if len(args) == 2:
-					port=args[1]
-				else:
-					port=6667
-				c = self.bot.getReactor().connectTCP(args[0],port,self.bot.factory)
-				return self._output("Connecting to "+str(c))
-		elif command == "listnetworks":
-			return self._output("Currently connected to: "+" ".join(self.bot.factory._getnetworkslist()))
-		elif command == "currentnetwork":
-			return self._output("Current network: "+self.bot.network)
-		elif command == "changenetwork":
-			self.bot=self.bot.factory._getnetwork(argument)
-			return self._output("changed network to "+self.bot.network)
-		elif command == "listchannels":
-			return self._output("Currently in: "+" ".join(self.bot.channels))
-		elif command == "changenick":
-			if argument == "":
-				return self._output("Usage: changenick newnick")
+				port=6667
+			c = self.bot.getReactor().connectTCP(args[0],port,self.bot.factory)
+			return "Connecting to "+str(c)
+	def _cmd_listnetworks(self,argument):
+		return "Currently connected to: "+" ".join(self.bot.factory._getnetworkslist())
+	def _cmd_currentnetwork(self,argument):
+		return "Current network: "+self.bot.network
+	def _cmd_changenetwork(self,argument):
+		self.bot=self.bot.getFactory()._getnetwork(argument)
+		return "changed network to "+self.bot.network
+	def _cmd_listchannels(self,argument):
+		return "Currently in: "+" ".join(self.bot.channels)
+	def _cmd_changenick(self,argument):
+		if argument == "":
+			return "Usage: changenick newnick"
+		else:
+			self.bot.setNick(argument)
+	def _cmd_join(self,argument):
+		if argument == "":
+			return "Usage: join channel"
+		else:
+			self.bot.join(argument)
+			return "Joined "+str(argument)
+	def _cmd_part(self,argument):
+		args=argument.split(" ",1)
+		if len(args) == 0:
+			return "Usage: part channel [message]"
+		else:
+			if len(args) > 1:
+				partmsg=args[1]
 			else:
-				self.bot.setNick(argument)
-		elif command == "join":
-			if argument == "":
-				return self._output("Usage: join channel")
+				partmsg=""
+			self.bot.leave(args[0],partmsg)
+			return "Left "+args[0]
+	def _cmd_kick(self,argument):
+		args=argument.split(" ",2)
+		if len(args) < 2:
+			return "Usage: kick channel user [message]"
+		else:
+			if len(args) == 2:
+				self.bot.kick(args[0],args[1])
 			else:
-				self.bot.join(argument)
-				return self._output("Joined "+str(argument))
-		elif command == "part":
-			args=argument.split(" ",1)
-			if len(args) == 0:
-				return self._output("Usage: part channel [message]")
-			else:
-				if len(args) > 1:
-					partmsg=args[1]
-				else:
-					partmsg=""
-				self.bot.leave(args[0],partmsg)
-				return self._output("Left "+args[0])
-		elif command == "kick":
-			args=msg.split(" ",2)
-			if len(args) < 2:
-				return self._output("Usage: kick channel user [message]")
-			else:
-				if len(args) == 2:
-					self.bot.kick(args[0],args[1])
-				else:
-					self.bot.kick(args[0],args[1],args[3])
-				return self._output("Kicked "+args[1]+" from "+args[0]+".")
\ No newline at end of file
+				self.bot.kick(args[0],args[1],args[3])
+			return "Kicked "+args[1]+" from "+args[0]+"."
\ No newline at end of file

Modified: trunk/helpers/TCPclient.py
===================================================================
--- trunk/helpers/TCPclient.py	2007-06-24 11:36:42 UTC (rev 122)
+++ trunk/helpers/TCPclient.py	2007-06-25 21:01:16 UTC (rev 123)
@@ -5,32 +5,32 @@
 readline.parse_and_bind("tab: complete")
 
 class ARLCompleter:
-    def __init__(self,logic):
-        self.logic = logic
+	def __init__(self,logic):
+		self.logic = logic
 
-    def traverse(self,tokens,tree):
-        if tree is None:
-            return []
-        elif len(tokens) == 0:
-            return []
-        if len(tokens) == 1:
-            return [x+' ' for x in tree if x.startswith(tokens[0])]
-        else:
-            if tokens[0] in tree.keys():
-                return self.traverse(tokens[1:],tree[tokens[0]])
-            else:
-                return []
-        return []
+	def traverse(self,tokens,tree):
+		if tree is None:
+			return []
+		elif len(tokens) == 0:
+			return []
+		if len(tokens) == 1:
+			return [x+' ' for x in tree if x.startswith(tokens[0])]
+		else:
+			if tokens[0] in tree.keys():
+				return self.traverse(tokens[1:],tree[tokens[0]])
+			else:
+				return []
+		return []
 
-    def complete(self,text,state):
-        try:
-            tokens = readline.get_line_buffer().split()
-            if not tokens or readline.get_line_buffer()[-1] == ' ':
-                tokens.append("")
-            results = self.traverse(tokens,self.logic) + [None]
-            return results[state]
-        except Exception,e:
-            print e
+	def complete(self,text,state):
+		try:
+			tokens = readline.get_line_buffer().split()
+			if not tokens or readline.get_line_buffer()[-1] == ' ':
+				tokens.append("")
+			results = self.traverse(tokens,self.logic) + [None]
+			return results[state]
+		except Exception,e:
+			print e
 
 
 class BotProtocol(basic.LineOnlyReceiver):
@@ -90,7 +90,7 @@
 				print
 
 class BotProtocolFactory(protocol.ClientFactory):
-        protocol=BotProtocol
+		protocol=BotProtocol
 
 f=BotProtocolFactory()
 print reactor.connectTCP("localhost", 5022, f)

Modified: trunk/modules/controlTCPMod.py
===================================================================
--- trunk/modules/controlTCPMod.py	2007-06-24 11:36:42 UTC (rev 122)
+++ trunk/modules/controlTCPMod.py	2007-06-25 21:01:16 UTC (rev 123)
@@ -18,8 +18,8 @@
 #
 
 # TODO: * some authorization
-#       * configuring point of listening (TCP, SSL, Socket)
-#       * clientapp
+#	   * configuring point of listening (TCP, SSL, Socket)
+#	   * clientapp
 
 from twisted.internet import protocol, error
 from twisted.protocols import basic
@@ -27,31 +27,54 @@
 from control import configShell, controlInterface
 
 class BotProtocol(basic.LineOnlyReceiver):
-    def lineReceived(self, data):
-        result = self.control.input(data)
-        if result:
-            self.sendLine(result)
-        else:
-            self.sendLine("00")
-    def connectionMade(self):
-        if self.transport.client[0] == "127.0.0.1":
-            self.control=controlInterface(self.factory.bot)
-        else:
-            self.sendLine("Connection not allowed")
-            self.transport.loseConnection()
+	PLAIN=0
+	TELNET=1
+	READLINE=2
+	terminal=PLAIN
+	def _output(self, data):
+		if self.terminal == self.READLINE:
+			self.sendLine("02 "+self.factory.bot.network)
+			self.sendLine("01 +channels,"+",".join(self.factory.bot.channels)+":+networks,"+",".join(self.factory.bot.factory._getnetworkslist())+":config:help:reload:listmodules:stop:quit:disconnect,+networks:connect:listnetworks:currentnetwork:changenetwork,+networks:listchannels:changenick:join:part,+channels:kick")
+		if not data or data == "" and self.terminal == self.READLINE:
+			self.sendLine("00")
+		else:
+			self.sendLine(data)
+		
+	def lineReceived(self, data):
+		tmp = data.strip().split(" ",1)
+		if len(tmp) == 1:
+			command=tmp[0]
+			argument=""
+		else:
+			(command, argument) = tmp
+		if command == "shell":
+			if argument == "telnet":
+				self.terminal=self.TELNET
+			elif argument == "readline":
+				self.terminal=self.READLINE
+		elif data != "":
+			self._output(self.control.input(data))
+		else:
+			self._output("")
 
+	def connectionMade(self):
+		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):
-        self.bot=bot #.getFactory()._getnetwork(factory._getnetworkslist()[0])
-        self.protocol=BotProtocol
+	def __init__(self, bot):
+		self.bot=bot #.getFactory()._getnetwork(factory._getnetworkslist()[0])
+		self.protocol=BotProtocol
 
 class chatMod(chatMod.chatMod):
-    def __init__(self, bot):
-        self.bot=bot
-    def start(self):
-        f=BotProtocolFactory(self.bot)
-        try:
-            self.bot.getReactor().listenTCP(5022, f)
-        except (error.CannotListenError):
-            pass
-
+	def __init__(self, bot):
+		self.bot=bot
+	def start(self):
+		f=BotProtocolFactory(self.bot)
+		try:
+			self.bot.getReactor().listenTCP(5022, f)
+		except (error.CannotListenError):
+			pass

Modified: trunk/otfbot.py
===================================================================
--- trunk/otfbot.py	2007-06-24 11:36:42 UTC (rev 122)
+++ trunk/otfbot.py	2007-06-25 21:01:16 UTC (rev 123)
@@ -83,7 +83,7 @@
 	logging.getLogger('').addHandler(console)
 	#corelogger.addHandler(console)
 corelogger = logging.getLogger('core')
-corelogger.info("Starting OtfBot - Version svn "+str(svnversion))
+corelogger.info("Starting OtfBot - Version svn "+"$Revision$".split(" ")[1])
 
 def logerror(logger, module, exception):
 	""" format a exception nicely and pass it to the logger




Mehr Informationen über die Mailingliste Otfbot-dev