Skip to main content
 首页 » 编程设计

python之如何检索 Google Talk 用户状态消息

2025年05月04日10thcjp

我希望能够使用 Python 检索用户的 Google Talk 状态消息,很难找到关于如何使用其中一些库的文档。

请您参考如下方法:

我没有安装 xmpp 的任何东西,但这里有一些我手边的旧代码可能会对您有所帮助。出于测试目的,您需要将 USERNAME/PASSWORD 更新为您自己的值。

注意事项:登录到 Google Talk 的用户会在他们的用户 ID 上获得一个随机的在线状态字符串:如果您试图获取其他用户的状态,这无关紧要,但如果您想编写一些代码,那么要与自己交流,您需要区分从 GMail 或 GTalk 客户端登录的用户与测试程序。因此,代码会搜索用户 ID。

此外,如果您在登录后立即阅读状态,您可能什么也得不到。代码中存在延迟,因为状态需要一段时间才能变为可用。

"""Send a single GTalk message to myself""" 
 
import xmpp 
import time 
 
_SERVER = 'talk.google.com', 5223 
USERNAME = 'someuser@gmail.com' 
PASSWORD = 'whatever' 
 
 
def sendMessage(tojid, text, username=USERNAME, password=PASSWORD): 
    jid = xmpp.protocol.JID(username) 
    client = xmpp.Client(jid.getDomain(), debug=[]) 
    #self.client.RegisterHandler('message', self.message_cb) 
    if not client: 
      print 'Connection failed!' 
      return 
    con = client.connect(server=_SERVER) 
    print 'connected with', con 
    auth = client.auth(jid.getNode(), password, 'botty') 
    if not auth: 
      print 'Authentication failed!' 
      return 
    client.RegisterHandler('message', message_cb) 
    roster = client.getRoster() 
    client.sendInitPresence() 
    if '/' in tojid: 
        tail = tojid.split('/')[-1] 
        t = time.time() + 1 
        while time.time() < t: 
            client.Process(1) 
            time.sleep(0.1) 
            if [ res for res in roster.getResources(tojid) if res.startswith(tail) ]: 
                break 
        for res in roster.getResources(tojid): 
            if res.startswith(tail): 
                tojid = tojid.split('/', 1)[0] + '/' + res 
 
    print "sending to", tojid 
    id = client.send(xmpp.protocol.Message(tojid, text)) 
    t = time.time() + 1 
    while time.time() < t: 
        client.Process(1) 
        time.sleep(0.1) 
    print "status", roster.getStatus(tojid) 
    print "show", roster.getShow(tojid) 
    print "resources", roster.getResources(tojid) 
    client.disconnect() 
 
def message_cb(session, message): 
    print ">", message 
 
sendMessage(USERNAME + '/Talk', "This is an automatically generated gtalk message: did you get it?")