Reputation: 13
I'am trying to send notifications to devices that allows notifications in a Firebase site. I have the tokens of those devices in Firebase relational database. I can successfully retrieve them, but when i send the notifications everything seems messed up. I can send notifications using the command line method. But when i does it with a python script, its not working. Is my script right?
import firebase_admin
import google.cloud
from firebase_admin import credentials, firestore
import datetime
import pycurl, json, re
now=datetime.datetime.now()
time=now.strftime("%H:%M")
print(time)
cred = credentials.Certificate("./ServiceAccountKey.json")
app = firebase_admin.initialize_app(cred)
store = firestore.client()
doc_ref = store.collection(u'testy')
tokens=[]
try:
docs = doc_ref.stream()
for doc in docs:
print(u'Doc Data:{}'.format(doc.to_dict()))
if doc.to_dict() not in tokens:
tokens.append(doc.to_dict())
print('*********tokens:{}*********'.format(tokens))
except google.cloud.exceptions.NotFound:
print(u'Missing data')
tokensnew='{}'.format(tokens)
print(tokensnew)
x=re.sub("token", "", tokensnew)
x=re.sub("]", "", x)
x=re.sub('\[', "", x)
x=re.sub("'", "", x)
x=re.sub("{", "", x)
x=re.sub("}", "", x)
x=re.sub(",", "", x)
x=re.split(" ",x)
x = list(filter(None, x))
print(x)
x=[i for i in x if i!=':']
for i in x:
c = pycurl.Curl()
c.setopt(pycurl.URL, 'https://fcm.googleapis.com/fcm/send')
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json','Authorization: key='''key goes here''''])
print('======================{}'.format(i))
data = json.dumps({"notification":{"title":"GTFO","body":"frame{clas},{id}.jpg" .format(clas=class_names[0],id=int(track.track_id)),"icon":"/itwonders-web-logo.png",}, "to":"{}".format(i)})
c.setopt(pycurl.POSTFIELDS, data)
c.setopt(pycurl.VERBOSE, 1)
c.perform()
print(c.getinfo(pycurl.RESPONSE_CODE))
certinfo = c.getinfo(pycurl.INFO_CERTINFO)
print(certinfo)
c.close()
Upvotes: 1
Views: 171
Reputation: 1476
I see that you tried to convert the command line curl into a verbose python script. You did a great job. But you should've mentioned the connection method. As in this script you can add c.setopt(pycurl.POST, 1)
to the for loop that contains your pycurl statements (put it below c.setopt(pycurl.VERBOSE, 1)
).
BTW, you show look into regex more,:).
Upvotes: 1