Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from direct.showbase.ShowBase import ShowBase
- from gui.console import Console
- from direct.task import Task
- from string import split,strip
- import sys
- #sys.path.insert(1, os.path.join(sys.path[0], '..'))
- import jabber
- #jabber.xmlstream.ENCODING='koi8-r' # Default is "utf-8"
- class MyApp(ShowBase):
- def __init__(self):
- ShowBase.__init__(self)
- #self.xmpp = XMPP_Class(self)
- #consolex = Console(self)
- #Initialized the XMPP Class
- r = XMPP_Class()
- #Must be declared as global since it is used inside of the XMPP_Class
- global consolex
- consolex = Console(r)
- #Adds the listener to the task manager
- self.taskMgr.add(r.cycleTask, "CycleChatTask")
- class XMPP_Class():
- True = 1
- False = 0
- # Change this to 0 if you dont want a color xterm
- USE_COLOR = 1
- JID = ''
- Aliases = {}
- RAliases = {}
- Who = ''
- MyStatus = ''
- MyShow = ''
- LastMessaged = ''
- LastReceived = ''
- def __init__(self):
- def usage():
- print "%s: a simple python jabber client " % sys.argv[0]
- print "usage:"
- print "%s <server> - connect to <server> and register" % sys.argv[0]
- print "%s <server> <username> <password> <resource>" % sys.argv[0]
- print " - connect to server and login "
- sys.exit(0)
- def doCmd(con,txt):
- global Who
- if txt[0] == '/' :
- cmd = split(txt)
- if cmd[0] == '/select':
- Who = cmd[1]
- print "%s selected" % cmd[1]
- elif cmd[0] == '/presence':
- to = cmd[1]
- type = cmd[2]
- con.send(jabber.Presence(to, type))
- elif cmd[0] == '/status':
- p = jabber.Presence()
- MyStatus = ' '.join(cmd[1:])
- p.setStatus(MyStatus)
- con.send(p)
- elif cmd[0] == '/show':
- p = jabber.Presence()
- MyShow = ' '.join(cmd[1:])
- p.setShow(MyShow)
- con.send(p)
- elif cmd[0] == '/subscribe':
- to = cmd[1]
- con.send(jabber.Presence(to, 'subscribe'))
- elif cmd[0] == '/unsubscribe':
- to = cmd[1]
- con.send(jabber.Presence(to, 'unsubscribe'))
- elif cmd[0] == '/roster':
- con.requestRoster()
- _roster = con.getRoster()
- for jid in _roster.getJIDs():
- print colorize(u"%s :: %s (%s/%s)"
- % ( jid, _roster.getOnline(jid),
- _roster.getStatus(jid),
- _roster.getShow(jid),
- ) , 'blue' )
- elif cmd[0] == '/agents':
- print con.requestAgents()
- elif cmd[0] == '/register':
- agent = ''
- if len(cmd) > 1:
- agent = cmd[1]
- con.requestRegInfo(agent)
- print con.getRegInfo()
- elif cmd[0] == '/exit':
- con.disconnect()
- print colorize("Bye!",'red')
- sys.exit(0)
- elif cmd[0] == '/help':
- print "commands are:"
- print " /select <jabberid>"
- print " - selects who to send messages to"
- print " /subscribe <jid>"
- print " - subscribe to jid's presence"
- print " /unsubscribe <jid>"
- print " - unsubscribe to jid's presence"
- print " /presence <jabberid> <type>"
- print " - sends a presence of <type> type to the jabber id"
- print " /status <status>"
- print " - set your presence status message"
- print " /show <status>"
- print " - set your presence show message"
- print " /roster"
- print " - requests roster from the server and "
- print " display a basic dump of it."
- print " /exit"
- print " - exit cleanly"
- else:
- print colorize("uh?", 'red')
- else:
- if Who != '':
- msg = jabber.Message(Who, strip(txt))
- msg.setType('chat')
- #print "<%s> %s" % (JID, msg.getBody())
- con.send(msg)
- else:
- print colorize('Nobody selected','red')
- def messageCB(con, msg):
- """Called when a message is recieved"""
- if msg.getBody(): ## Dont show blank messages ##\
- print "messageCB"
- if not str(msg.getFrom()).split('/')[0] in self.Aliases:
- consolex.write("[From: " + str(msg.getFrom()).split('/')[0] + "]: " + msg.getBody())
- else:
- consolex.write("[From: " + self.Aliases[str(msg.getFrom()).split('/')[0]] + "]: " + msg.getBody())
- self.LastReceived = str(msg.getFrom()).split('/')[0]
- print self.LastReceived
- def presenceCB(con, prs):
- """Called when a presence is recieved"""
- who = str(prs.getFrom())
- type = prs.getType()
- if type == None: type = 'available'
- # subscription request:
- # - accept their subscription
- # - send request for subscription to their presence
- if type == 'subscribe':
- print colorize(u"subscribe request from %s" % (who), 'blue')
- con.send(jabber.Presence(to=who, type='subscribed'))
- con.send(jabber.Presence(to=who, type='subscribe'))
- # unsubscription request:
- # - accept their unsubscription
- # - send request for unsubscription to their presence
- elif type == 'unsubscribe':
- print colorize(u"unsubscribe request from %s" % (who), 'blue')
- con.send(jabber.Presence(to=who, type='unsubscribed'))
- con.send(jabber.Presence(to=who, type='unsubscribe'))
- elif type == 'subscribed':
- print colorize(u"we are now subscribed to %s" % (who), 'blue')
- elif type == 'unsubscribed':
- print colorize(u"we are now unsubscribed to %s" % (who), 'blue')
- elif type == 'available':
- print colorize(u"%s is available (%s / %s)" % \
- (who, prs.getShow(), prs.getStatus()),'blue')
- elif type == 'unavailable':
- print colorize(u"%s is unavailable (%s / %s)" % \
- (who, prs.getShow(), prs.getStatus()),'blue')
- def iqCB(con,iq):
- """Called when an iq is recieved, we just let the library handle it at the moment"""
- pass
- def disconnectedCB(con):
- print colorize("Ouch, network error", 'red')
- sys.exit(1)
- def colorize(txt, col):
- """Return colorized text"""
- if not self.USE_COLOR: return txt ## DJ - just incase it breaks your terms ;) ##
- if type(txt)==type(u''): txt=txt.encode(jabber.xmlstream.ENCODING,'replace')
- cols = { 'red':1, 'green':2, 'yellow':3, 'blue':4}
- initcode = '\033[;3'
- endcode = '\033[0m'
- if type(col) == type(1):
- return initcode + str(col) + 'm' + txt + endcode
- try: return initcode + str(cols[col]) + 'm' + txt + endcode
- except: return txt
- Server = 'isgeek.info'
- Username = 'syddrafcray'
- Password = ''
- Resource = 'default'
- while(Username == ''):
- consolex.write("Please enter your Username")
- global con
- con = jabber.Client(host=Server,debug=jabber.DBG_ALWAYS ,log=sys.stderr)
- # Experimental SSL support
- #
- # con = jabber.Client(host=Server,debug=True ,log=sys.stderr,
- # port=5223, connection=xmlstream.TCP_SSL)
- try:
- con.connect()
- except IOError, e:
- print "Couldn't connect: %s" % e
- sys.exit(0)
- else:
- print colorize("Connected",'red')
- con.registerHandler('message',messageCB)
- con.registerHandler('presence',presenceCB)
- con.registerHandler('iq',iqCB)
- con.setDisconnectHandler(disconnectedCB)
- if con.auth(Username,Password,Resource):
- print colorize(u"Logged in as %s to server %s" % ( Username, Server), 'red')
- else:
- print "eek -> ", con.lastErr, con.lastErrCode
- sys.exit(1)
- print colorize("Requesting Roster Info" , 'red')
- con.requestRoster()
- con.sendInitPresence()
- print colorize("Ok, ready" , 'red')
- print colorize("Type /help for help", 'red')
- self.JID = Username + '@' + Server + '/' + Resource
- def cycleTask(self, task):
- con.process(0)
- return Task.cont
- def push(self, message):
- msg = ''
- parsed = message.split(' ')
- if (parsed[0] == '/w') and (len(parsed) >=3):
- Who = parsed[1]
- print Who
- msg = ''
- for i in range(2,len(parsed)):
- msg += (parsed[i] + ' ')
- if '@' in Who:
- msg2 = jabber.Message(Who, strip(msg))
- msg2.setType('chat')
- #print "<%s> %s" % (JID, msg.getBody())
- con.send(msg2)
- if not Who in self.Aliases:
- consolex.write("[To: " + Who + "]: " + msg)
- else:
- consolex.write("[To: " + self.Aliases[Who] + "]: " + msg)
- self.LastMessaged = Who
- else:
- if Who in self.RAliases:
- msg2 = jabber.Message(self.RAliases[Who], strip(msg))
- msg2.setType('chat')
- #print "<%s> %s" % (JID, msg.getBody())
- con.send(msg2)
- consolex.write("[To: " + Who + "]: " + msg)
- self.LastMessaged = Who
- else:
- consolex.write("Error: Invalid Alias ID")
- elif (parsed[0] == '/r') and (len(parsed) >= 2):
- for i in range(1,len(parsed)):
- msg += (parsed[i] + ' ')
- Who = self.LastReceived
- msg2 = jabber.Message(Who, strip(msg))
- msg2.setType('chat')
- #print "<%s> %s" % (JID, msg.getBody())
- con.send(msg2)
- if not Who in self.Aliases:
- consolex.write("[To: " + Who + "]: " + msg)
- else:
- consolex.write("[To: " + self.Aliases[Who] + "]: " + msg)
- elif (parsed[0] == '/a') and (len(parsed) >=3):
- if '@' in parsed[2]:
- self.Aliases[parsed[2]] = parsed[1]
- self.RAliases[parsed[1]] = parsed[2]
- consolex.write(parsed[1] + " now has the alias " + parsed[2])
- else:
- consolex.write("Error: Invalid Syntax. Please use:")
- consolex.write("/a Joe joebob@sue.net")
- app = MyApp()
- app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement