如何激活webhookcontroller?

时间:2018-04-16 15:45:03

标签: c# visual-studio facebook-graph-api webhooks dialogflow

我正在使用面向webhook的对话框流在facebook messenger中创建一个聊天机器人,我使用visual studio c#。

我想在特定时刻在chatbot messenger中向用户发送消息。

我有两个不同的控制器,第一个用于意图实现:

namespace WebhookReceiver.Controllers
{

public class FirstController : ApiController
{
    GlobalClasses gc = new GlobalClasses();


    public string Get()
    {
        return "OK";
    }


    public int Get(int id)
    {
        return id;
    }


    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 ("input.data".Equals(request.result.action.ToLower()))
            {

                                speechLang = "xxxx";
                                source = "NoResult";
                            }

我创建的第二个控制器发送广播消息(当调用action input.data(在firstController中)时,我不知道如何调用此控制器。

我保存用户的PSID以在另一时刻发送广播消息(当事件在线时)。

public HttpResponseMessage Get()
{
    var querystrings = Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
    if (querystrings["hub.verify_token"] == "xxxx")
    {
        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"));
    }
}

您是否知道如何使用此webhook为机器人中订阅的用户发送通知消息? 我想从数据库中获取计时器。架构数据库将如下所示:

ID | Message | Event | EventDate | 1 | text text | Birthday | 13/04/2018 17:05

0 个答案:

没有答案