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

cato- at BerliOS cato-
Fr Jun 15 01:44:53 CEST 2007


Author: cato-
Date: 2007-06-15 01:44:53 +0200 (Fri, 15 Jun 2007)
New Revision: 112

Added:
   trunk/helpers/
   trunk/helpers/TCPclient.py
Modified:
   trunk/control.py
   trunk/modules/controlTCPMod.py
   trunk/otfbot.py
Log:
* added cmd-line controll client



Modified: trunk/control.py
===================================================================
--- trunk/control.py	2007-06-14 17:48:28 UTC (rev 111)
+++ trunk/control.py	2007-06-14 23:44:53 UTC (rev 112)
@@ -104,7 +104,11 @@
         self.bot=bot
         self.modus=self.MODUS_DEFAULT
         self.configshell=None
+        self.prompt=""
     
+    def _output(self, string):
+        return unicode(self.prompt+string).encode("utf-8")
+    
     def input(self, request):
         tmp = request.strip().split(" ",1)
         if len(tmp) == 1:
@@ -114,92 +118,96 @@
             (command, argument) = tmp
         if command == "config":
             self.configshell=configShell(self.bot)
-            return "Entering configshell ..."
+            return self._output("Entering configshell ...")
         elif self.configshell:
             output = self.configshell.input(request)
             if (output == self.configshell.DESTROY_ME):
                 self.configshell=None
-                return "Leaving configshell ..."
+                return self._output("Leaving configshell ...")
             else:
-                return output
+                return self._output(output)
         elif command == "help":
-            return "Available commands: reload, stop|quit, disconnect [network], connect network [port], listnetworks, changenick newnick, join channel, part channel [message], listchannels"
+            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 "Reloading all modules ..."
+            return self._output("Reloading all modules ...")
         elif command == "listmodules":
             module=[]
             for mod in self.bot.mods:
                 module.append(mod.name)
-            return str(module)
+            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()
-            #self.bot.getReactor().stop()
-            return "Disconnecting from all networks und exiting ..."                
+            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 "Disconnecting from "+str(argument)
+                    return self._output("Disconnecting from "+str(argument))
                 else:
-                    return "Not connected to "+str(argument)
+                    return self._output("Not connected to "+str(argument))
             else:
                 self.bot.quit("Bye.")
-                return "Disconnecting from current network. Bye."                
+                return self._output("Disconnecting from current network. Bye.")
         elif command == "connect":
             args = argument.split(" ")
             if len(args) < 1 or len(args) > 2:
-                return "Usage: connect irc.network.tld [port]"
+                return self._output("Usage: connect irc.network.tld [port]")
             else:
                 if len(args) == 2:
                     port=args[1]
                 else:
                     port=6667
                 c = self.bot.getReactor().connectTCP(args[0],port,self.bot.factory)
-                #self.bot.addConnection(args[1],port)
-                return "Connecting to "+str(c)
+                return self._output("Connecting to "+str(c))
         elif command == "listnetworks":
-            #ne=""
-            #for n in self.bot.getConnections():
-            #    ne=ne+" "+n
-            return "Currently connected to:"+unicode(self.bot.factory._getnetworkslist()).encode("utf-8")
+            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":
-            ch=""
-            for c in self.bot.channels:
-                ch=ch+" "+c
-            return "Currently in:"+unicode(ch).encode("utf-8")
+            return self._output("Currently in: "+" ".join(self.bot.channels))
         elif command == "changenick":
             if argument == "":
-                return "Usage: changenick newnick"
+                return self._output("Usage: changenick newnick")
             else:
                 self.bot.setNick(argument)
         elif command == "join":
             if argument == "":
-                return "Usage: join channel"
+                return self._output("Usage: join channel")
             else:
                 self.bot.join(argument)
-                return "Joined "+str(argument)
+                return self._output("Joined "+str(argument))
         elif command == "part":
             args=argument.split(" ",1)
             if len(args) == 0:
-                return "Usage: part channel [message]"
+                return self._output("Usage: part channel [message]")
             else:
                 if len(args) > 1:
                     partmsg=args[1]
                 else:
                     partmsg=""
                 self.bot.leave(args[0],partmsg)
-                return "Left "+args[0]
+                return self._output("Left "+args[0])
         elif command == "kick":
             args=msg.split(" ",2)
             if len(args) < 2:
-                return "Usage: kick channel user [message]"
+                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 "Kicked "+args[1]+" from "+args[0]+"."
+                return self._output("Kicked "+args[1]+" from "+args[0]+".")
\ No newline at end of file

Added: trunk/helpers/TCPclient.py
===================================================================
--- trunk/helpers/TCPclient.py	2007-06-14 17:48:28 UTC (rev 111)
+++ trunk/helpers/TCPclient.py	2007-06-14 23:44:53 UTC (rev 112)
@@ -0,0 +1,97 @@
+from twisted.internet import protocol, error, reactor
+from threading import Thread
+from twisted.protocols import basic
+import readline
+readline.parse_and_bind("tab: complete")
+
+class ARLCompleter:
+    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 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):
+	prompt="prompt"
+	def lineReceived(self, data):
+		noask=False
+		if data[0] == "0":
+			noask=True
+			if data[1] == "1":
+				logic={}
+				values={}
+				for x in data[3:].split(":"):
+					if x[0] == "+":
+						tmp=x[1:].split(",")
+						key=tmp.pop(0)
+						values[key]={}
+						for y in tmp:
+							values[key][y] = None
+					else:
+						tmp=x.split(",")
+						if len(tmp) == 1:
+							logic[tmp[0]]=None
+						else:
+							key=tmp.pop(0)
+							logic[key]={}
+							for y in tmp:
+								if y[0] == "+":
+									logic[key] = values[y[1:]]
+								else:
+									logic[key][y] = None
+				completer = ARLCompleter(logic)
+				readline.set_completer(completer.complete)
+			elif data[1] == "2":
+				self.prompt=data[3:]
+			elif data[1] == "0":
+				noask=False
+		else:
+			print data
+		if not noask:
+			self.ask()
+
+	def connectionMade(self):
+		print "connection made"
+		self.sendLine("hallo")
+		
+	def ask(self):
+		#end=False
+		#while not end:
+			try:
+				input = raw_input(self.prompt+"> ")
+				self.sendLine("shell prompt")
+				self.sendLine("shell readline")
+				self.sendLine(input)
+			except EOFError:
+		#		end=True
+				reactor.stop()
+				print
+
+class BotProtocolFactory(protocol.ClientFactory):
+        protocol=BotProtocol
+
+f=BotProtocolFactory()
+print reactor.connectTCP("localhost", 5022, f)
+reactor.run()

Modified: trunk/modules/controlTCPMod.py
===================================================================
--- trunk/modules/controlTCPMod.py	2007-06-14 17:48:28 UTC (rev 111)
+++ trunk/modules/controlTCPMod.py	2007-06-14 23:44:53 UTC (rev 112)
@@ -27,8 +27,12 @@
 from control import configShell, controlInterface
 
 class BotProtocol(basic.LineOnlyReceiver):
-    def dataReceived(self, data):
-        self.sendLine(self.control.input(data))
+    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)
@@ -38,7 +42,7 @@
 
 class BotProtocolFactory(protocol.ServerFactory):
     def __init__(self, bot):
-        self.bot=bot
+        self.bot=bot #.getFactory()._getnetwork(factory._getnetworkslist()[0])
         self.protocol=BotProtocol
 
 class chatMod(chatMod.chatMod):

Modified: trunk/otfbot.py
===================================================================
--- trunk/otfbot.py	2007-06-14 17:48:28 UTC (rev 111)
+++ trunk/otfbot.py	2007-06-14 23:44:53 UTC (rev 112)
@@ -248,6 +248,8 @@
         return addScheduleJob(time, function)
     def getReactor(self):
         return reactor
+    def getFactory(self):
+        return self.factory
     def auth(self, user):
         """test if the user is privileged"""
         level=0
@@ -321,8 +323,9 @@
     
     def signedOn(self):
         self.logger.info("signed on "+self.network+" as "+self.nickname)
-
-        for channel in self.channels:
+        channelstojoin=self.channels
+        self.channels=[]
+        for channel in channelstojoin:
             if(getBoolConfig("enabled", "false", "main", self.network, channel)):
                 self.join(unicode(channel).encode("iso-8859-1"))
         self._apirunner("signedOn")




Mehr Informationen über die Mailingliste Otfbot-dev