#!/usr/bin/python
# -*- coding: ISO-8859-1 -*-
import sys, xmpp, threading, time
# thread for listening to events
class events(threading.Thread):
global cl
def __init__(self, cl):
self.cl = cl
threading.Thread.__init__ (self)
def run(self):
self.keepGoing = True
# waiting for events
while self.keepGoing:
self.cl.Process(1)
# stop the loop for events
def stop(self):
self.keepGoing = False
# time.sleep(1)
# self.cl.disconnect() # there were errors on terminal
# thread that waits for user input
class waitCommand(threading.Thread):
def __init__(self, cl):
self.cl = cl
self.keepGoing = True
threading.Thread.__init__ (self)
def run(self):
while self.keepGoing:
cmd = raw_input()
if cmd == "bye":
self.keepGoing = False
elif cmd != "" and cmd.split()[0] == "send":
sendMessage(self.cl, cmd.split("\"")[2].split("to ")[1], \
cmd.split("\"")[1])
# send messages
def sendMessage(cl, to, msg):
cl.send(xmpp.Message(to, msg))
# handling income messages
def messageHandler(cl, msg):
presence_type=msg.getType()
if presence_type == "chat":
print ""
print "------------- New Message -------------"
print "From: " + str(msg.getFrom()).split("/")[0]
print "Message: " + str(msg.getBody())
print "---------------------------------------"
print ""
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) < 3:
print ""
print "Usage:"
print "python client.py <username> <password>"
print ""
print "* Attention: the username must be provided with '@domain.com'. *"
print ""
sys.exit(2)
# parameters from args
jabber_user = argv[1]
jabber_pw = argv[2]
jid=xmpp.protocol.JID(jabber_user)
cl=xmpp.Client(jid.getDomain(), debug=[])
# possible servers
if jid.getDomain() == "gmail.com":
jabber_server = "talk.google.com"
else:
print "Server not yet supported."
sys.exit(2)
# try to connect and login
print "Connecting..."
if not cl.connect((jabber_server,5222)):
raise IOError(1, "Couldn't connect to the server.")
print "Connected, trying to login...,"
if not cl.auth(jid.getNode(),jabber_pw):
raise IOError(2, "Login attempt failed. \
Are the provided username and password correct?")
print "Logged in! Enjoy your stay ;)."
# send a "hi there".. comment this for invisible connection
cl.sendInitPresence()
# handlers
cl.RegisterHandler("message", messageHandler)
# start the thread for events
threadEvents = events(cl)
threadEvents.start()
# start the thread for user input
threadWaitCommand = waitCommand(cl)
threadWaitCommand.start()
# main loop
while 1:
try:
if threadWaitCommand.keepGoing == True:
pass
else:
sys.exit(0)
except (SystemExit, KeyboardInterrupt):
threadEvents.stop()
print ""
print "Exiting, please wait..."
time.sleep(1)
sys.exit(0)
if __name__=='__main__':
main()
New comment