使用xmpp协议跟gtalk对话
首先开通两个gtalk帐号,相互加为好友。如xxxxx@gmail.com和yyyyy@gmail.com。
然后安装xmpppy-0.5.0rc1以上版本的xmpp库。
用xxxxx@gmail.com登录gtalk,然后跟yyyyy@gmail.com对话。
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, string
import time
import codecs
import threading
import getpass
import xmpp
programName=”
class Xmpp_Msg_Class(threading.Thread):
def __init__(self, threadName, loginUser, loginPasswd, xmppServer, xmppDomain, xmppPort):
threading.Thread.__init__(self)
self.name = threadName
self.loginUser = loginUser
self.loginPasswd = loginPasswd
self.xmppServer = xmppServer
self.xmppDomain = xmppDomain
self.xmppPort = xmppPort
self.isQuit = False
self.xmppTo = ”
self.client = None
self.conn = None
self.connOK = False
def __del__(self):
time.sleep(1) # some older servers will not send the message if you disconnect immediately after sending
if not self.client == None:
self.client.disconnect()
def quit(self):
self.isQuit = True
def run(self):
while True:
if self.isQuit:
break
if self.client == None:
if not self.ConnectToXmppServer():
print ‘ERROR: can not connect to XMPP server.’
self.client = None
time.sleep(5)
continue
if not self.client.isConnected():
if not self.client.reconnectAndReauth():
print ‘ERROR: can not connect to XMPP server.’
time.sleep(5)
continue
if self.client.Process(1) == None:
print ‘ERROR: lost connection!’
time.sleep(5)
time.sleep(0.1)
def ConnectToXmppServer(self):
print ‘Create Client: DOMAIN:%s, port:%u’ % (self.xmppDomain, 5222)
#self.client = xmpp.Client(self.xmppDomain, port=5222, debug=[‘always’])
self.client = xmpp.Client(self.xmppDomain, port=5222, debug=[])
print ‘Create Connect: SERVER:%s, port:%u’ % (self.xmppServer, self.xmppPort)
self.conn = self.client.connect((self.xmppServer, self.xmppPort), proxy=None, secure=None, use_srv=True)
if not self.conn:
print ‘ERROR: Could not connect to %s !’ % (self.xmppServer)
return False
print ‘INFO: Connected with ‘,self.conn
print ‘Create Auth: USER:%s, PASSWORD:%s’ % (self.loginUser.split(‘@’)[0], ‘******’)#self.loginPasswd)
auth=self.client.auth(self.loginUser.split(‘@’)[0], self.loginPasswd, resource=”, sasl=1)
if not auth:
print ‘ERROR: Could not authenticate with %s !’ % (self.xmppServer)
return False
print ‘INFO: Aauthenticated using ‘,auth
# …register some handlers (if you will register them before auth they will be thrown away)
print ‘Register Handle: presence/iq/message/disconnect’
self.client.RegisterHandler(‘presence’,self.presenceHandler)
self.client.RegisterHandler(‘iq’,self.iqHandler)
self.client.RegisterHandler(‘message’,self.messageHandler)
self.client.RegisterDisconnectHandler(self.disconnectHandler)
# …become available
print ‘INFO: Online’
self.client.sendInitPresence(requestRoster=0) # you may need to uncomment this for old server
print “============> I’m online <=============”
self.connOK = True
return True
def presenceHandler(self, conn,presence_node):
“”” Handler for playing a sound when particular contact became online “””
for targetJID in self.xmppTo:
if presence_node.getFrom().bareMatch(targetJID):
print ‘USER: %s has login!’ % (targetJID)
def iqHandler(self, conn,iq_node):
“”” Handler for processing some “get” query from custom namespace”””
reply=iq_node.buildReply(‘result’)
# … put some content into reply node
self.conn.send(reply)
raise NodeProcessed # This stanza is fully processed
def messageHandler(self, conn,mess_node):
print ‘Send message to <%s>, MSG: “%s”‘ % (str(mess_node.getFrom()), mess_node.getBody().encode(‘utf-8’))
id = self.client.send(xmpp.protocol.Message(str(mess_node.getFrom()), mess_node.getBody().encode(‘utf-8’)))
print ‘INFO: Sent message with id ‘,id
def disconnectHandler(self, conn,disconn_node):
print ‘INFO: Disconnect!’
def SendMsg(self, xmppTo, xmppMsg):
self.xmppTo = xmppTo
if not self.connOK:
print ‘ERROR: not connected to XMPP server.’
return
for tojid in self.xmppTo:
print ‘Send message to <%s>, MSG: “%s”‘ % (tojid, xmppMsg)
id = self.client.send(xmpp.protocol.Message(tojid, xmppMsg))
print ‘INFO: Sent message with id ‘,id
if self.client.Process(1) == None:
print ‘ERROR: lost connection!’
def OutputHelp():
print ‘Use XMPP to send messages to gtalk: ‘
print ‘Usage: ‘ + programName + ‘ ‘
print ‘Example: ‘ + programName + ‘ ‘
print ‘ ‘
if __name__ == ‘__main__’ :
programName = sys.argv[0]
if len(sys.argv) > 1:
OutputHelp()
sys.exit(0)
password = getpass.getpass(prompt=’Please input the password for “xxxxx@gmail.com”: ‘).strip()
if password == “”:
sys.exit(0)
xmpp_msg = Xmpp_Msg_Class(‘CHART’, ‘xxxxx@gmail.com’, password, ‘talk.google.com’, ‘gmail.com’, 443)
xmpp_msg.start()
time.sleep(5)
xmpp_msg.SendMsg([‘yyyyy@gmail.com’], ‘test测试1’)
while True:
input = raw_input(‘======>>>msg(“q” is quit)>>>: ‘).strip()
if input == ‘q’:
xmpp_msg.quit()
break
if input == ”:
continue
xmpp_msg.SendMsg([‘yyyyy@gmail.com’], input)
xmpp_msg.join()
sys.exit()