article

Anand@Amazon avatar image
Anand@Amazon posted

How to add Proactive Events to your existing skill

Sending notifications from applications in your mobile devices is a common feature nowadays but what if you can send notifications from your skills to Alexa devices. With the release of proactive events now you can send timely and relevant information to your users.

We have provided pre-defined set of schemas that best describe your events and send proactive events information that conforms to a schema via the Skill Management API (SMAPI) as part of a skill manifest. Each schema has a predefined template that represents the text read back to the end customers by Alexa.

To make sure Alexa notifications provide relevant updates, customers have the ability to enable notifications for each skill, and they can opt out at any time using the Alexa app.

When an Alexa notification is sent, customers see a yellow light on devices without screens and an on-screen banner on devices with screens that indicate that they have new notifications. Customers can ask Alexa to read their notifications when they want to hear them.

How to add:

To add proactive events in your Alexa skill you need to follow below details:

  • Select schemas to represent the events you wanted to send to users.
  • Update skill manifest with Proactive Events capabilities.
  • In the Notification settings page in the Alexa app, enable notification for your skill.
  • Send a proactive event and ensure you receive the notification on your Alexa-enabled device.

To call proactive event API you need to authenticate with Alexa as follows:

HTTP header:

POST /auth/O2/token HTTP/1.1
Host: api.amazon.com
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

Request body syntax:

grant_type=client_credentials&client_id=(clientID)&client_secret=(clientSecret)&scope=alexa::proactive_events


function getTokenOptions(postLength){
    // const TokenPostData = getTokenPostData();
    return {
        hostname: 'api.amazon.com',
        port: 443,
        path: '/auth/O2/token',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': postLength // TokenPostData.length
        }
    }
}
function getTokenPostData() {
    return 'grant_type=client_credentials&client_id=' + clientID + '&client_secret=' + clientSecret 
                + '&scope=alexa::proactive_events';
}
function getToken() {
    return new Promise(resolve => {
        const TokenPostData = getTokenPostData();
        const req = https.request(getTokenOptions(TokenPostData.length), (res) => {
            res.setEncoding('utf8');
            let returnData = '';
            res.on('data', (chunk) => { returnData += chunk; });
            res.on('end', () => {
                const tokenRequestId = res.headers['x-amzn-requestid'];
                // console.log(`Token requestId: ${tokenRequestId}`);
                resolve(JSON.parse(returnData).access_token);
            });
        });
        req.write(TokenPostData);
        req.end();
    });
}


To locate ClientId and ClientSecret in the developer console, select the Build tab, scroll down to the Permissions section, and get these values from Alexa Skill Messaging at the bottom right.

Developer needs to select schemas to represent the events they want to notify their customers about, and send these events to the ProactiveEvents API. Customers subscribed to receive notifications about these events from the skill will then receive an Alexa notification. Schemas are pre-defined by the Alexa Skills Kit.

Your skill can use different schemas to represent different themes about which you want to engage their customers. Your skill cannot implement multiple instances of the same schema.

Below schema is used to send weather alert to all customers who enabled this skill and subscribed for notification:

function getWeatherEvent() {
    let timestamp = new Date();
    let expiryTime = new Date();
    expiryTime.setMinutes(expiryTime.getHours() + 24);
    let referenceId = "SampleReferenceId" + new Date().getTime();  // cross reference to records in your existing systems
    const eventJson = {
        "timestamp": timestamp.toISOString(),
        "referenceId": referenceId,
        "expiryTime": expiryTime.toISOString(),
        "event":{
            "name":"AMAZON.WeatherAlert.Activated",
            "payload":{
              "alert":{
                "source": "localizedattribute:source",
                "alertType": "HURRICANE"           
              }
            }
        },
        "localizedattribute":[
            {
                "locale": "en-US",
                "source": "Weather Channel"
            },
            {
                "locale": "en-GB",
                "source": "Britain Met Office"
            },
            {
                "locale": "fr-FR",
                "source": "Canal météo"
            }
        ],
        "relevantAudience":{
            "type":"Multicast",
            "payload":{}
        }
    };
    return eventJson;
}

In your skill manifest you must define the event your skill will provide to your customer. Publications Object has been added to the events section of the skill manifest. When specifying you must include “alexa::devices:all:notifications:write” as a permission.

"permissions": [
    {
      "name": "alexa::devices:all:notifications:write"
    }
  ],
  "events": {
    "publications": [
      {
        "eventName": "AMAZON.WeatherAlert.Activated"
      },
      {
        "eventName": "AMAZON.MessageAlert.Activated"
      }
    ],
    "endpoint": {
      "uri": "Your-ARN-Here"
    },
    "subscriptions": [
      {
        "eventName": "SKILL_PROACTIVE_SUBSCRIPTION_CHANGED"
      }
    ],
    "regions": {
      "NA": {
        "endpoint": {
          "uri": "Your-ARN-Here"
        }
      }
    }
  } 

While your skill is in the development stage, you can test it by sending proactive events using the following development endpoint. This endpoint is always available to you, and you can use it without concerns of sending requests to your live customers. Use the Notifications settings in the Alexa app to subscribe to receive test notifications.


To send events to your live customers, send proactive events to the live endpoint. This endpoint is only available to you once your skill is certified, and it only accepts events that your skill has been certified to send to Alexa. Select the appropriate endpoint for your region.

function getProactiveOptions(token, postLength){
    return {
        hostname: 'api.amazonalexa.com',  // api.eu.amazonalexa.com (Europe) api.fe.amazonalexa.com (Far East)
        port: 443,
        path: '/v1/proactiveEvents/' + (mode && mode === 'prod' ? '' : 'stages/development'),  // mode: global var
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': postLength,
            'Authorization' : 'Bearer ' + token
        }
    };
}
function sendEvent(token) {
    return new Promise(resolve => {
        const ProactivePostData = JSON.stringify(getWeatherEvent());
        const ProactiveOptions = getProactiveOptions(token, ProactivePostData.length);
        const req = https.request(ProactiveOptions, (res) => {
            res.setEncoding('utf8');
            if ([200, 202].includes(res.statusCode)) {
                 console.log('successfully sent event');
            } else {
                console.log(`Error https response: ${res.statusCode}`);
                console.log(`requestId: ${res.headers['x-amzn-requestid']}`);
                if ([403].includes(res.statusCode)) {
                    resolve(`error ${res.statusCode}`);
                }
            }
            let returnData;
            res.on('data', (chunk) => { returnData += chunk; });
            res.on('end', () => {
                const requestId = res.headers['x-amzn-requestid'];
                resolve("sent event");
            });
        });
        req.write(ProactivePostData);
        req.end();
    });
}

ProactiveEvents API is available in all locales supported by Alexa. Review our technical documentation to learn more. We have also provided sample code for proactive events on our official GitHub repository. If you need any help or have any feedback please reach out to us via contact-us . We are also present on Alexa Developer community forum.

alexa skills kitask clinotificationssmapiproactive events
10 comments
10 |5000 characters needed characters left characters exceeded

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Hello Anand. Thanks for your text, it's helpful.

Well, I have a doubt. I'm developing skills for Brazil, in portuguese, and I want to do a notification. My skill is about schedule a specific type of appointments, so, sometime before the booking time, I would to notify the user with the Alexa Device.


I did a prototype using Proactive Events API, but the Schemas are a little bit limitaded when talking about the messages read by Alexa.

First, I don't understand why I can't create my own messages to notify my user. Second, the portuguese version of Ocassion Update Schema it's wrong. (the APPOINTMENT type has a weird translating, by example).


So, I wanna know if there are some other way to create notifications to Alexa Devices. Just to remember, I need to notify the user one day(or two) before the appointment date.


Thanks in advance.

1 Like 1 ·

Olá, Giovane!

Meu nome é Thiago e também tenho feito skills em português para usar aqui no Brasil.

Estou tentando implementar proactive events na minha skill, mas, apesar de o request retornar o código 202, meu dispositivo não recebe a notificação.

Você poderia, por favor, me ajudar?

Abraços,

0 Likes 0 ·

Hi, my custom skill is live.

However, when I go to the Permissions Tab in the dev version of the app, there is no option to enable a Proactive Event API permission.

I have only these options:


0 Likes 0 ·
newuser-82227a11-67bb-4b68-968a-75c4b680544b avatar image newuser-82227a11-67bb-4b68-968a-75c4b680544b newuser-82227a11-67bb-4b68-968a-75c4b680544b ·

bump bump bump

0 Likes 0 ·
newuser-82227a11-67bb-4b68-968a-75c4b680544b avatar image newuser-82227a11-67bb-4b68-968a-75c4b680544b newuser-82227a11-67bb-4b68-968a-75c4b680544b ·

@Anand@Amazon please help!


Thanks!

Adam

0 Likes 0 ·
mmallick avatar image mmallick newuser-82227a11-67bb-4b68-968a-75c4b680544b ·

were you able to get your answer on this?

0 Likes 0 ·

Hi, I followed the example using PostMan to send and receive requests. First to get the bearer and then to send the Weather JSON.
I did have to change the JSON event payload from "alert" to "weatherAlert"

However, I still just get a 202 response and nothing orange or notification alerts at the client side. What can I do next to get notifications tested and then working in code.

0 Likes 0 ·

Hi, I follow your example and a get a 202 when a send the notification, but i never receive that.

These is my response header.

return headers: {
"content-length": "0",
"connection": "close",
"server": "Server",
"date": "Mon, 09 Mar 2020 12:41:12 GMT",
"x-amzn-requestid": "20b85fa8-1fc6-1e9f-917f-bebd6e33029f",
"x-amz-rid": "RAE8KNJCAD9CYCB5C0HP",
"vary": "Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent",
"x-cache": "Miss from cloudfront",
"via": "1.1 6807491555b9c49f0b843f3fd1c3ba66.cloudfront.net (CloudFront)",
"x-amz-cf-pop": "SCL50-C1",
"x-amz-cf-id": "YXUE1cKd9W_R7i9CuSC5G18A2adn2Zp6hvV65Q6cGIaBRvQlK_kxUA=="
}

RequestId: 20b85fa8-1fc6-1e9f-917f-bebd6e33029f

Can you help me?

0 Likes 0 ·

What can I do to not encounter this issue?


This happens when I update the skill with the permission.

-1 Like -1 ·
Anand@Amazon avatar image Anand@Amazon ♦ newuser-c536bef2-c2d6-4d72-b834-b88376809d1a ·

There was some issue on our end which is fixed now. Please try it again and let us know if this issue still occurs for you.

0 Likes 0 ·

Article

Contributors

kumaanan contributed to this article