Search code examples
pythonclienttwistedirc

python twisted simple client - server communication


Trying to get a simple python twisted client - server application working. The intention will be to use this to control a few IRC bots; like a master console to issue commands to all (5ish) bots.

The attached code will form into the server code, someday. For the moment, I'm using telnet to simulate the IRC bots (clients) connecting to the "party line".

What I'm stuck on is, how do I, from the server application attached, sendLine to all the bots? Every time I create a loop to get raw_input, I end up stalling the execution. I've thought about testing against a connection state function, but can't seem to find that (if connection is true, raw_input sort of logic).

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class bottalk(LineReceiver):

    botlist = []

    def lineReceived(self, line):
        botlistspot = len(self.botlist)
        self.botlist.append(line)
        print self.botlist[botlistspot] + " checked in."

class botfactory(Factory):

    def buildProtocol(self, addr):
        return bottalk()

reactor.listenTCP(8123, botfactory())
reactor.run() 

I've tried to place the following raw_input inside of the LineReceiver class, outside. All over.. I want this raw_input prompt to continually prompt for input, not just after a event like a line received - all the time.. I want the server bot console always ready to accept my input and sendLine to all the bots.

sendLine(raw_input("> "))

Solution

  • Don't use raw_input at all. Instead, instantiate a stdio.StandardIO, giving its constructor an instance of your LineReceiver subclass. The lineReceived you defined in the subclass will be called whenever a new line is available on stdin, and then you can broadcast it to the bots.

    This example from the Twisted site demonstrates the idea.