A√ļn no tienes acceso a esta clase

Crea una cuenta y contin√ļa viendo este curso

Media Template / Webviews

19/25
Recursos

Los Media Templates nos permiten mostrar contenido extra en el flujo de nuestro bot. Cuando nuestros usuarios manden mensajes de texto podemos responder con imágenes graciosas o la opción de contactarnos por teléfono.

Los Webviews nos permiten mostrar una p√°gina web dentro de Messenger sin necesidad de abrir un navegador, podemos mostrar elementos mucho m√°s complejos (mapas, por ejemplo).

Aportes 8

Preguntas 2

Ordenar por:

¬ŅQuieres ver m√°s aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesi√≥n.

Podemos presentar nuestro webview, abrirlo en tres formas ( compact, tall, full )

"webview_height_ratio": "compact"

"webview_height_ratio": "tall"

"webview_height_ratio": "full"

Documentacion

Gifs
Giphy
Imagenes
Pexels

Hasta el momento tengo todo perfecto, comparto mi código

app.js:

'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const access_token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

const app = express();

app.set('port', 5000);
app.use(bodyParser.json());

app.get('/', function(req, response){
    response.send('Hola Mundo!');
})

app.get('/webhook', function(req, response){
    if(req.query['hub.verify_token'] === 'pizzaplaneta_token'){
        response.send(req.query['hub.challenge']);
    } else {
        response.send('Pug Pizza no tienes permisos.');
    }
});

app.post('/webhook/', function(req, res){
    const webhook_event = req.body.entry[0];
    if(webhook_event.messaging) {
        webhook_event.messaging.forEach(event => {
            handleEvent(event.sender.id, event);
        });
    }
    res.sendStatus(200);
});

function handleEvent(senderId, event){
    if(event.message){
        handleMessage(senderId, event.message)
    } else if(event.postback) {
        handlePostback(senderId, event.postback.payload)
    }
}

// esto es lo que envia imagenes o texto al usuario cuando el responde con un mensaje
function handleMessage(senderId, event){
    if(event.text){
        //cambiado el defaultMessage por messageImage, para enviar un gift cuando el usuario escribe.
        // messageImage(senderId);
        defaultMessage(senderId)
    } else if (event.attachments) {
        handleAttachments(senderId, event)
    }
}

function defaultMessage(senderId) {
    const messageData = {
        "recipient": {
            "id": senderId
        },
        "message": {
            "text": "Hola soy un bot de messenger y te invito a utilizar nuestro menu",
            "quick_replies": [
                {
                    "content_type": "text",
                    "title": "√ā¬ŅQuieres una Pizza?",
                    "payload": "PIZZAS_PAYLOAD"
                },
                {
                    "content_type": "text",
                    "title": "Acerca de",
                    "payload": "ABOUT_PAYLOAD"
                }
            ]
        }
    }
    senderActions(senderId)
    callSendApi(messageData)
    // setTimeout(function(){ callSendApi(messageData); }, 3000);
}

function handlePostback(senderId, payload){
    console.log(payload)
    switch (payload) {
        case "GET_STARTED_PUGPIZZA":
            console.log(payload)
        break;
        case "PIZZAS_PAYLOAD":
            showPizzas(senderId);
        break;
        case "CONTACT_PAYLOAD":
            contactSupport(senderId);
        break;
        case "LOCATIONS_PAYLOAD":
            showLocation(senderId);
        break;
    }
}

function senderActions(senderId) {
    const messageData = {
        "recipient": {
            "id": senderId
        },
        "sender_action": "typing_on"
    }
    callSendApi(messageData);
}

function handleAttachments(senderId, event){
    let attachment_type = event.attachments[0].type;
    switch (attachment_type) {
        case "image":
            console.log(attachment_type);
        break;
        case "video": 
            console.log(attachment_type);
        break;
        case "audio":
            console.log(attachment_type);
        break;
      case "file":
            console.log(attachment_type);
        break;
      default:
            console.log(attachment_type);
        break;
    }
}

function callSendApi(response) {
    request({
        "uri": "https://graph.facebook.com/me/messages",
        "qs": {
            "access_token": access_token
        },
        "method": "POST",
        "json": response
    },
        function (err) {
            if (err) {
                console.log('Ha ocurrido un error')
            } else {
                console.log('Mensaje enviado')
            }
        }
    )
}


function showPizzas(senderId) {
    const messageData = {
        "recipient": {
            "id": senderId
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "generic",
                    "elements":[
                        {
                          "title":"Pepperoni",
                          "subtitle":"Con todo el sabor del pepperoni.\n"+"Personal: 20 cm\n" + "Mediana: 30 cm\n"+ "Familiar: 35 cm",
                          "image_url": "https://images.pexels.com/photos/774487/pexels-photo-774487.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                          "buttons":[
                            {
                                "type":"postback",
                                "title":"Elegir Personal",
                                "payload":"PEPPERONI_PERSONAL_PAYLOAD",
                              },
                            {
                              "type":"postback",
                              "title":"Elegir Mediana",
                              "payload":"PEPPERONI_MEDIANA_PAYLOAD",
                            },
                            {
                              "type":"postback",
                              "title":"Elegir Familiar",
                              "payload":"PEPPERONI_FAMILIAR_PAYLOAD",
                            }
                          ]
                        },
                        {
                          "title":"Pollo BBQ",
                          "subtitle":"Con todo el sabor de el pollo BBQ.\n"+"Personal: 20 cm\n" + "Mediana: 30 cm\n"+ "Familiar: 35 cm",
                          "image_url": "https://images.pexels.com/photos/1653877/pexels-photo-1653877.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
                          "buttons":[
                            {
                              "type":"postback",
                              "title":"Elegir Personal",
                              "payload":"BBQ_PERSONAL_PAYLOAD",
                            },
                            {
                              "type":"postback",
                              "title":"Elegir Mediana",
                              "payload":"BBQ_MEDIANA_PAYLOAD",
                            },
                            {
                              "type":"postback",
                              "title":"Elegir Familiar",
                              "payload":"BBQ_FAMILIAR_PAYLOAD",
                            }
                          ]
                        }
                      ]
                }
            }
        }
    }
    callSendApi(messageData)
}

//clase 19
function messageImage(senderId) {
    const messageData = {
        "recipient": {
            "id": senderId
        },
        "message":{
            "attachment":{
              "type":"image", 
              "payload":{
                "is_reusable": true,
                "url":"https://media.giphy.com/media/9fuvOqZ8tbZOU/giphy.gif"
              }
            }
          }
    }
    callSendApi(messageData)
}

//clase 19
function contactSupport(senderId) {
    const messageData = {
        "recipient": {
            "id": senderId
        },
        "message":{
            "attachment":{
              "type":"template",
              "payload":{
                "template_type":"button",
                "text":"Contactanos por una llamada",
                "buttons":[
                  {
                    "type":"phone_number",
                    "title":"Llamar",
                    "payload":"+573205644748"
                  }
                ]
              }
            }
          }
    }
    callSendApi(messageData)
}

//clase 19
function showLocation(senderId) {
    const messageData = {
        "recipient": {
            "id": senderId
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "generic",
                    "elements":[
                        {
                          "title":"Nuestas Sucursales en Medellín",
                          "subtitle":"Disfruta de un 10% de descuento los viernes",
                          "image_url": "https://media-cdn.tripadvisor.com/media/photo-w/13/df/d8/ea/our-new-look-store.jpg",
                          "buttons":[
                            {
                                "type":"web_url",
                                "url":"https://www.google.com/maps/search/domino's+pizza/@6.2477598,-75.5941865,12z",
                                "title":"Abrir mapa",
                                "webview_height_ratio": "tall"
                            }
                          ]
                        }
                      ]
                }
            }
        }
    }
    callSendApi(messageData)
}


app.listen(app.get('port'), function(){
    console.log('Nuestro servidor esta funcionando con el barto en el puerto: ', app.get('port'));
});

Texto para mandar al servidor:

curl -X POST -H "Content-Type: application/json" -d '{
    "get_started": {"payload": "GET_STARTED_PIZZAPLANETA"}
  }' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"


  curl -X POST -H "Content-Type: application/json" -d '{
"greeting": [{
  "locale": "default",
  "text": "Hola {{user_first_name}} Esto es PizzaPlaneta, te invitamos a conocer nuestras geniales Pizzas \u26A1!"
}, {
  "locale": "en_US",
  "text": "Hello {{user_first_name}} This is PizzaPlaneta, we invite you to check our amazing pizzas \u26A1!"
}]
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

curl -X POST -H "Content-Type: application/json" -d '{
"persistent_menu": [{
  "locale": "default",
  "composer_input_disabled": false,
  "call_to_actions": [{
      "title": "\u26A1 PizzaPlaneta ",
      "type": "nested",
      "call_to_actions": [{
          "title": "About",
          "type": "postback",
          "payload": "ABOUT_PAYLOAD"
        },
        {
          "title": "Pizza shops",
          "type": "postback",
          "payload": "LOCATIONS_PAYLOAD"
        },
        {
          "title": "Help",
          "type": "postback",
          "payload": "HELP_PAYLOAD"
        },
        {
          "title": "Contact us",
          "type": "postback",
          "payload": "CONTACT_PAYLOAD"
        }
      ]
    },
    {
      "title": "\u26A1 Our Menu",
      "type": "nested",
      "call_to_actions": [{
          "title": "Pizzas",
          "type": "postback",
          "payload": "PIZZAS_PAYLOAD"
        },
        {
          "title": "Specials",
          "type": "postback",
          "payload": "SPECIALS_PAYLOAD"
        },
        {
          "title": "Drinks",
          "type": "postback",
          "payload": "DRINKS_PAYLOAD"
        },
        {
          "title": "Discounts",
          "type": "postback",
          "payload": "PROMOTIONS_PAYLOAD"
        }
      ]
    },
    {
      "type": "web_url",
      "title": "\u26A1 Our webpage",
      "url": "https://github.com/AndresCampuzano",
      "webview_height_ratio": "full"
    }
  ]
}]
}
' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

No se como verlo en mi celular, lo busco en messenger y envío un mensaje pero nada ocurre, Pude alguien ayudarme?

Por alguna razon no me funciona el codigo, le he dado mil vueltas y no se si hay un typo que no veo o estructure algo mal, alguien puede ayudarme?

function showLocations(senderID) {
    const messageData = {
        "recipient": {
            "id": senderID
        }, 

        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "list",
                    "top_element_style": "compact",
                    "elements": [
                        {
                            "title": "Surcursal Mexico",
                            "image_url": "https://s3.amazonaws.com/chewiekie/img/productos-pizza-peperoni-champinones.jpg",
                            "subtitle": "Cll XX # XX-XX",
                            "buttons": [
                                {
                                    "title": "Ver en el mapa",
                                    "type": "web_url",
                                    "url": "https://goo.gl/maps/GCCpWmZep1t",
                                    "webview_height_ratio": "full"
                                }
                            ]
                        },

                        {
                            "title": "Surcursal Colombia",
                            "image_url": "https://s3.amazonaws.com/chewiekie/img/productos-pizza-peperoni-champinones.jpg",
                            "subtitle": "Cll ZZ # ZZ-ZZ",
                            "buttons": [
                                {
                                    "title": "Ver en el mapa",
                                    "type": "web_url",
                                    "url": "https://goo.gl/maps/GCCpWmZep1t",
                                    "webview_height_ratio": "tall"
                                }
                            ]
                        }
                    ]
                }
            }
        }
    }

    callSendApi(messageData);
}

con respecto a la ubicacion podemos poner las coordenadas de google maps