Skip to content

Instantly share code, notes, and snippets.

@vietkute02
Created March 21, 2014 06:47
Show Gist options
  • Save vietkute02/9680901 to your computer and use it in GitHub Desktop.
Save vietkute02/9680901 to your computer and use it in GitHub Desktop.
python gcm
#!/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()
@sujitmhj
Copy link

I cannot import xmpp. Can you help me ?

@nKandel
Copy link

nKandel commented Mar 15, 2016

pip install xmpppy

@sujitmhj
Copy link

Thanks

@cecyurbina
Copy link

How send a message to user segments, for example com.androidapplication.name?

@winster
Copy link

winster commented Sep 21, 2016

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'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment