How to get user information using webhook in c#

坚强是说给别人听的谎言 提交于 2019-12-08 11:44:32

问题


I'm using api.ai and for webhook visual studo 2015 c# .

I have created some action for some intents and now i'm looking for an action called "welcome.input". I want to get username of the user. If the user is starting conversation with the bot for the first time i want to give him the possibility to view help menu or standard menu , and when the user re-enter in the bot i want to send text : Welcome back {username} and to show him the standard menu.

Have you any idea how to do this.

I was reading https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/core-State this sample ...but i cannot addapt as webhook in my project.

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


    }
}

Please help me . I have many times searching about this topic


回答1:


So your question is a little vague, but at a conceptual level what you will need to do is

  1. Store some unique user or session ID coming from the messaging integration like facebook messenger
  2. Save the associated name with the userID in some kind of Map of key-values, or for a more viable production option in a database. Note that if you want to check if some time has passed since the last message to do some kind of 'welcome back message' based on time gap of messages you will also want to store the timestamp for the latest message
  3. On message, check if user exists, if not its a brand new user and prompt for name, if yes run timestamp check to see if coming back after some time away

Here's an example in javascript to demonstrate the approach itself, where you would call this function on receipt of a message from the user, and before passing it to 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)
            }
        }

EDITED TO ADD EXAMPLES FOR 'CATCHING' MESSAGE EVENTS AND THEN PARSING THEM:

//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;
  //...
 }


来源:https://stackoverflow.com/questions/43609553/how-to-get-user-information-using-webhook-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!