from twisted.internet.protocol import Factory, Protocol from twisted.internet import reactor from twisted.protocols.basic import LineReceiver class QOTD(LineReceiver): def connectionMade(self): #send welcome message, add user to ram self.sendLine("Richies Telnet Chat, Powered By: \ Python http://www.python.org, Twisted http://twistedmatrix.com\r\n\r\n\ Please type a username to begin:") self.factory.connections.append(self.transport) self.factory.username[self.transport] = "" def lineReceived(self, line): if self.factory.username[self.transport] == "": #set username self.factory.username[self.transport] = line self.sendLine("\r\nSet Username, You may now chat! Type !userlist for a userlist.") #send connected msg for clicon in self.factory.connections: if clicon <> self.transport: clicon.write("%s has Connected\r\n" % (self.factory.username[self.transport])) elif line.lower() == "!userlist": strusrlst = "\r\n----------\r\n" for usrlst in self.factory.username: strusrlst = "%s%s\r\n" % (strusrlst, self.factory.username[usrlst]) strusrlst = strusrlst + "----------\r\n" self.sendLine(strusrlst) else: #send to all clients for clicon in self.factory.connections: if clicon <> self.transport: clicon.write("%s says: %s\r\n" % (self.factory.username[self.transport], line)) def connectionLost(self, reason): #send disconnected msg for clicon in self.factory.connections: if clicon <> self.transport: clicon.write("%s has Disconnected\r\n" % (self.factory.username[self.transport])) #cleanup user from ram del self.factory.username[self.transport] self.factory.connections.remove(self.transport) class QOTDFactory(Factory): protocol = QOTD def __init__(self): self.connections = [] self.username = {} reactor.listenTCP(8007, QOTDFactory()) reactor.run()