我正在使用sleekmpp python使用GCM / CCS与我的Android客户端进行通信。主要问题是数据是json格式,需要在gcm标签内。我怎样才能实现它?
这是我的代码:
#!/usr/bin/python
import sys
import logging
import getpass
from optparse import OptionParser
import sleekxmpp
import json
from sleekxmpp import Iq
from sleekxmpp.xmlstream import ElementBase, register_stanza_plugin
REGISTRATION_ID = "APA91bF61NHoXfH4gHojuejpodfghdfvbnazqsrfsgdvfdodxdufcokojnogfvr4ijUbsTWzc-u9lsE2XkkNyQ"
class AA(ElementBase):
name = 'gcm'
namespace = 'google:mobile:data'
plugin_attrib = 'aa'
interfaces = set(['to', 'message_id', 'data'])
sub_interfaces = interfaces
register_stanza_plugin(Iq, AA)
SERVER = 'gcm.googleapis.com'
PORT = 5235
USERNAME = "1013691256357"
PASSWORD = "AIAASDFSefeffefEFEFFeFfefefefEFEFfefefefFEffeFf7qeO1zB0Vt4"
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding('utf8')
else:
raw_input = input
class SendMsgBot(sleekxmpp.ClientXMPP):
def __init__(self, jid, password):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.add_event_handler("message", self.start)
def start(self, event):
print event
self.send_presence()
self.get_roster()
self.disconnect(wait=True)
if __name__ == '__main__':
# Setup logging.
# logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s %(message)s')
xmpp = SendMsgBot(USERNAME, PASSWORD)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0199') # XMPP Ping
if xmpp.connect(('gcm.googleapis.com', 5235), use_ssl=True):
# while True:
xmpp.process(block=True)
to_send = {'to': REGISTRATION_ID,
'message_id': 'reg_id',
'data': {'ma_message': 'message for android',
'ma_title': "Reg title"}}
xmpp.sendMessage("google", "<message><gcm xmlns='google:mobile:data'>"+json.dumps(to_send)+"</gcm></message>")
print("Done")
else:
print("Unable to connect.")
必需的xmpp节就是这个。
<message id="">
<gcm xmlns="google:mobile:data">
{
"to":"REGISTRATION_ID", // "to" replaces "registration_ids"
"message_id":"m-1366082849205" // new required field
"data":
{
"hello":"world",
}
"time_to_live":"600",
"delay_while_idle": true/false,
"delivery_receipt_requested": true/false
}
</gcm>
</message>
答案 0 :(得分:0)
您可以改为使用send_raw
,并在data
字段中发送完整的GCM消息节。当我这样做时,我不再看到400错误,而是我收到了一个&#34; BAD_REGISTRATION&#34;哪个是对的。