如何在c#中使用webhook获取用户信息

时间:2017-04-25 11:34:40

标签: c# facebook bots webhooks dialogflow

我正在使用api.ai和webhook visual studo 2015 c#。

我为某些意图创建了一些动作,现在我正在寻找一个名为“welcome.input”的动作。我想获得用户的用户名。 如果用户第一次与机器人开始对话我想让他有机会查看帮助菜单或标准菜单, 当用户重新进入机器人时我想发送文字:欢迎回来{username}并向他显示标准菜单。

你知道怎么做吗?

我正在阅读https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/core-State这个示例...但我不能在我的项目中添加ash作为webhook。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using WebhookReceiver.Models;

  namespace FBReceiver.Controllers
    {

public class  facebookController : ApiController
{

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


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



    public ApiAiResponse Post([FromBody]JObject jsonRequest)
    {
        using (FbReceiverModelDataContext ctx = new 
   FbModelDataContext())
        {
            ctx.spTblTransactions_CreateNew("xyz", "Request", 
   jsonRequest.ToString(), HttpContext.Current.User.Identity.Name);

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

            ApiAiResponse response = new ApiAiResponse();

            JObject jObject = JObject.Parse(request.result.parameters.ToString());
            string xyznumber = (string)jObject["xyznumber"] != null ? (string)jObject["xyznumber"] : "";

            string otherparameter = (string)jObject["otherparameter"] != null ? (string)jObject["otherparameter"] : "";

            if (("action1".Equals(request.result.action.ToLower())))
            {
                tbla a= new tbla();
                a= ctx.tblAa.SingleOrDefault(u => u.a.ToLower() == a.ToLower());

                if (a!= null)
                {
                    response.speech = "a with number " + xyznumber+ " " + a.aaaa;

                    response.source = "aaa";
                }
                else if (!string.IsNullOrEmpty(xyznumber))
                {
                    response.speech = "Generic info about " + xyznumber;
                    response.displayText = "Generic info about " + xyznumber;
                    response.source = "aaaa";
                }
                else
                {
                    response.speech = "No info";
                    response.displayText = "No info";
                    response.source = "Parcels";
                }
            }



            else if (("pay.info".Equals(request.result.action.ToLower())))
            {
                ///yyyyyyyyyyyyyyyyyyyyyyyyyyyyy
            }


            else if (("welcome.input".Equals(request.result.action.ToLower())))
            {

                // to do 

            }


            else
            {
                response.speech = "something is wrong ????";
                response.displayText = "something is wrong ????";
                response.source = "None";
            }




            ctx.spTblTransactions_CreateNew("aaaa", "Response", JsonConvert.SerializeObject(response), HttpContext.Current.User.Identity.Name);

            return response;
        }
    }


    }
}

请帮帮我。我有很多次搜索这个话题

1 个答案:

答案 0 :(得分:0)

所以你的问题有点模糊,但从概念上讲,你需要做的是

  1. 存储来自facebook messenger等邮件集成的一些唯一用户或会话ID
  2. 将关联名称与userID保存在某种键值映射中,或者保存在数据库中更可行的生产选项中。请注意,如果您想检查自上一条消息以来是否已经过了一段时间,根据消息的时间间隔执行某种“欢迎回复消息”,您还需要存储最新消息的时间戳
  3. 在消息上,检查用户是否存在,如果不是全新用户并提示输入名称,如果是,则运行时间戳检查以查看是否在一段时间后返回
  4. 以下是javascript中用于演示方法本身的示例,您可以在收到来自用户的消息时调用此函数,然后将其传递给API.ai:

            function setSessionAndUser(messageEvent, callback) {
                var senderID = messageEvent.sender.id;
                var firstTimeUser = false
                if (!sessionIds.has(senderID)) {
                    sessionIds.set(senderID, uuid.v1());
                }
    
                if (!usersMap.has(senderID)) {
                    firstTimeUser = true
                    database.userData( function (user) {
                        usersMap.set(senderID, user);
                        //Note this is not touching the database and is instead temporarily storing users as a Map in server memory, it's a tradeoff of waiting to touch the DB before replying to every message vs how permanent you need the data to be (and how much data you'll be dealing with)
                        callback(messageEvent, firstTimeUser)
                    }, senderID);
                } else{
                    callback(messageEvent, firstTimeUser)
                }
            }

    编辑添加“捕获”消息事件的示例,然后分享它们:

    //Post to webhook to catch messages
    app.post('/webhook/', function (req, res) {
        var data = req.body;
    
        // Make sure this is a page subscription
        if (data.object == 'page') {
            // Iterate over each entry
            // There may be multiple if batched
            data.entry.forEach(function (pageEntry) {
                var pageID = pageEntry.id;
                var timeOfEvent = pageEntry.time;
    
                // Iterate over each messaging event
                pageEntry.messaging.forEach(function (messagingEvent) {
                    if (messagingEvent.message) {
                        receivedMessage(messagingEvent);
                    }
                    //Catch all
                    else {
                        console.log("Webhook received unknown messagingEvent: ", messagingEvent);
                    }
                });
            });
    
            //Must return a 200 status
            res.sendStatus(200);
        }
    });
    
    // Parsing the messageEvent
    function receivedMessage(event) {
      var senderID = event.sender.id;
      //...
     }