Created
March 21, 2014 06:47
-
-
Save vietkute02/9680901 to your computer and use it in GitHub Desktop.
python gcm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import sys, json, xmpp, random, string | |
SERVER = 'gcm.googleapis.com' | |
PORT = 5235 | |
USERNAME = "Your GCM Sender Id" | |
PASSWORD = "API Key" | |
REGISTRATION_ID = "Registration Id of the target device" | |
unacked_messages_quota = 1000 | |
send_queue = [] | |
# Return a random alphanumerical id | |
def random_id(): | |
rid = '' | |
for x in range(8): rid += random.choice(string.ascii_letters + string.digits) | |
return rid | |
def message_callback(session, message): | |
global unacked_messages_quota | |
gcm = message.getTags('gcm') | |
if gcm: | |
gcm_json = gcm[0].getData() | |
msg = json.loads(gcm_json) | |
if not msg.has_key('message_type'): | |
# Acknowledge the incoming message immediately. | |
send({'to': msg['from'], | |
'message_type': 'ack', | |
'message_id': msg['message_id']}) | |
# Queue a response back to the server. | |
if msg.has_key('from'): | |
# Send a dummy echo response back to the app that sent the upstream message. | |
send_queue.append({'to': msg['from'], | |
'message_id': random_id(), | |
'data': {'pong': 1}}) | |
elif msg['message_type'] == 'ack' or msg['message_type'] == 'nack': | |
unacked_messages_quota += 1 | |
def send(json_dict): | |
template = ("<message><gcm xmlns='google:mobile:data'>{1}</gcm></message>") | |
client.send(xmpp.protocol.Message( | |
node=template.format(client.Bind.bound[0], json.dumps(json_dict)))) | |
def flush_queued_messages(): | |
global unacked_messages_quota | |
while len(send_queue) and unacked_messages_quota > 0: | |
send(send_queue.pop(0)) | |
unacked_messages_quota -= 1 | |
client = xmpp.Client('gcm.googleapis.com', debug=['socket']) | |
client.connect(server=(SERVER,PORT), secure=1, use_srv=False) | |
auth = client.auth(USERNAME, PASSWORD) | |
if not auth: | |
print 'Authentication failed!' | |
sys.exit(1) | |
client.RegisterHandler('message', message_callback) | |
send_queue.append({'to': REGISTRATION_ID, | |
'message_id': 'reg_id', | |
'data': {'message_destination': 'RegId', | |
'message_id': random_id()}}) | |
while True: | |
client.Process(1) | |
flush_queued_messages() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Getting error after setting the projectId and API key
(ENV) D:\Workspace\python\xmpppy>python run.py
Invalid debugflag given: socket
DEBUG:
DEBUG: Debug created for D:\Workspace\python\xmpppy\ENV\lib\site-packages\xmpp\client.py
DEBUG: flags defined: socket
DEBUG: socket start Plugging <xmpp.transports.TCPsocket instance at 0x000000000263DF48> into <xmpp.client.Client instance at 0x000000000263DDC8>
DEBUG: socket error Failed to connect to remote host ('gcm.googleapis.com', 5235): A connection attempt failed because the connected party did not properly respond after a pe
riod of time, or established connection failed because connected host has failed to respond (10060)
Traceback (most recent call last):
File "D:\Workspace\python\xmpppy\ENV\lib\site-packages\xmpp\transports.py", line 133, in connect
self._sock.connect((server[0], int(server[1])))
File "d:\program files\python27\Lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected hos
t has failed to respond
DEBUG: socket stop Plugging <xmpp.transports.TCPsocket instance at 0x000000000263DF48> out of <xmpp.client.Client instance at 0x000000000263DDC8>.
Traceback (most recent call last):
File "run.py", line 52, in
auth = client.auth(USERNAME, PASSWORD)
File "D:\Workspace\python\xmpppy\ENV\lib\site-packages\xmpp\client.py", line 214, in auth
while not self.Dispatcher.Stream._document_attrs and self.Process(1): pass
AttributeError: Client instance has no attribute 'Dispatcher'