Parse to Firebase enhanced push notifications - python

I'm migrating Parse to Firebase and I'm having trouble with the enhanced push notification.
Parse data (iOS side) was like:
{"ast":
{"alert": {
{"body": "body_test",
"title": "title_test",
"description": "description",
"endpoint-proposal": "https://.."
"launch-image": "https://..."
},
"sound": "chime",
...
}
Working with Firebase API the ast tag is the ['notification']['body'].
If I send
['notification']['body'] = 'Hello'
It works perfectly and generate the following push:
{"ast":
{"alert": "Hello"}
}...
So, here the problem, I need to send a dictionary in that tag (alert) and I cannot do that because firebase set the value as string.
Example in python:
alert = dict()
alert['title'] = 'title'
alert['description'] = 'description'
alert['endpoint-proposal'] = 'https://..'
alert['launch-image'] = 'https://..'
fcm_payload['notification']['body'] = alert
send_push()
And in the iOS side I get:
[AnyHashable("gcm.message_id"): 0:123456789,
AnyHashable("aps"): {
alert = "{\"body\": \"body\",
\"launch-image\": \"https://...\",
\"endpoint-proposal\": \"https://...\",
\"description\": \"description\",
\"title\": \"title\"}";
}]
Always as string :S
Is there any way to send that alert as dict?

The notification body parameter will always be treated by FCM as a String. It's just the behavior. What you'll have to do is make use of the data payload and put in your custom key-value pairs:
On iOS, if the message is sent via APNS, it represents the custom data fields. If it is sent via FCM connection server, it would be represented as key value dictionary in AppDelegate application:didReceiveRemoteNotification:.
More details can be seen in this Receiving Messages in iOS doc. I think for your case, you just have to use the notification and data parameters together in your payload.

json.loads() should get you a dict.

Related

How to enable the Google Firebase notification analytics in Django Python using PyFCM?

We are using the PyFCM module to send the notification via google firebase and somehow the notification analysis report's data is missing in the report section of the GCP firebase console.
Can someone know how to enable the notification analysis on firebase? As we want to know the details of the notification being sent, received, and opened.
We need to add the analytics_label with every notification being sent to firebase and for PyFcm using Django you can pass the analytics_label in the fcm_options given below:-
from pyfcm import FCMNotification
push_service = FCMNotification(api_key=FCM_SERVER_KEY)
registration_ids = ['user_mobile_token_key']
data = {
"body": "test body,
"title": "title,
"priority": "high"
}
extra_kwargs = {'**fcm_options**': {
'analytics_label': 'notification-label'}}
result = push_service.multiple_devices_data_message(registration_ids=registration_ids,
data_message=data, extra_kwargs=extra_kwargs)
print(result)

How to send multiple messages to user as answer from AWS lambda?

I've followed tutorials to setup Lex&Lambda. My lambda function returns
return {
"dialogAction": {
"type": "ConfirmIntent",
"intentName": "GetPersonInfo",
"message": {
"contentType": "PlainText",
"content": ""
}
}
}
and Lex displays it as single message. When I'm building my bot on aws site I can setup multiple messages as answer(without using lambda) and I would like to do that with lambda function just like on img: https://docs.aws.amazon.com/lex/latest/dg/images/default-response-25a.png.
On aws site I've prepared output for multiple messages and it look like this:
{
"dialogState": "Fulfilled",
"intentName": "GetPersonInfo",
"message": "{\"messages\":[{\"type\":\"PlainText\",\"group\":1,\"value\":\"siema siemanko\"},{\"type\":\"CustomPayload\",\"group\":2,\"value\":\"{\\\"moj\\\":\\\"json\\\"}\"}]}",
"messageFormat": "Composite",
...
}
I've noticed that Lex expect "dialogAction" as lambda output and multiple message feature is used in "PostText" and "PostContent". I know, that dialogAction is used to build PostText/PostContent object.
I also would like to send different message to speech, different to display as text and another as a JSON (for my Frontend). Right now my solution is to send everything as PlainText message in dialogAction object and then via my front end execute Polly to read message prepared for speach. Is this possible to do such stuff just with Lex and lambda?
The only way I know to display multiple messages is to do that via Lex configuration on AWS Lex side. As an example:
1. You create an intent with an utterance I want to get information about user {UserEmailAddress}.
2. You create a required slot UserEmailAddress and non-required UserFirstName and UserLastName.
3. Once the first slot is filled by an utterance you send a request to your backend API within Lambda exports function to get information about that user via his email address and fill other slots (the code is applicable to Node 8.10 you may create your own Python version):
`
exports.handler = async (event, context) => {
...
return context.succeed({
event.sessionAttributes,
dialogAction: {
type: "Delegate",
{
...event.currentIntent.slots,
UserFirstName: httpResponse.firstName,
UserLastName: httpResponse.lastName
}
}
})
}
`
4. In "Response" section of your intent you add multiple messages:
Here is the information for the user {UserEmailAddress}
His first name is {UserFirstName} and his last name is {UserLastName}.
5. Add a response card with the question that contains an utterance as one/many of responses. For example, the question "What do you want to do next?" and a button:
Button title: "Get his address",
Button value: ""
Ideally the dialog should look like this:
User: I want to get information about user simon#tech.com
Bot: Here is the information about user simon#tech.com
Bot: His first name is Simon his last name is Anderson
Bot: What do you want to do next?
[Get his address]
And when you click the button it will look the same as the ordinary response for a slot.
You can use multiple messages as an array in your response.
return {...
'message' : [{'contentType': 'PlainText',
'content': 'Something response'}],...
}

How to store complex meta data using Asana's external data feature

Background
My organization uses the Asana platform to coordinate our work efforts. I have been leveraging Asana's API to automate a number of our daily operations and as well integrate Asana's platform with other external services we use. I interact with Asana's API using python and the requests library to make GET, POST, and PUT requests.
Often times I need to GET or POST to a specific task within Asana, I can often achieve this using Asana's auto-generated task ID.
result = requests.get("https://app.asana.com/api/1.0/tasks/task_id", headers)
However there are times where it is useful for me to be able to identify a task by specific information stored within it. I have been able to successfully do so by storing the specific information in question within task's meta data, referred to as "external data" by Asana.
result = requests.get("https://app.asana.com/api/1.0/tasks/external_id", headers)
Both of these methods have served me well. However I am having trouble storing specific data within a task's external data which I outline in the section below.
Problem
Currently when I store meta data in a task external data my PUT/POST request is as follows:
header = {
"Authorization" : "Bearer " + AUTH_TOKEN
}
data = {
"data" : {
"name" : "Burgers",
"external" : {
"id" : "external_id",
"data" : "data_value"
}
}
}
url = "https://app.asana.com/api/1.0/tasks/task_id"
result = requests.put(url, headers=header, json=data)
return result
The important thing to note here is that the "data_value" is a single string. However according to Asana's documentation here the "data_value" can actually store a dictionary of keys and values. I have attempted to pass a dictionary object by doing the following:
data = {
"data" : {
"name" : "Burgers",
"external" : {
"id" : "external_id",
"data" : {
"data_value" : "some_data",
"data_value_2" : "some_data"
}
}
}
}
But I continue to receive an error stating:
"{"errors":[{"message":"external: data: Value is not a string: [object Object]","help":"For more information on API status codes and how to handle them, read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}]}"
Any ideas where I am going wrong? Has anyone had success with this?

Django Simple Push Notification to IOS

I want to create simple function for sending push notification to IOS devices. Inside my model i am storing Device_type and Device_token
for Android i had written simple code using requests like below
import requests, json
def send_push_notif_android(device_token,title,msg):
payload = {
"to" : device_token,
"notification" : {
"title": title,
"text": msg
}
}
url = "https://fcm.googleapis.com/fcm/send"
header = {
"Content-Type":"application/json",
"Authorization":"key = <app key>"
}
requests.post(url, data=json.dumps(payload), headers=header)
I dont know how to do it for IOS
i had generated Certificates.pem file and kept it in my root folder.
Can someone tell me how to write simplest example like this.
Maybe you are looking for django-push-notifications
Since this questions still turns up in search, here is 2020 update version of Python3 HTTP2-compatible script to send push notifications.

Can I send richly-formatted Slack messages as a Bot and not as a Webhook?

I started writing a Slack bot in Python and came to a halt when I couldn't find a way to send richly-formatted messages using the either of the two methods:
sc.rtm_send_message("channel_name", my_message)
sc.api_call("chat.postMessage", channel="channel_name", text=my_message, username="username", icon_url="icon_url")
where my_message = json.dumps({'attachments': [{...}]})
I now know that I can do this using the webhook approach but is it possible with the above method?
Both API (method chat.postMessage) and incoming webhook offer the same options for formatting your messages including markup and attachments.
Hint: if you want to use markup in your attachments, make sure to add the field "mrkdwn_in" and name the field your want to use it in or it will be ignored by Slack.
Example:
{
"attachments": [
{
"title": "Title",
"pretext": "Pretext _supports_ mrkdwn",
"text": "Testing *right now!*",
"mrkdwn_in": ["text", "pretext"]
}
]
}
See here for full documentation.
I found out where I was going wrong.
I was passing my message to the wrong argument in the sc.api_call method.
I should've been passing it to sc.api_call(attachments=...) argument, not the text argument.

Categories