How to send silent notification from server to ios devices? - python

This is my python script which sends the fcm notifications to the devices.
It sends priority notifications not silent notifications....
How can I silence them ?
def sendGCMToTopiciOS():
url = 'https://fcm.googleapis.com/fcm/send'
headers = {
'UserAgent': "GCM-Server",
'Content-Type': 'application/json',
'Authorization': 'key=' + 'XXXXXXXXXXXXXXXXXXXX',
}
data = {'title': 'Yugam', 'message': 'Hello Everyone', 'event': '13', 'workshop': '-1',
'link': 'https://www.google.com'}
notification = {
'body': data.get('message'),
'title': data.get('title')
}
values = {
'to': '/topics/' + 'global',
'data': data,
'notification': notification,
"aps":{
"content-available":1}
}
pipe = requests.post(url=url, json=values, headers=headers)
return pipe.json()

To send a data-message you need to skip the notification part of the json payload

The 'notification' field will cause iOS 10 to send your notifications to the system, automatically displaying notifications based on the given values. If you're looking for a completely silent notification try:
values = {
'to': '/topics/' + 'global',
'content_available': true
'priority': 'high',
'data': data
}
This will be delivered in the background without an alert. The 'content_available' field will also convert to 'content-available':1 after passing through the GCM server for APNS.

Related

FCM push notifications not working in AWS Lambda using Python

I didn't find any questions that solved my issue, hence below:
This is the code I am using to send an FCM push notification via AWS Lambda written in Python. The AWS code is deployed on Lambda using the Zappa package:
# SENDING FCM NOTIFICATION
notification_headers = {
'Content-Type': 'application/json',
'Authorization': 'key=' + serverToken,
}
body_en = {
'notification': {
'title': post['src'],
'body': post['title'],
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'sound': 'default'
},
'to': deviceToken,
'priority': 'high',
'content_available': 'true',
}
response_en = requests.post(
"https://fcm.googleapis.com/fcm/send",
headers = notification_headers,
data = json.dumps(body_en)
)
return response_en
Are there any imports I must do before being able to use FCM in AWS Lambda?

Xero API not working for Accounts in python

I am trying to call xero Accounts api in python but not working for some reason. It works well for the rest of APIs such as Invoices, reports, and so on, but Accounts.
The following script is my python script i am using to call the api.
get_url = 'https://api.xero.com/api.xro/2.0/Accounts'
response = requests.get(get_url,
headers = {
'Authorization': 'Bearer ' + access_token,
'Xero-tenant-id': xero_tenant_id,
'Accept': 'application/json'
})
json_response = response.json()
print(json_response)
But this is throwing the following error:
{'Type': None, 'Title': 'Unauthorized', 'Status': 401, 'Detail': 'AuthorizationUnsuccessful', 'Instance': '3c1649ef-6eed-4e64-8503-04fc99481db2', 'Extensions': {}}
Can anyone tell me why this is happening? why just Accounts?
Can you share what scopes you're requesting? https://developer.xero.com/documentation/oauth2/scopes
Invoices requires accounting.transactions
Reports requires accounting.reports.read
Accounts requires accounting.settings

How to create an account, and upload an image with that account with imgur

I am designing a python GUI, one of its functions is taking a screenshot, uploading it to Imgur and then getting the URL. Though I am having issues understanding the documentation (especially since it says you need to create an account through the API, but not how to do it.). Would anyone be able to explain how exactly to create an account and then upload an image using it?
Note: I am using PIL to get the screenshots, I would prefer you explain it as code written with the requests library or maybe curl (as that isn't too hard to move to python with requests), and I'll be saving only the refresh token in the program, as it would be hardcoded (But the user can change it) and I don't want the user to authenticate.
Thanks in advance.
Edit 1: Also, I will not use imgurpython as it is outdated.
First you have to create normal account on Imgur.
After loging to normal account you can go to https://api.imgur.com/oauth2/addclient to register application.
It needs application name and email. Type of authorization depends on how you will use it.
You should get API keys
Which you can use with API
To get information:
import requests
headers = {
'Authorization': 'Client-ID f1XXXXXXXXXXXXX',
}
#https://i.imgur.com/cvWgXFc.jpg
imageHash = 'cvWgXFc'
r = requests.get(f'https://api.imgur.com/3/image/{imageHash}', headers=headers)
print('status:', r.status_code)
data = r.json()
print(data)
print('size:', data['data']['size'])
Result:
status: 200
{'data': {'id': 'cvWgXFc', 'title': None, 'description': None, 'datetime': 1579572289, 'type': 'image/jpeg', 'animated': False, 'width': 506, 'height': 500, 'size': 89341, 'views': 8087, 'bandwidth': 722500667, 'vote': None, 'favorite': False, 'nsfw': False, 'section': None, 'account_url': None, 'account_id': None, 'is_ad': False, 'in_most_viral': False, 'has_sound': False, 'tags': [], 'ad_type': 0, 'ad_url': '', 'edited': '0', 'in_gallery': False, 'link': 'https://i.imgur.com/cvWgXFc.jpg', 'ad_config': {'safeFlags': ['onsfw_mod_safe', 'share', 'page_load'], 'highRiskFlags': [], 'unsafeFlags': ['not_in_gallery', 'sixth_mod_unsafe'], 'wallUnsafeFlags': [], 'showsAds': False}}, 'success': True, 'status': 200}
size: 89341
To upload:
import requests
import base64
headers = {
'Authorization': 'Client-ID f1XXXXXXXXXXXXX',
}
params = {
'image': base64.b64encode(open('images.png', 'rb').read())
}
r = requests.post(f'https://api.imgur.com/3/image', headers=headers, data=params)
print('status:', r.status_code)
data = r.json()
print(data)
BTW: you can see your registered applications and regenerate API keys (if you forget it) after login on https://imgur.com/account/settings/apps
You will need to use the Imgur API, which you can get from
here:
Once you get the API key from their site, you can start writing some code.

Metadeta error on stripe transaction using python

I am doing stripe payment integration using python and use the following data:
import requests
import json
pos = requests.post
url = "https://api.stripe.com/v1/sources"
headers = {'AUTHORIZATION': 'Bearer sk_test_NXht3wZpuYWRIWpMDDqT3RG2'}
data = {
'type': 'alipay',
'owner[email]': 'abc#xyz.com',
'redirect[return_url]': 'https://www.google.com',
'amount': '500',
'currency': 'USD',
'metadata': {
'data': 'data'
}
}
pos(url, data=data, headers=headers).text
json.loads(pos(url, data=data, headers=headers).text)
When give the metadata it gives error '{\n "error": {\n "message": "Invalid hash",\n "param": "metadata",\n "type": "invalid_request_error"\n }\n}\n'
but according to stripe documentation metadata can be used( https://stripe.com/docs/api/curl#create_source-metadata)
Can anyone tell the solution why it gives that error.
This will solve the problem.
import requests
import json
pos = requests.post
url = "https://api.stripe.com/v1/sources"
headers = {'AUTHORIZATION': 'Bearer sk_test_NXht3wZpuYWRIWpMDDqT3RG2'}
data = {
'type': 'alipay',
'owner[email]': 'abc#xyz.com',
'redirect[return_url]': 'https://www.google.com',
'amount': '500',
'currency': 'USD',
'metadata[data]': 'data'
}
pos(url, data=data, headers=headers).text
json.loads(pos(url, data=data, headers=headers).text)
Stripe does not support JSON payloads for the parameters. Instead, they require application/x-www-form-urlencoded.
At the moment, you are sending metadata as a hash and you are not encoding it properly so Stripe is rejecting it.
The best solution here is to avoid doing this yourself and instead rely on Stripe's official Python library that you can find here: https://github.com/stripe/stripe-python

Facebook Messenger Bot Python Send Image

I'm trying to send an image with a facebook bot. I can send text fine, but whenever I try to send a message I get an error: TypeError: open file 'plot.jpg', mode 'rb' at 0x7f34a2fe8b70 is not JSON serializable. I'm using flask and heroku for the bot if that makes a difference.
This is my code:
def send_message(recipient_id, message_text):
log("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text))
params = {
"access_token": os.environ["PAGE_ACCESS_TOKEN"]
}
headers = {
"Content-Type": "application/json"
}
log(os.getcwd())
data = json.dumps({
'recipient': {
'id': recipient_id
},
'message': {
'attachment': {
'type': 'image',
'payload': {}
}
},
'filedata': (os.path.basename('plot.jpg'), open('plot.jpg', 'rb'))
})
r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=headers, data=data)
if r.status_code != 200:
log(r.status_code)
log(r.text)
I got the same issue and i solved it by using multipart/form-data, instead of encoding the entire payload using json.dumps() you can use the MultipartEncoder from requests-toolbelt-0.8.0 to multipart encode the payload.
Note - Facebook's Graph API is accepting only png images for some unknown reasons, in the below example i've used a png file.
*Edited the code(redundant end parenthesis)
import json
import requests
from requests_toolbelt import MultipartEncoder
def send_message(recipient_id, message_text):
log("sending message to {recipient}: {text}".format(recipient=recipient_id, text=message_text))
params = {
"access_token": os.environ["PAGE_ACCESS_TOKEN"]
}
log(os.getcwd())
data = {
# encode nested json to avoid errors during multipart encoding process
'recipient': json.dumps({
'id': recipient_id
}),
# encode nested json to avoid errors during multipart encoding process
'message': json.dumps({
'attachment': {
'type': 'image',
'payload': {}
}
}),
'filedata': (os.path.basename('plot.png'), open('plot.png', 'rb'), 'image/png')
}
# multipart encode the entire payload
multipart_data = MultipartEncoder(data)
# multipart header from multipart_data
multipart_header = {
'Content-Type': multipart_data.content_type
}
r = requests.post("https://graph.facebook.com/v2.6/me/messages", params=params, headers=multipart_header, data=multipart_data)
if r.status_code != 200:
log(r.status_code)
log(r.text)

Categories

Resources