如何获取Google Talk用户的状态消息

2 投票
1 回答
1639 浏览
提问于 2025-04-16 04:48

我想用Python获取用户的Google Talk状态消息,但很难找到关于如何使用一些库的文档。

1 个回答

0

我手头没有安装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?")

撰写回答