3

我正在使用 Visual Studio 在 c# 中使用 dialogflow ( api.ai ) 和 webhook 创建一个机器人。

我必须为所有请求订阅的用户创建广播消息选项。

当用户调用意图订阅时,我调用操作:subscribe.about 我保存 psid 的位置。

下面的代码:

 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";

                }

            }

我必须创建一个模块,以便在活动上线时向所有这些用户发送广播消息。

我在表中存储了以下数据:ID、事件名称、事件日期

时间: 事件日期 = 现在=> 我必须向所有订阅的用户发送消息。

我开始使用主动消息,但似乎它们是使用 botframework 创建的。我只想使用 webhook 。

我创建了一个控制器来在 facebook 中发送消息,但似乎不行当我调用这个控制器时,我收到了这条消息:

<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"));
        }
    }
  }
 }

请问我该如何创建这个模块。我需要一些建议。使用邮递员我已经测试使用 Facebook 的 API 调用通过机器人发送消息。我是 C# 新手,所以请帮助我:(

4

0 回答 0