3

I'm creating a bot using dialogflow ( api.ai ) and webhook in c# using visual studio.

I have to create the option of broadcast message for all the user who has request to be subscribe.

When user call intent subscribe , i call the action : subscribe.about where i save psid .

The code below :

 public ApiAiResponse Post([FromBody]JObject jsonRequest)
    {
        using (WebhookReceiverModelDataContext ctx = new 
      WebhookReceiverModelDataContext())
        {


            ApiAiRequest request = jsonRequest.ToObject<ApiAiRequest>();

            ApiAiResponse response = new ApiAiResponse();

            JObject jObject = 
            JObject.Parse(request.result.parameters.ToString());
         if ("subscribe.about".Equals(request.result.action.ToLower()))
            {

    using (WebhookReceiverModelDataContext cts = new 
       WebhookReceiverModelDataContext())
                {
                    string messageabout = request.result.resolvedQuery != null ? request.result.resolvedQuery : "";                  


                    speechLang = "You are subscribed";
                    source = "Broadcast";

                }

            }

I have to create a module to send broadcast message to all this users in the moment that the event will be online .

I have in a table stored data like : Id, Event Name , Event Date

When : Event Date = now => i have to send the message all this users which are subscribed.

I start to use proactive message , but seems that they are created using botframework . I want to use only the webhook .

I created a controller to send message in facebook , but seems not OK : I got this message when i call this controller :

<Error>
<Message>An error has occurred.</Message>
</Error>


     namespace WebhookReceiver.Controllers
     {
    public class WebhookController : ApiController
     {
    string pageToken = "xxxxxxx";
    string appSecret = "yyyyy";

    public HttpResponseMessage Get()
    {
        var querystrings = Request.GetQueryNameValuePairs().ToDictionary(x 
        => x.Key, x => x.Value);
         if (querystrings["hub.verify_token"] == "zzzzz")
        {
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(querystrings["hub.challenge"], 
         Encoding.UTF8, "text/plain")
            };
        }
        return new HttpResponseMessage(HttpStatusCode.Unauthorized);
    }

    [HttpPost]
    public async Task<HttpResponseMessage> Post()
    {
        var signature = Request.Headers.GetValues("X-Hub- 
         Signature").FirstOrDefault().Replace("sha1=", "");
        var body = await Request.Content.ReadAsStringAsync();
        if (!VerifySignature(signature, body))
            return new HttpResponseMessage(HttpStatusCode.BadRequest);

        var value = JsonConvert.DeserializeObject<WebhookModel>(body);
        if (value._object != "page")
            return new HttpResponseMessage(HttpStatusCode.OK);

        foreach (var item in value.entry[0].messaging)
        {
            if (item.message == null && item.postback == null)
                continue;
            else
                await SendMessage(GetMessageTemplate(item.message.text, 
          item.sender.id));
        }

        return new HttpResponseMessage(HttpStatusCode.OK);
    }

    private bool VerifySignature(string signature, string body)
    {
        var hashString = new StringBuilder();
        using (var crypto = new HMACSHA1(Encoding.UTF8.GetBytes(appSecret)))
        {
            var hash = crypto.ComputeHash(Encoding.UTF8.GetBytes(body));
            foreach (var item in hash)
                hashString.Append(item.ToString("X2"));
        }

        return hashString.ToString().ToLower() == signature.ToLower();
    }

    /// <summary>
    /// get text message template
    /// </summary>
    /// <param name="text">text</param>
    /// <param name="sender">sender id</param>
    /// <returns>json</returns>
    private JObject GetMessageTemplate(string text, string sender)
    {
        return JObject.FromObject(new
        {
            recipient = new { id = sender },
            message = new { text = text }
        });
    }

    /// <summary>
    /// send message
    /// </summary>
    /// <param name="json">json</param>
    private async Task SendMessage(JObject json)
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new 
     MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage res = await 
  client.PostAsync($"https://graph.facebook.com/v2.6/me/messages? 
     access_token={pageToken}", new StringContent(json.ToString(), 
       Encoding.UTF8, 
   "application/json"));
        }
    }
  }
 }

How can i create this module please . I need some advises . Using postman i have test to send message in by bot using API call of Facebook . I'm new in c# so please help me :(

  • what is at the bot client side? I mean FB messanger, web page, slack... etc.? I think you will have to implement this broadcast functionality outside of dialogflow. – pgcan Apr 18 '18 at 11:24
  • Facebook , thnx @Prasoon –  Apr 18 '18 at 11:47

0 Answers0