Search code examples
c#botframeworkmessenger

Converting facebook button template from json to c#


Hello i am trying to do this template on my C# code for Bot Framework V4. This is the code from facebook.

  "payload": {
  "template_type":"button",
  "text":"<MESSAGE_TEXT>",
  "buttons":[
    <BUTTON_OBJECT>, 
    <BUTTON_OBJECT>, 
    ...
  ]
}

And this is my attempt of doing it. I can't debug the error cause it only works on messenger. Any help would be appreciated thank you.

            Activity reply = stepContext.Context.Activity.CreateReply();
            reply.ChannelData = JObject.FromObject(
                new
                {
                    attachment = new
                    {
                        type = "template",
                        payload = new
                        {
                            template_type = "button",
                            text = "xx",
                            buttons = new[]
                            {
                               new
                                  {
                                       type = "web_url",
                                       title = "take test",
                                       url = "xx",
                                       messenger_extensions="true",
                                       webview_height_ratio = "tall",
                                  },
                            },
                        },
                    },
                });
            await stepContext.Context.SendActivityAsync(reply);

Solution

  • Your code looks fine. Make sure to Whitelist any URLs you use with Facebook. Note, they must be https URLs. Additionally, unless the website is configured to be a webview, you do not need the messenger_extensions and webview_height_ratio properties in the button.

    var reply = turnContext.Activity.CreateReply();
    
    var attachment = new
    {
        type = "template",
        payload = new
        {
            template_type = "button",
            text = "Sign up for our mailing list!",
            buttons = new[]
            {
                new
                {
                    type = "web_url",
                    url = "https://mybot.azurewebsites.net/",
                    title = "Sign Up!"
                },
            },
        },
    };
    
    reply.ChannelData = JObject.FromObject(new { attachment });
    
    await turnContext.SendActivityAsync(reply, cancellationToken);
    
    

    Take a look at Messengers Documentation on Button Templates for more details.

    Hope this helps!