Advertisement
Guest User

Untitled

a guest
May 13th, 2017
556
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.04 KB | None | 0 0
  1. from direct.showbase.ShowBase import ShowBase
  2. from gui.console import Console
  3. from direct.task import Task
  4. from string import split,strip
  5. import sys
  6. #sys.path.insert(1, os.path.join(sys.path[0], '..'))
  7.  
  8. import jabber
  9.  
  10.  
  11. #jabber.xmlstream.ENCODING='koi8-r'      # Default is "utf-8"
  12.  
  13.  
  14.  
  15.    
  16. class MyApp(ShowBase):
  17.     def __init__(self):
  18.         ShowBase.__init__(self)
  19.        
  20.         #self.xmpp = XMPP_Class(self)
  21.         #consolex = Console(self)
  22.         #Initialized the XMPP Class
  23.         r = XMPP_Class()
  24.         #Must be declared as global since it is used inside of the  XMPP_Class
  25.         global consolex
  26.         consolex = Console(r)
  27.         #Adds the listener to the task manager
  28.         self.taskMgr.add(r.cycleTask, "CycleChatTask")
  29.  
  30. class XMPP_Class():
  31.     True = 1
  32.     False = 0
  33.    
  34.     # Change this to 0 if you dont want a color xterm
  35.     USE_COLOR = 1
  36.     JID = ''
  37.     Aliases = {}
  38.     RAliases = {}
  39.     Who = ''
  40.     MyStatus = ''
  41.     MyShow   = ''
  42.     LastMessaged = ''
  43.     LastReceived = ''
  44.     def __init__(self):
  45.  
  46.         def usage():
  47.             print "%s: a simple python jabber client " % sys.argv[0]
  48.             print "usage:"
  49.             print "%s <server> - connect to <server> and register" % sys.argv[0]
  50.             print "%s <server> <username> <password> <resource>"   % sys.argv[0]
  51.             print "            - connect to server and login   "
  52.             sys.exit(0)
  53.  
  54.  
  55.         def doCmd(con,txt):
  56.             global Who
  57.             if txt[0] == '/' :
  58.                 cmd = split(txt)
  59.                 if cmd[0] == '/select':
  60.                     Who = cmd[1]
  61.                     print "%s selected" % cmd[1]
  62.                 elif cmd[0] == '/presence':
  63.                     to = cmd[1]
  64.                     type = cmd[2]
  65.                     con.send(jabber.Presence(to, type))
  66.                 elif cmd[0] == '/status':
  67.                     p = jabber.Presence()
  68.                     MyStatus = ' '.join(cmd[1:])
  69.                     p.setStatus(MyStatus)
  70.                     con.send(p)
  71.                 elif cmd[0] == '/show':
  72.                     p = jabber.Presence()
  73.                     MyShow = ' '.join(cmd[1:])
  74.                     p.setShow(MyShow)
  75.                     con.send(p)
  76.                 elif cmd[0] == '/subscribe':
  77.                     to = cmd[1]
  78.                     con.send(jabber.Presence(to, 'subscribe'))
  79.                 elif cmd[0] == '/unsubscribe':
  80.                     to = cmd[1]
  81.                     con.send(jabber.Presence(to, 'unsubscribe'))
  82.                 elif cmd[0] == '/roster':
  83.                     con.requestRoster()
  84.                     _roster = con.getRoster()
  85.                     for jid in _roster.getJIDs():
  86.                         print colorize(u"%s :: %s (%s/%s)"
  87.                                        % ( jid, _roster.getOnline(jid),
  88.                                            _roster.getStatus(jid),
  89.                                            _roster.getShow(jid),
  90.                                            ) , 'blue' )
  91.        
  92.                 elif cmd[0] == '/agents':
  93.                     print con.requestAgents()
  94.                 elif cmd[0] == '/register':
  95.                     agent = ''
  96.                     if len(cmd) > 1:
  97.                         agent = cmd[1]
  98.                     con.requestRegInfo(agent)
  99.                     print con.getRegInfo()
  100.                 elif cmd[0] == '/exit':
  101.                     con.disconnect()
  102.                     print colorize("Bye!",'red')
  103.                     sys.exit(0)
  104.                 elif cmd[0] == '/help':
  105.                     print "commands are:"
  106.                     print "   /select <jabberid>"
  107.                     print "      - selects who to send messages to"
  108.                     print "   /subscribe <jid>"
  109.                     print "      - subscribe to jid's presence"
  110.                     print "   /unsubscribe <jid>"
  111.                     print "      - unsubscribe to jid's presence"
  112.                     print "   /presence <jabberid> <type>"
  113.                     print "      - sends a presence of <type> type to the jabber id"
  114.                     print "   /status <status>"
  115.                     print "      - set your presence status message"
  116.                     print "   /show <status>"
  117.                     print "      - set your presence show message"
  118.                     print "   /roster"
  119.                     print "      - requests roster from the server and "
  120.                     print "        display a basic dump of it."
  121.                     print "   /exit"
  122.                     print "      - exit cleanly"
  123.                 else:
  124.                     print colorize("uh?", 'red')
  125.             else:
  126.                 if Who != '':
  127.                     msg = jabber.Message(Who, strip(txt))
  128.                     msg.setType('chat')
  129.                     #print "<%s> %s" % (JID, msg.getBody())
  130.                     con.send(msg)
  131.                 else:
  132.                     print colorize('Nobody selected','red')
  133.                    
  134.        
  135.         def messageCB(con, msg):
  136.             """Called when a message is recieved"""
  137.            
  138.             if msg.getBody(): ## Dont show blank messages ##\
  139.                 print "messageCB"
  140.                 if not str(msg.getFrom()).split('/')[0] in self.Aliases:
  141.                     consolex.write("[From: " + str(msg.getFrom()).split('/')[0] + "]: " + msg.getBody())    
  142.                 else:
  143.                     consolex.write("[From: " + self.Aliases[str(msg.getFrom()).split('/')[0]] + "]: " + msg.getBody())
  144.                 self.LastReceived = str(msg.getFrom()).split('/')[0]
  145.                 print self.LastReceived
  146.                    
  147.                
  148.        
  149.        
  150.         def presenceCB(con, prs):
  151.             """Called when a presence is recieved"""
  152.             who = str(prs.getFrom())
  153.             type = prs.getType()
  154.             if type == None: type = 'available'
  155.        
  156.             # subscription request:
  157.             # - accept their subscription
  158.             # - send request for subscription to their presence
  159.             if type == 'subscribe':
  160.                 print colorize(u"subscribe request from %s" % (who), 'blue')
  161.                 con.send(jabber.Presence(to=who, type='subscribed'))
  162.                 con.send(jabber.Presence(to=who, type='subscribe'))
  163.        
  164.             # unsubscription request:
  165.             # - accept their unsubscription
  166.             # - send request for unsubscription to their presence
  167.             elif type == 'unsubscribe':
  168.                 print colorize(u"unsubscribe request from %s" % (who), 'blue')
  169.                 con.send(jabber.Presence(to=who, type='unsubscribed'))
  170.                 con.send(jabber.Presence(to=who, type='unsubscribe'))
  171.        
  172.             elif type == 'subscribed':
  173.                 print colorize(u"we are now subscribed to %s" % (who), 'blue')
  174.        
  175.             elif type == 'unsubscribed':
  176.                 print colorize(u"we are now unsubscribed to %s"  % (who), 'blue')
  177.        
  178.             elif type == 'available':
  179.                 print colorize(u"%s is available (%s / %s)" % \
  180.                                (who, prs.getShow(), prs.getStatus()),'blue')
  181.             elif type == 'unavailable':
  182.                 print colorize(u"%s is unavailable (%s / %s)" % \
  183.                                (who, prs.getShow(), prs.getStatus()),'blue')
  184.        
  185.        
  186.         def iqCB(con,iq):
  187.             """Called when an iq is recieved, we just let the library handle it at the moment"""
  188.             pass
  189.        
  190.         def disconnectedCB(con):
  191.             print colorize("Ouch, network error", 'red')
  192.             sys.exit(1)
  193.        
  194.         def colorize(txt, col):
  195.             """Return colorized text"""
  196.             if not self.USE_COLOR: return txt ## DJ - just incase it breaks your terms ;) ##
  197.             if type(txt)==type(u''): txt=txt.encode(jabber.xmlstream.ENCODING,'replace')
  198.             cols = { 'red':1, 'green':2, 'yellow':3, 'blue':4}
  199.             initcode = '\033[;3'
  200.             endcode  = '\033[0m'
  201.             if type(col) == type(1):
  202.                 return initcode + str(col) + 'm' + txt + endcode
  203.             try: return initcode + str(cols[col]) + 'm' + txt + endcode
  204.             except: return txt
  205.        
  206.        
  207.         Server = 'isgeek.info'
  208.         Username = 'syddrafcray'
  209.         Password = ''
  210.         Resource = 'default'
  211.         while(Username == ''):
  212.             consolex.write("Please enter your Username")
  213.            
  214.         global con
  215.         con = jabber.Client(host=Server,debug=jabber.DBG_ALWAYS ,log=sys.stderr)
  216.        
  217.        
  218.         # Experimental SSL support
  219.         #
  220.         # con = jabber.Client(host=Server,debug=True ,log=sys.stderr,
  221.         #                    port=5223, connection=xmlstream.TCP_SSL)
  222.        
  223.         try:
  224.             con.connect()
  225.         except IOError, e:
  226.             print "Couldn't connect: %s" % e
  227.             sys.exit(0)
  228.         else:
  229.             print colorize("Connected",'red')
  230.        
  231.         con.registerHandler('message',messageCB)
  232.         con.registerHandler('presence',presenceCB)
  233.         con.registerHandler('iq',iqCB)
  234.         con.setDisconnectHandler(disconnectedCB)
  235.        
  236.         if con.auth(Username,Password,Resource):
  237.             print colorize(u"Logged in as %s to server %s" % ( Username, Server), 'red')
  238.         else:
  239.             print "eek -> ", con.lastErr, con.lastErrCode
  240.             sys.exit(1)
  241.        
  242.         print colorize("Requesting Roster Info" , 'red')
  243.         con.requestRoster()
  244.         con.sendInitPresence()
  245.         print colorize("Ok, ready" , 'red')
  246.         print colorize("Type /help for help", 'red')
  247.        
  248.         self.JID = Username + '@' + Server + '/' + Resource
  249.        
  250.  
  251.     def cycleTask(self, task):
  252.         con.process(0)
  253.         return Task.cont
  254.     def push(self, message):
  255.         msg = ''
  256.         parsed = message.split(' ')
  257.        
  258.         if (parsed[0] == '/w') and (len(parsed) >=3):
  259.             Who = parsed[1]
  260.             print Who
  261.             msg = ''
  262.             for i in range(2,len(parsed)):
  263.                 msg += (parsed[i] + ' ')
  264.             if '@' in Who:
  265.                 msg2 = jabber.Message(Who, strip(msg))
  266.                 msg2.setType('chat')
  267.                 #print "<%s> %s" % (JID, msg.getBody())
  268.                 con.send(msg2)
  269.                
  270.                 if not Who in self.Aliases:
  271.                     consolex.write("[To: " + Who + "]: " + msg)
  272.                 else:
  273.                     consolex.write("[To: " + self.Aliases[Who] + "]: " + msg)
  274.                 self.LastMessaged = Who
  275.             else:
  276.                 if Who in self.RAliases:
  277.                     msg2 = jabber.Message(self.RAliases[Who], strip(msg))
  278.                     msg2.setType('chat')
  279.                 #print "<%s> %s" % (JID, msg.getBody())
  280.                     con.send(msg2)
  281.                     consolex.write("[To: " + Who + "]: " + msg)
  282.                     self.LastMessaged = Who
  283.                 else:
  284.                     consolex.write("Error: Invalid Alias ID")
  285.                
  286.            
  287.        
  288.         elif (parsed[0] == '/r') and (len(parsed) >= 2):
  289.             for i in range(1,len(parsed)):
  290.                 msg += (parsed[i] + ' ')
  291.             Who = self.LastReceived
  292.             msg2 = jabber.Message(Who, strip(msg))
  293.             msg2.setType('chat')
  294.             #print "<%s> %s" % (JID, msg.getBody())
  295.             con.send(msg2)
  296.             if not Who in self.Aliases:
  297.                 consolex.write("[To: " + Who + "]: " + msg)
  298.             else:
  299.                 consolex.write("[To: " + self.Aliases[Who] + "]: " + msg)
  300.        
  301.         elif (parsed[0] == '/a') and (len(parsed) >=3):
  302.             if '@' in parsed[2]:
  303.                 self.Aliases[parsed[2]] = parsed[1]
  304.                 self.RAliases[parsed[1]] = parsed[2]
  305.                 consolex.write(parsed[1] + " now has the alias " + parsed[2])
  306.             else:
  307.                 consolex.write("Error: Invalid Syntax. Please use:")
  308.                 consolex.write("/a Joe joebob@sue.net")
  309.  
  310.  
  311.        
  312. app = MyApp()
  313. app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement