Пример #1
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            string cashOrgMent = "";

            //DbConnect db = new DbConnect();
            //DButil dbutil = new DButil();
            DButil.HistoryLog("db connect !! ");
            //HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            HttpResponseMessage response;

            Activity reply1 = activity.CreateReply();
            Activity reply2 = activity.CreateReply();
            Activity reply3 = activity.CreateReply();
            Activity reply4 = activity.CreateReply();

            // Activity 값 유무 확인하는 익명 메소드
            Action <Activity> SetActivity = (act) =>
            {
                if (!(reply1.Attachments.Count != 0 || reply1.Text != ""))
                {
                    reply1 = act;
                }
                else if (!(reply2.Attachments.Count != 0 || reply2.Text != ""))
                {
                    reply2 = act;
                }
                else if (!(reply3.Attachments.Count != 0 || reply3.Text != ""))
                {
                    reply3 = act;
                }
                else if (!(reply4.Attachments.Count != 0 || reply4.Text != ""))
                {
                    reply4 = act;
                }
                else
                {
                }
            };

            if (activity.Type == ActivityTypes.ConversationUpdate && activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id))
            {
                startTime = DateTime.Now;
                //activity.ChannelId = "facebook";
                //파라메터 호출
                if (LUIS_NM.Count(s => s != null) > 0)
                {
                    //string[] LUIS_NM = new string[10];
                    Array.Clear(LUIS_NM, 0, LUIS_NM.Length);
                }

                if (LUIS_APP_ID.Count(s => s != null) > 0)
                {
                    //string[] LUIS_APP_ID = new string[10];
                    Array.Clear(LUIS_APP_ID, 0, LUIS_APP_ID.Length);
                }
                //Array.Clear(LUIS_APP_ID, 0, 10);
                DButil.HistoryLog("db SelectConfig start !! ");
                List <ConfList> confList = db.SelectConfig();
                DButil.HistoryLog("db SelectConfig end!! ");


                DButil.HistoryLog("* confList.Count : " + confList.Count);

                for (int i = 0; i < confList.Count; i++)
                {
                    switch (confList[i].cnfType)
                    {
                    case "LUIS_APP_ID":
                        LUIS_APP_ID[LUIS_APP_ID.Count(s => s != null)] = confList[i].cnfValue;
                        LUIS_NM[LUIS_NM.Count(s => s != null)]         = confList[i].cnfNm;

                        DButil.HistoryLog("* confList[" + i + "].cnfNm : " + confList[i].cnfNm);
                        DButil.HistoryLog("* confList[" + i + "].cnfValue : " + confList[i].cnfValue);

                        break;

                    case "LUIS_SUBSCRIPTION":
                        LUIS_SUBSCRIPTION = confList[i].cnfValue;
                        break;

                    case "BOT_ID":
                        BOT_ID = confList[i].cnfValue;
                        break;

                    case "MicrosoftAppId":
                        MicrosoftAppId = confList[i].cnfValue;
                        break;

                    case "MicrosoftAppPassword":
                        MicrosoftAppPassword = confList[i].cnfValue;
                        break;

                    case "QUOTE":
                        QUOTE = confList[i].cnfValue;
                        break;

                    case "TESTDRIVE":
                        TESTDRIVE = confList[i].cnfValue;
                        break;

                    case "LUIS_SCORE_LIMIT":
                        LUIS_SCORE_LIMIT = confList[i].cnfValue;
                        break;

                    case "LUIS_TIME_LIMIT":
                        LUIS_TIME_LIMIT = Convert.ToInt32(confList[i].cnfValue);
                        break;

                    default:     //미 정의 레코드
                        Debug.WriteLine("*conf type : " + confList[i].cnfType + "* conf value : " + confList[i].cnfValue);
                        DButil.HistoryLog("*conf type : " + confList[i].cnfType + "* conf value : " + confList[i].cnfValue);
                        break;
                    }
                }

                Debug.WriteLine("* DB conn : " + activity.Type);
                DButil.HistoryLog("* DB conn : " + activity.Type);

                //초기 다이얼로그 호출
                List <DialogList> dlg = db.SelectInitDialog(activity.ChannelId);

                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                foreach (DialogList dialogs in dlg)
                {
                    Activity initReply = activity.CreateReply();
                    initReply.Recipient   = activity.From;
                    initReply.Type        = "message";
                    initReply.Attachments = new List <Attachment>();
                    //initReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                    Attachment tempAttachment;

                    if (dialogs.dlgType.Equals(CARDDLG))
                    {
                        foreach (CardList tempcard in dialogs.dialogCard)
                        {
                            tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);
                            initReply.Attachments.Add(tempAttachment);
                        }
                    }
                    else
                    {
                        if (activity.ChannelId.Equals("facebook") && string.IsNullOrEmpty(dialogs.cardTitle) && dialogs.dlgType.Equals(TEXTDLG))
                        {
                            Activity reply_facebook = activity.CreateReply();
                            reply_facebook.Recipient = activity.From;
                            reply_facebook.Type      = "message";
                            DButil.HistoryLog("facebook  card Text : " + dialogs.cardText);
                            reply_facebook.Text = dialogs.cardText;
                            var reply_ment_facebook = connector.Conversations.SendToConversationAsync(reply_facebook);
                            //SetActivity(reply_facebook);
                        }
                        else
                        {
                            tempAttachment = dbutil.getAttachmentFromDialog(dialogs, activity);
                            initReply.Attachments.Add(tempAttachment);
                        }
                    }
                    await connector.Conversations.SendToConversationAsync(initReply);
                }

                DateTime endTime = DateTime.Now;
                Debug.WriteLine("프로그램 수행시간 : {0}/ms", ((endTime - startTime).Milliseconds));
                Debug.WriteLine("* activity.Type : " + activity.Type);
                Debug.WriteLine("* activity.Recipient.Id : " + activity.Recipient.Id);
                Debug.WriteLine("* activity.ServiceUrl : " + activity.ServiceUrl);

                DButil.HistoryLog("* activity.Type : " + activity.ChannelData);
                DButil.HistoryLog("* activity.Recipient.Id : " + activity.Recipient.Id);
                DButil.HistoryLog("* activity.ServiceUrl : " + activity.ServiceUrl);
            }
            else if (activity.Type == ActivityTypes.Message)
            {
                //activity.ChannelId = "facebook";
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                try
                {
                    Debug.WriteLine("* activity.Type == ActivityTypes.Message ");
                    channelID = activity.ChannelId;
                    string orgMent = activity.Text;


                    apiFlag = "COMMON";

                    //대화 시작 시간
                    startTime = DateTime.Now;
                    long unixTime = ((DateTimeOffset)startTime).ToUnixTimeSeconds();

                    DButil.HistoryLog("orgMent : " + orgMent);
                    //금칙어 체크
                    CardList bannedMsg = db.BannedChk(orgMent);
                    Debug.WriteLine("* bannedMsg : " + bannedMsg.cardText);//해당금칙어에 대한 답변

                    //if (bannedMsg.cardText != null)
                    //{
                    //    Activity reply_ment = activity.CreateReply();
                    //    reply_ment.Recipient = activity.From;
                    //    reply_ment.Type = "message";
                    //    reply_ment.Text = bannedMsg.cardText;

                    //    var reply_ment_info = await connector.Conversations.SendToConversationAsync(reply_ment);
                    //    response = Request.CreateResponse(HttpStatusCode.OK);
                    //    return response;
                    //}


                    if (bannedMsg.cardText != null)
                    {
                        Activity reply_ment = activity.CreateReply();
                        reply_ment.Recipient = activity.From;
                        reply_ment.Type      = "message";
                        //reply_ment.Text = bannedMsg.cardText;

                        //var reply_ment_info = await connector.Conversations.SendToConversationAsync(reply_ment);
                        //response = Request.CreateResponse(HttpStatusCode.OK);
                        //return response;

                        reply_ment.Attachments      = new List <Attachment>();
                        reply_ment.AttachmentLayout = AttachmentLayoutTypes.Carousel;


                        HeroCard plCard = new HeroCard()
                        {
                            Text = bannedMsg.cardText
                        };
                        Attachment plAttachment = plCard.ToAttachment();
                        reply_ment.Attachments.Add(plAttachment);

                        SetActivity(reply_ment);
                        replyresult = "D";
                    }

                    else
                    {
                        luisQuery = orgMent;
                        queryStr  = orgMent;
                        //인텐트 엔티티 검출
                        //캐시 체크
                        //cashOrgMent = Regex.Replace(orgMent, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);
                        //cacheList = db.CacheChk(cashOrgMent.Replace(" ", ""));                     // 캐시 체크


                        orgMent              = Regex.Replace(orgMent, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);
                        orgMent              = orgMent.Replace(" ", "").ToLower();
                        queryStr             = orgMent;
                        cacheList.luisIntent = null;

                        //캐시에 없을 경우
                        if (cacheList.luisIntent == null || cacheList.luisEntities == null)
                        {
                            DButil.HistoryLog("cache none : " + orgMent);
                            //루이스 체크
                            //cacheList.luisId = dbutil.GetMultiLUIS(orgMent);
                            cacheList.luisIntent = dbutil.GetMultiLUIS(luisQuery);
                            Debug.WriteLine("cacheList.luisIntent : " + cacheList.luisIntent);
                            //Debug.WriteLine("cacheList.luisEntitiesValue : " + cacheList.luisEntitiesValue);
                            cacheList = db.CacheDataFromIntent(cacheList.luisIntent);
                        }

                        //if (cacheList != null && cacheList.luisIntent != null)
                        //{
                        //    if (cacheList.luisIntent.Contains("testdrive") || cacheList.luisIntent.Contains("branch"))
                        //    {
                        //        apiFlag = "TESTDRIVE";
                        //    }
                        //    else if (cacheList.luisIntent.Contains("quot"))
                        //    {
                        //        apiFlag = "QUOT";
                        //    }
                        //    else if (cacheList.luisIntent.Contains("recommend "))
                        //    {
                        //        apiFlag = "RECOMMEND";
                        //    }
                        //    else
                        //    {
                        //        apiFlag = "COMMON";
                        //    }
                        //    DButil.HistoryLog("cacheList.luisIntent : " + cacheList.luisIntent);
                        //}

                        luisId          = cacheList.luisId;
                        luisIntent      = cacheList.luisIntent;
                        luisEntities    = cacheList.luisEntities;
                        luisIntentScore = cacheList.luisScore;

                        if (!string.IsNullOrEmpty(luisIntent))
                        {
                            relationList = db.DefineTypeChkSpare(cacheList.luisIntent, cacheList.luisEntities);
                        }
                        else
                        {
                            relationList = null;
                        }


                        //String fullentity = db.SearchCommonEntities;
                        //DButil.HistoryLog("fullentity : " + fullentity);
                        //if (!string.IsNullOrEmpty(fullentity) || !fullentity.Equals(""))
                        //{
                        //    if (!String.IsNullOrEmpty(luisEntities))
                        //    {
                        //        //entity 길이 비교
                        //        if (fullentity.Length > luisEntities.Length || luisIntent == null || luisIntent.Equals(""))
                        //        {
                        //            //DefineTypeChkSpare에서는 인텐트나 루이스아이디조건 없이 엔티티만 일치하면 다이얼로그 리턴
                        //            relationList = db.DefineTypeChkSpare(fullentity);
                        //        }
                        //        else
                        //        {
                        //            relationList = db.DefineTypeChk(MessagesController.luisId, MessagesController.luisIntent, MessagesController.luisEntities);
                        //        }
                        //    }
                        //    else
                        //    {
                        //        relationList = db.DefineTypeChkSpare(fullentity);
                        //    }
                        //}
                        //else
                        //{

                        //    if (apiFlag.Equals("COMMON"))
                        //    {
                        //        relationList = db.DefineTypeChkSpare(cacheList.luisEntities);
                        //    }
                        //    else
                        //    {
                        //        relationList = null;
                        //    }

                        //}
                        //if (relationList != null)
                        ////if (relationList.Count > 0)
                        //{
                        //    if (relationList.Count > 0 && relationList[0].dlgApiDefine != null)
                        //    {
                        //        if (relationList[0].dlgApiDefine.Equals("api testdrive"))
                        //        {
                        //            apiFlag = "TESTDRIVE";
                        //        }
                        //        else if (relationList[0].dlgApiDefine.Equals("api quot"))
                        //        {
                        //            apiFlag = "QUOT";
                        //        }
                        //        else if (relationList[0].dlgApiDefine.Equals("api recommend"))
                        //        {
                        //            apiFlag = "RECOMMEND";
                        //        }
                        //        else if (relationList[0].dlgApiDefine.Equals("D"))
                        //        {
                        //            apiFlag = "COMMON";
                        //        }
                        //        DButil.HistoryLog("relationList[0].dlgApiDefine : " + relationList[0].dlgApiDefine);
                        //    }

                        //}
                        //else
                        //{

                        //    if (MessagesController.cacheList.luisIntent == null || apiFlag.Equals("COMMON"))
                        //    {
                        //        apiFlag = "";
                        //    }
                        //    else if (MessagesController.cacheList.luisId.Equals("hanHwaLifeChatBot_luis_01") && MessagesController.cacheList.luisIntent.Contains("quot"))
                        //    {
                        //        apiFlag = "QUOT";
                        //    }
                        //}


                        //if (apiFlag.Equals("COMMON") && relationList.Count > 0)
                        if (relationList != null)
                        {
                            //context.Call(new CommonDialog("", MessagesController.queryStr), this.ResumeAfterOptionDialog);
                            dlgId = "";
                            for (int m = 0; m < MessagesController.relationList.Count; m++)
                            {
                                DialogList dlg = db.SelectDialog(MessagesController.relationList[m].dlgId);
                                dlgId += Convert.ToString(dlg.dlgId) + ",";
                                Activity   commonReply    = activity.CreateReply();
                                Attachment tempAttachment = new Attachment();
                                DButil.HistoryLog("dlg.dlgType : " + dlg.dlgType);
                                if (dlg.dlgType.Equals(CARDDLG))
                                {
                                    foreach (CardList tempcard in dlg.dialogCard)
                                    {
                                        DButil.HistoryLog("tempcard.card_order_no : " + tempcard.card_order_no);

                                        tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);
                                        if (tempAttachment != null)
                                        {
                                            commonReply.Attachments.Add(tempAttachment);
                                        }

                                        //2018-04-19:KSO:Carousel 만드는부분 추가
                                        if (tempcard.card_order_no > 1)
                                        {
                                            commonReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                                        }
                                    }
                                }
                                else
                                {
                                    DButil.HistoryLog("facebook dlg.dlgId : " + dlg.dlgId);
                                    tempAttachment = dbutil.getAttachmentFromDialog(dlg, activity);
                                    commonReply.Attachments.Add(tempAttachment);
                                }

                                if (commonReply.Attachments.Count > 0)
                                {
                                    SetActivity(commonReply);
                                    conversationhistory.commonBeforeQustion = orgMent;
                                    replyresult = "H";
                                }
                            }
                        }
                        else
                        {
                            string newUserID         = activity.Conversation.Id;
                            string beforeUserID      = "";
                            string beforeMessgaeText = "";
                            //string messgaeText = "";

                            Activity intentNoneReply = activity.CreateReply();
                            //Boolean sorryflag = false;


                            if (beforeUserID != newUserID)
                            {
                                beforeUserID = newUserID;
                                MessagesController.sorryMessageCnt = 0;
                            }

                            var message = MessagesController.queryStr;
                            beforeMessgaeText = message.ToString();

                            Debug.WriteLine("SERARCH MESSAGE : " + message);

                            Activity sorryReply = activity.CreateReply();
                            sorryReply.Recipient        = activity.From;
                            sorryReply.Type             = "message";
                            sorryReply.Attachments      = new List <Attachment>();
                            sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                            List <TextList> text = new List <TextList>();
                            text = db.SelectSorryDialogText("5");
                            for (int i = 0; i < text.Count; i++)
                            {
                                HeroCard plCard = new HeroCard()
                                {
                                    Title = text[i].cardTitle,
                                    Text  = text[i].cardText
                                };

                                Attachment plAttachment = plCard.ToAttachment();
                                sorryReply.Attachments.Add(plAttachment);
                            }

                            SetActivity(sorryReply);
                            replyresult = "D";



                            ////네이버 기사 검색
                            //if (sorryflag)
                            //{
                            //    //Sorry Message
                            //    int sorryMessageCheck = db.SelectUserQueryErrorMessageCheck(activity.Conversation.Id, MessagesController.chatBotID);

                            //    ++MessagesController.sorryMessageCnt;

                            //    Activity sorryReply = activity.CreateReply();

                            //    sorryReply.Recipient = activity.From;
                            //    sorryReply.Type = "message";
                            //    sorryReply.Attachments = new List<Attachment>();
                            //    sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                            //    List<TextList> text = new List<TextList>();
                            //    if (sorryMessageCheck == 0)
                            //    {
                            //        text = db.SelectSorryDialogText("5");
                            //    }
                            //    else
                            //    {
                            //        text = db.SelectSorryDialogText("6");
                            //    }

                            //    for (int i = 0; i < text.Count; i++)
                            //    {
                            //        HeroCard plCard = new HeroCard()
                            //        {
                            //            Title = text[i].cardTitle,
                            //            Text = text[i].cardText
                            //        };

                            //        Attachment plAttachment = plCard.ToAttachment();
                            //        sorryReply.Attachments.Add(plAttachment);
                            //    }

                            //    SetActivity(sorryReply);
                            //    //await connector.Conversations.SendToConversationAsync(sorryReply);
                            //    sorryflag = false;
                            //    replyresult = "D";
                            //}
                        }

                        DateTime endTime = DateTime.Now;
                        //analysis table insert
                        //if (rc != null)
                        //{
                        int dbResult = db.insertUserQuery();

                        //}
                        //history table insert
                        db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds));
                        replyresult     = "";
                        recommendResult = "";
                    }
                }
                catch (Exception e)
                {
                    Debug.Print(e.StackTrace);
                    int sorryMessageCheck = db.SelectUserQueryErrorMessageCheck(activity.Conversation.Id, MessagesController.chatBotID);

                    ++MessagesController.sorryMessageCnt;

                    Activity sorryReply = activity.CreateReply();

                    sorryReply.Recipient   = activity.From;
                    sorryReply.Type        = "message";
                    sorryReply.Attachments = new List <Attachment>();
                    //sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                    List <TextList> text = new List <TextList>();
                    if (sorryMessageCheck == 0)
                    {
                        text = db.SelectSorryDialogText("5");
                    }
                    else
                    {
                        text = db.SelectSorryDialogText("6");
                    }

                    for (int i = 0; i < text.Count; i++)
                    {
                        HeroCard plCard = new HeroCard()
                        {
                            Title = text[i].cardTitle,
                            Text  = text[i].cardText
                        };

                        Attachment plAttachment = plCard.ToAttachment();
                        sorryReply.Attachments.Add(plAttachment);
                    }

                    SetActivity(sorryReply);

                    DateTime endTime  = DateTime.Now;
                    int      dbResult = db.insertUserQuery();
                    db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds));
                    replyresult     = "";
                    recommendResult = "";
                }
                finally
                {
                    if (reply1.Attachments.Count != 0 || reply1.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply1);
                    }
                    if (reply2.Attachments.Count != 0 || reply2.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply2);
                    }
                    if (reply3.Attachments.Count != 0 || reply3.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply3);
                    }
                    if (reply4.Attachments.Count != 0 || reply4.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply4);
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            //string cashOrgMent = "";

            //DbConnect db = new DbConnect();
            //DButil dbutil = new DButil();
            DButil.HistoryLog("db connect !! ");
            //HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            HttpResponseMessage response;

            Activity reply1 = activity.CreateReply();
            Activity reply2 = activity.CreateReply();
            Activity reply3 = activity.CreateReply();
            Activity reply4 = activity.CreateReply();

            // Activity 값 유무 확인하는 익명 메소드
            Action <Activity> SetActivity = (act) =>
            {
                if (!(reply1.Attachments.Count != 0 || reply1.Text != ""))
                {
                    reply1 = act;
                }
                else if (!(reply2.Attachments.Count != 0 || reply2.Text != ""))
                {
                    reply2 = act;
                }
                else if (!(reply3.Attachments.Count != 0 || reply3.Text != ""))
                {
                    reply3 = act;
                }
                else if (!(reply4.Attachments.Count != 0 || reply4.Text != ""))
                {
                    reply4 = act;
                }
                else
                {
                }
            };

            if (activity.Type == ActivityTypes.ConversationUpdate && activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id))
            {
                startTime = DateTime.Now;
                //activity.ChannelId = "facebook";
                //파라메터 호출
                if (LUIS_NM.Count(s => s != null) > 0)
                {
                    //string[] LUIS_NM = new string[10];
                    Array.Clear(LUIS_NM, 0, LUIS_NM.Length);
                }

                if (LUIS_APP_ID.Count(s => s != null) > 0)
                {
                    //string[] LUIS_APP_ID = new string[10];
                    Array.Clear(LUIS_APP_ID, 0, LUIS_APP_ID.Length);
                }
                //Array.Clear(LUIS_APP_ID, 0, 10);
                DButil.HistoryLog("db SelectConfig start !! ");
                List <ConfList> confList = db.SelectConfig();
                DButil.HistoryLog("db SelectConfig end!! ");

                for (int i = 0; i < confList.Count; i++)
                {
                    switch (confList[i].cnfType)
                    {
                    case "LUIS_APP_ID":
                        LUIS_APP_ID[LUIS_APP_ID.Count(s => s != null)] = confList[i].cnfValue;
                        LUIS_NM[LUIS_NM.Count(s => s != null)]         = confList[i].cnfNm;
                        break;

                    case "LUIS_SUBSCRIPTION":
                        LUIS_SUBSCRIPTION = confList[i].cnfValue;
                        break;

                    case "BOT_ID":
                        BOT_ID = confList[i].cnfValue;
                        break;

                    case "MicrosoftAppId":
                        MicrosoftAppId = confList[i].cnfValue;
                        break;

                    case "MicrosoftAppPassword":
                        MicrosoftAppPassword = confList[i].cnfValue;
                        break;

                    case "LUIS_SCORE_LIMIT":
                        LUIS_SCORE_LIMIT = confList[i].cnfValue;
                        break;

                    case "LUIS_TIME_LIMIT":
                        LUIS_TIME_LIMIT = Convert.ToInt32(confList[i].cnfValue);
                        break;

                    default:     //미 정의 레코드
                        Debug.WriteLine("*conf type : " + confList[i].cnfType + "* conf value : " + confList[i].cnfValue);
                        DButil.HistoryLog("*conf type : " + confList[i].cnfType + "* conf value : " + confList[i].cnfValue);
                        break;
                    }
                }

                Debug.WriteLine("* DB conn : " + activity.Type);
                DButil.HistoryLog("* DB conn : " + activity.Type);

                //초기 다이얼로그 호출
                List <DialogList> dlg = db.SelectInitDialog(activity.ChannelId);

                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                foreach (DialogList dialogs in dlg)
                {
                    Activity initReply = activity.CreateReply();
                    initReply.Recipient   = activity.From;
                    initReply.Type        = "message";
                    initReply.Attachments = new List <Attachment>();
                    //initReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                    Attachment tempAttachment;

                    if (dialogs.dlgType.Equals(CARDDLG))
                    {
                        foreach (CardList tempcard in dialogs.dialogCard)
                        {
                            tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);
                            initReply.Attachments.Add(tempAttachment);

                            //2018-11-26:KSO:INIT Carousel 만드는부분 추가
                            if (tempcard.card_order_no > 1)
                            {
                                initReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                            }
                        }
                    }
                    else
                    {
                        tempAttachment = dbutil.getAttachmentFromDialog(dialogs, activity);
                        initReply.Attachments.Add(tempAttachment);
                    }
                    await connector.Conversations.SendToConversationAsync(initReply);
                }


                DateTime endTime = DateTime.Now;
                Debug.WriteLine("프로그램 수행시간 : {0}/ms", ((endTime - startTime).Milliseconds));
                Debug.WriteLine("* activity.Type : " + activity.Type);
                Debug.WriteLine("* activity.Recipient.Id : " + activity.Recipient.Id);
                Debug.WriteLine("* activity.ServiceUrl : " + activity.ServiceUrl);

                DButil.HistoryLog("* activity.Type : " + activity.ChannelData);
                DButil.HistoryLog("* activity.Recipient.Id : " + activity.Recipient.Id);
                DButil.HistoryLog("* activity.ServiceUrl : " + activity.ServiceUrl);
            }
            else if (activity.Type == ActivityTypes.Message)
            {
                //activity.ChannelId = "facebook";
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                try
                {
                    Debug.WriteLine("* activity.Type == ActivityTypes.Message ");
                    channelID = activity.ChannelId;
                    string orgMent = activity.Text;

                    //대화 시작 시간
                    startTime = DateTime.Now;
                    long unixTime = ((DateTimeOffset)startTime).ToUnixTimeSeconds();

                    DButil.HistoryLog("orgMent : " + orgMent);
                    //금칙어 체크
                    CardList bannedMsg = db.BannedChk(orgMent);
                    Debug.WriteLine("* bannedMsg : " + bannedMsg.cardText);//해당금칙어에 대한 답변

                    if (bannedMsg.cardText != null)
                    {
                        Activity reply_ment = activity.CreateReply();
                        reply_ment.Recipient = activity.From;
                        reply_ment.Type      = "message";
                        reply_ment.Text      = bannedMsg.cardText;

                        var reply_ment_info = await connector.Conversations.SendToConversationAsync(reply_ment);

                        response = Request.CreateResponse(HttpStatusCode.OK);
                        return(response);
                    }
                    else
                    {
                        //정규화
                        luisQuery = orgMent;
                        orgMent   = Regex.Replace(orgMent, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);
                        orgMent   = orgMent.Replace(" ", "").ToLower();
                        queryStr  = orgMent;
                        cacheList = db.CacheChk(orgMent.Replace(" ", ""));                     // 캐시 체크 (TBL_QUERY_ANALYSIS_RESULT 조회..)
                        //cacheList.luisIntent 초기화
                        //cacheList.luisIntent = null;

                        //smalltalk 문자 확인
                        String smallTalkSentenceConfirm = db.SmallTalkSentenceConfirm;

                        //smalltalk 답변이 있을경우
                        if (!string.IsNullOrEmpty(smallTalkSentenceConfirm))
                        {
                            luisId = "";
                        }
                        //luis 호출
                        else if (cacheList.luisIntent == null || cacheList.luisEntities == null)
                        {
                            DButil.HistoryLog("cache none : " + orgMent);
                            Debug.WriteLine("cache none : " + orgMent);
                            //루이스 체크(intent를 루이스를 통해서 가져옴)
                            //cacheList.luisId = dbutil.GetMultiLUIS(orgMent);
                            //Debug.WriteLine("cacheList.luisId : " + cacheList.luisId);

                            cacheList.luisIntent = dbutil.GetMultiLUIS(luisQuery);
                            Debug.WriteLine("cacheList.luisIntent : " + cacheList.luisIntent);
                            //Debug.WriteLine("cacheList.luisEntitiesValue : " + cacheList.luisEntitiesValue);
                            cacheList = db.CacheDataFromIntent(cacheList.luisIntent);

                            luisId          = cacheList.luisId;
                            luisIntent      = cacheList.luisIntent;
                            luisEntities    = cacheList.luisEntities;
                            luisIntentScore = cacheList.luisScore;
                        }
                        else
                        {
                            luisId          = cacheList.luisId;
                            luisIntent      = cacheList.luisIntent;
                            luisEntities    = cacheList.luisEntities;
                            luisIntentScore = cacheList.luisScore;
                        }

                        string smallTalkConfirm = "";

                        if (!string.IsNullOrEmpty(luisIntent))
                        {
                            relationList = db.DefineTypeChkSpare(cacheList.luisIntent);
                        }
                        else
                        {
                            relationList = null;
                            //smalltalk 답변가져오기
                            if (orgMent.Length < 11)    // 2019-04-30 smalltalk 길이제한 10으로 변경 (epkim)
                            {
                                smallTalkConfirm = db.SmallTalkConfirm;
                            }
                            else
                            {
                                smallTalkConfirm = "";
                            }
                        }

                        if (relationList != null)
                        {
                            dlgId = "";
                            for (int m = 0; m < MessagesController.relationList.Count; m++)
                            {
                                DialogList dlg = db.SelectDialog(MessagesController.relationList[m].dlgId);
                                dlgId += Convert.ToString(dlg.dlgId) + ",";
                                Activity   commonReply    = activity.CreateReply();
                                Attachment tempAttachment = new Attachment();
                                DButil.HistoryLog("dlg.dlgType : " + dlg.dlgType);

                                if (dlg.dlgType.Equals(CARDDLG))
                                {
                                    foreach (CardList tempcard in dlg.dialogCard)
                                    {
                                        tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);

                                        if (tempAttachment != null)
                                        {
                                            commonReply.Attachments.Add(tempAttachment);
                                        }

                                        //2018-04-19:KSO:Carousel 만드는부분 추가
                                        if (tempcard.card_order_no > 1)
                                        {
                                            commonReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                                        }
                                    }
                                }
                                else
                                {
                                    //DButil.HistoryLog("* facebook dlg.dlgId : " + dlg.dlgId);
                                    DButil.HistoryLog("* activity.ChannelId : " + activity.ChannelId);

                                    tempAttachment = dbutil.getAttachmentFromDialog(dlg, activity);
                                    commonReply.Attachments.Add(tempAttachment);
                                }

                                if (commonReply.Attachments.Count > 0)
                                {
                                    SetActivity(commonReply);
                                    replyresult = "H";
                                }
                            }
                        }
                        //SMALLTALK 확인
                        else if (!string.IsNullOrEmpty(smallTalkConfirm))
                        {
                            Debug.WriteLine("smalltalk dialogue-------------");

                            Random rand = new Random();

                            //SMALLTALK 구분
                            string[] smallTalkConfirm_result = smallTalkConfirm.Split('$');

                            int smallTalkConfirmNum = rand.Next(0, smallTalkConfirm_result.Length);

                            Activity smallTalkReply = activity.CreateReply();
                            smallTalkReply.Recipient   = activity.From;
                            smallTalkReply.Type        = "message";
                            smallTalkReply.Attachments = new List <Attachment>();

                            HeroCard plCard = new HeroCard()
                            {
                                Title = "",
                                Text  = smallTalkConfirm_result[smallTalkConfirmNum]
                            };

                            Attachment plAttachment = plCard.ToAttachment();
                            smallTalkReply.Attachments.Add(plAttachment);

                            SetActivity(smallTalkReply);
                            replyresult = "S";
                        }
                        else
                        {
                            Debug.WriteLine("no dialogue-------------");
                            string newUserID = activity.Conversation.Id;
                            //string beforeUserID = "";
                            //string beforeMessgaeText = "";
                            //string messgaeText = "";

                            Activity intentNoneReply = activity.CreateReply();

                            //if (beforeUserID != newUserID)
                            //{
                            //    beforeUserID = newUserID;
                            //    MessagesController.sorryMessageCnt = 0;
                            //}

                            var message = MessagesController.queryStr;
                            //beforeMessgaeText = message.ToString();

                            //Debug.WriteLine("SERARCH MESSAGE : " + message);

                            Activity sorryReply = activity.CreateReply();
                            sorryReply.Recipient   = activity.From;
                            sorryReply.Type        = "message";
                            sorryReply.Attachments = new List <Attachment>();
                            //sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                            List <CardList>   text        = new List <CardList>();
                            List <CardAction> cardButtons = new List <CardAction>();

                            text = db.SelectSorryDialogText("5");
                            for (int i = 0; i < text.Count; i++)
                            {
                                CardAction plButton = new CardAction();
                                plButton = new CardAction()
                                {
                                    Type  = text[i].btn1Type,
                                    Value = text[i].btn1Context,
                                    Title = text[i].btn1Title
                                };
                                cardButtons.Add(plButton);

                                UserHeroCard plCard = new UserHeroCard()
                                {
                                    //Title = text[i].cardTitle,
                                    Text    = text[i].cardText,
                                    Buttons = cardButtons
                                };

                                Attachment plAttachment = plCard.ToAttachment();
                                sorryReply.Attachments.Add(plAttachment);
                            }

                            SetActivity(sorryReply);
                            replyresult = "D";
                        }

                        DateTime endTime = DateTime.Now;

                        int dbResult = db.insertUserQuery();

                        //}
                        //history table insert
                        db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), luisIntent, luisEntities, luisIntentScore, dlgId, replyresult);
                        replyresult = "";
                        luisIntent  = "";
                    }
                }
                catch (Exception e)
                {
                    Debug.Print(e.StackTrace);
                    //int sorryMessageCheck = db.SelectUserQueryErrorMessageCheck(activity.Conversation.Id, MessagesController.chatBotID);



                    Activity sorryReply = activity.CreateReply();

                    sorryReply.Recipient   = activity.From;
                    sorryReply.Type        = "message";
                    sorryReply.Attachments = new List <Attachment>();
                    //sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                    List <CardList>   text        = new List <CardList>();
                    List <CardAction> cardButtons = new List <CardAction>();

                    text = db.SelectSorryDialogText("5");
                    for (int i = 0; i < text.Count; i++)
                    {
                        CardAction plButton = new CardAction();
                        plButton = new CardAction()
                        {
                            Type  = text[i].btn1Type,
                            Value = text[i].btn1Context,
                            Title = text[i].btn1Title
                        };
                        cardButtons.Add(plButton);

                        UserHeroCard plCard = new UserHeroCard()
                        {
                            //Title = text[i].cardTitle,
                            Text    = text[i].cardText,
                            Buttons = cardButtons
                        };

                        Attachment plAttachment = plCard.ToAttachment();
                        sorryReply.Attachments.Add(plAttachment);
                    }

                    SetActivity(sorryReply);

                    DateTime endTime  = DateTime.Now;
                    int      dbResult = db.insertUserQuery();
                    db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), luisIntent, luisEntities, luisIntentScore, "", "E");
                    replyresult = "";
                    //recommendResult = "";
                }
                finally
                {
                    if (reply1.Attachments.Count != 0 || reply1.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply1);
                    }
                    if (reply2.Attachments.Count != 0 || reply2.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply2);
                    }
                    if (reply3.Attachments.Count != 0 || reply3.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply3);
                    }
                    if (reply4.Attachments.Count != 0 || reply4.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply4);
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }
Пример #3
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            string cashOrgMent = "";

            //DbConnect db = new DbConnect();
            //DButil dbutil = new DButil();
            DButil.HistoryLog("db connect !! ");
            //HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            HttpResponseMessage response;

            Activity reply1 = activity.CreateReply();
            Activity reply2 = activity.CreateReply();
            Activity reply3 = activity.CreateReply();
            Activity reply4 = activity.CreateReply();

            // Activity 값 유무 확인하는 익명 메소드
            Action <Activity> SetActivity = (act) =>
            {
                if (!(reply1.Attachments.Count != 0 || reply1.Text != ""))
                {
                    reply1 = act;
                }
                else if (!(reply2.Attachments.Count != 0 || reply2.Text != ""))
                {
                    reply2 = act;
                }
                else if (!(reply3.Attachments.Count != 0 || reply3.Text != ""))
                {
                    reply3 = act;
                }
                else if (!(reply4.Attachments.Count != 0 || reply4.Text != ""))
                {
                    reply4 = act;
                }
                else
                {
                }
            };

            if (activity.Type == ActivityTypes.ConversationUpdate && activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id))
            {
                startTime = DateTime.Now;
                //activity.ChannelId = "facebook";
                //파라메터 호출
                if (LUIS_NM.Count(s => s != null) > 0)
                {
                    //string[] LUIS_NM = new string[10];
                    Array.Clear(LUIS_NM, 0, LUIS_NM.Length);
                }

                if (LUIS_APP_ID.Count(s => s != null) > 0)
                {
                    //string[] LUIS_APP_ID = new string[10];
                    Array.Clear(LUIS_APP_ID, 0, LUIS_APP_ID.Length);
                }
                //Array.Clear(LUIS_APP_ID, 0, 10);
                DButil.HistoryLog("db SelectConfig start !! ");
                List <ConfList> confList = db.SelectConfig();
                DButil.HistoryLog("db SelectConfig end!! ");

                for (int i = 0; i < confList.Count; i++)
                {
                    switch (confList[i].cnfType)
                    {
                    case "LUIS_APP_ID":
                        LUIS_APP_ID[LUIS_APP_ID.Count(s => s != null)] = confList[i].cnfValue;
                        LUIS_NM[LUIS_NM.Count(s => s != null)]         = confList[i].cnfNm;
                        break;

                    case "LUIS_SUBSCRIPTION":
                        LUIS_SUBSCRIPTION = confList[i].cnfValue;
                        break;

                    case "BOT_ID":
                        BOT_ID = confList[i].cnfValue;
                        break;

                    case "MicrosoftAppId":
                        MicrosoftAppId = confList[i].cnfValue;
                        break;

                    case "MicrosoftAppPassword":
                        MicrosoftAppPassword = confList[i].cnfValue;
                        break;

                    case "LUIS_SCORE_LIMIT":
                        LUIS_SCORE_LIMIT = confList[i].cnfValue;
                        break;

                    case "LUIS_TIME_LIMIT":
                        LUIS_TIME_LIMIT = Convert.ToInt32(confList[i].cnfValue);
                        break;

                    default:     //미 정의 레코드
                        Debug.WriteLine("*conf type : " + confList[i].cnfType + "* conf value : " + confList[i].cnfValue);
                        DButil.HistoryLog("*conf type : " + confList[i].cnfType + "* conf value : " + confList[i].cnfValue);
                        break;
                    }
                }

                Debug.WriteLine("* DB conn : " + activity.Type);
                DButil.HistoryLog("* DB conn : " + activity.Type);

                //초기 다이얼로그 호출
                DButil.HistoryLog("초기 인사말 시작 ");
                List <DialogList> dlg       = db.SelectInitDialog(activity.ChannelId);
                ConnectorClient   connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                foreach (DialogList dialogs in dlg)
                {
                    Activity initReply = activity.CreateReply();
                    initReply.Recipient   = activity.From;
                    initReply.Type        = "message";
                    initReply.Attachments = new List <Attachment>();
                    //initReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                    Attachment tempAttachment;

                    if (dialogs.dlgType.Equals(CARDDLG))
                    {
                        foreach (CardList tempcard in dialogs.dialogCard)
                        {
                            tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);
                            initReply.Attachments.Add(tempAttachment);
                        }
                    }
                    else
                    {
                        if (activity.ChannelId.Equals("facebook") && string.IsNullOrEmpty(dialogs.cardTitle) && dialogs.dlgType.Equals(TEXTDLG))
                        {
                            Activity reply_facebook = activity.CreateReply();
                            reply_facebook.Recipient = activity.From;
                            reply_facebook.Type      = "message";
                            DButil.HistoryLog("facebook  card Text : " + dialogs.cardText);
                            reply_facebook.Text = dialogs.cardText;
                            var reply_ment_facebook = connector.Conversations.SendToConversationAsync(reply_facebook);
                            //SetActivity(reply_facebook);
                        }
                        else
                        {
                            tempAttachment = dbutil.getAttachmentFromDialog(dialogs, activity);
                            initReply.Attachments.Add(tempAttachment);
                        }
                    }
                    DButil.HistoryLog("초기 인사말 종료 ");
                    await connector.Conversations.SendToConversationAsync(initReply);
                }

                //현재위치사용승인 테스트
                //Activity replyLocation = activity.CreateReply();
                //replyLocation.Recipient = activity.From;
                //replyLocation.Type = "message";
                //replyLocation.Attachments = new List<Attachment>();
                //replyLocation.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                //replyLocation.Attachments.Add(
                //    GetHeroCard_facebookMore(
                //    "", "",
                //    "현재 위치 사용 승인",
                //    new CardAction(ActionTypes.ImBack, "현재 위치 사용 승인", value: MessagesController.queryStr))
                //);
                //await connector.Conversations.SendToConversationAsync(replyLocation);

                DateTime endTime = DateTime.Now;
                Debug.WriteLine("프로그램 수행시간 : {0}/ms", ((endTime - startTime).Milliseconds));
                Debug.WriteLine("* activity.Type : " + activity.Type);
                Debug.WriteLine("* activity.Recipient.Id : " + activity.Recipient.Id);
                Debug.WriteLine("* activity.ServiceUrl : " + activity.ServiceUrl);

                DButil.HistoryLog("* activity.Type : " + activity.ChannelData);
                DButil.HistoryLog("* activity.Recipient.Id : " + activity.Recipient.Id);
                DButil.HistoryLog("* activity.ServiceUrl : " + activity.ServiceUrl);
            }
            else if (activity.Type == ActivityTypes.Message)
            {
                //activity.ChannelId = "facebook";
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                try
                {
                    Debug.WriteLine("* activity.Type == ActivityTypes.Message ");
                    channelID = activity.ChannelId;
                    string orgMent = activity.Text;

                    //현재위치사용승인
                    if (orgMent.Contains("current location") || orgMent.Equals("현재위치사용승인"))
                    {
                        if (!orgMent.Contains(':'))
                        {
                            //첫번쨰 메세지 출력 x
                            response = Request.CreateResponse(HttpStatusCode.OK);
                            return(response);
                        }
                        else
                        {
                            //위도경도에 따른 값 출력
                            try
                            {
                                string location = orgMent.Replace("current location:", "");
                                //테스트용
                                //string location = "129.0929788:35.2686635";
                                string[] location_result = location.Split(':');
                                //regionStr = db.LocationValue(location_result[1], location_result[2]);
                                DButil.HistoryLog("*regionStr : " + location_result[0] + " " + location_result[1]);
                                Debug.WriteLine("*regionStr : " + location_result[0] + " " + location_result[1]);
                                DButil.mapSave(location_result[0], location_result[1]);
                                Activity reply_brach = activity.CreateReply();
                                reply_brach.Recipient        = activity.From;
                                reply_brach.Type             = "message";
                                reply_brach.Attachments      = new List <Attachment>();
                                reply_brach.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                                reply_brach.Attachments.Add(
                                    DButil.GetHeroCard_Map(
                                        "타이호인스트",
                                        "연락처",
                                        "주소",
                                        new CardImage(url: "https://tiizchatbotv3.azurewebsites.net/image/map/" + location_result[1] + "," + location_result[0] + ".png"),
                                        new CardAction(ActionTypes.OpenUrl, "타이호인스트", value: "http://www.taihoinst.com/"),
                                        location_result[1],
                                        location_result[0])
                                    );
                                var reply_brach1 = await connector.Conversations.SendToConversationAsync(reply_brach);

                                response = Request.CreateResponse(HttpStatusCode.OK);
                                return(response);
                            }
                            catch
                            {
                                queryStr = "서울 시승센터";
                            }
                        }
                    }

                    apiFlag = "COMMON";

                    //대화 시작 시간
                    startTime = DateTime.Now;
                    long unixTime = ((DateTimeOffset)startTime).ToUnixTimeSeconds();

                    DButil.HistoryLog("orgMent : " + orgMent);
                    //금칙어 체크
                    CardList bannedMsg = db.BannedChk(orgMent);
                    Debug.WriteLine("* bannedMsg : " + bannedMsg.cardText);//해당금칙어에 대한 답변

                    //  QnA Maker 확인 - START
                    string qnaOrgMent     = orgMent.Replace("'", "\""); // singlequote problem..
                    string qnAMakerAnswer = dbutil.GetQnAMaker(qnaOrgMent);

                    if (bannedMsg.cardText != null)
                    {
                        Activity reply_ment = activity.CreateReply();
                        reply_ment.Recipient = activity.From;
                        reply_ment.Type      = "message";
                        reply_ment.Text      = bannedMsg.cardText;

                        var reply_ment_info = await connector.Conversations.SendToConversationAsync(reply_ment);

                        response = Request.CreateResponse(HttpStatusCode.OK);
                        return(response);
                    }

                    else if (!qnAMakerAnswer.Contains("No good match"))
                    {
                        Debug.WriteLine("* qnaOrgMent : " + qnaOrgMent);
                        Debug.WriteLine("* qnAMakerAnswer : " + qnAMakerAnswer);
                        Activity qnAMakerReply = activity.CreateReply();

                        qnAMakerReply.Recipient   = activity.From;
                        qnAMakerReply.Type        = "message";
                        qnAMakerReply.Attachments = new List <Attachment>();

                        List <CardList> text = new List <CardList>();

                        UserHeroCard plCard = new UserHeroCard()
                        {
                            //Title = "QnA",
                            Text    = qnAMakerAnswer,
                            Gesture = 9
                        };

                        Attachment plAttachment = plCard.ToAttachment();
                        qnAMakerReply.Attachments.Add(plAttachment);

                        SetActivity(qnAMakerReply);

                        replyresult = "Q";
                        luisIntent  = "QnA";
                    }

                    else
                    {
                        queryStr = orgMent;
                        //인텐트 엔티티 검출
                        //캐시 체크
                        cashOrgMent = Regex.Replace(orgMent, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);
                        cacheList   = db.CacheChk(cashOrgMent.Replace(" ", ""));                   // 캐시 체크 (TBL_QUERY_ANALYSIS_RESULT 조회..)

                        //캐시에 없을 경우
                        if (cacheList.luisIntent == null || cacheList.luisEntities == null)
                        {
                            DButil.HistoryLog("cache none : " + orgMent);
                            Debug.WriteLine("cache none : " + orgMent);
                            //루이스 체크(intent를 루이스를 통해서 가져옴)
                            //cacheList.luisId = dbutil.GetMultiLUIS(orgMent);
                            //Debug.WriteLine("cacheList.luisId : " + cacheList.luisId);

                            cacheList.luisIntent = dbutil.GetMultiLUIS(orgMent);
                            Debug.WriteLine("cacheList.luisIntent : " + cacheList.luisIntent);
                            //Debug.WriteLine("cacheList.luisEntitiesValue : " + cacheList.luisEntitiesValue);
                            cacheList = db.CacheDataFromIntent(cacheList.luisIntent);
                        }

                        luisId          = cacheList.luisId;
                        luisIntent      = cacheList.luisIntent;
                        luisEntities    = cacheList.luisEntities;
                        luisIntentScore = cacheList.luisScore;

                        DButil.HistoryLog("luisId : " + luisId);
                        DButil.HistoryLog("luisIntent : " + luisIntent);
                        DButil.HistoryLog("luisEntities : " + luisEntities);

                        String fullentity = db.SearchCommonEntities;
                        DButil.HistoryLog("fullentity : " + fullentity);
                        if (apiFlag.Equals("COMMON") && luisIntent != null) //MTC 관련 수정(&& luisIntent != null 추가)
                        {
                            relationList = db.DefineTypeChkSpare(cacheList.luisIntent, cacheList.luisEntities);
                        }
                        else
                        {
                            relationList = null;
                        }
                        if (relationList != null)
                        //if (relationList.Count > 0)
                        {
                            DButil.HistoryLog("relationList 조건 in ");
                            if (relationList.Count > 0 && relationList[0].dlgApiDefine != null)
                            {
                                if (relationList[0].dlgApiDefine.Equals("api testdrive"))
                                {
                                    apiFlag = "TESTDRIVE";
                                }
                                else if (relationList[0].dlgApiDefine.Equals("api quot"))
                                {
                                    apiFlag = "QUOT";
                                }
                                else if (relationList[0].dlgApiDefine.Equals("api recommend"))
                                {
                                    apiFlag = "RECOMMEND";
                                }
                                else if (relationList[0].dlgApiDefine.Equals("D"))
                                {
                                    apiFlag = "COMMON";
                                }
                                DButil.HistoryLog("relationList[0].dlgApiDefine : " + relationList[0].dlgApiDefine);
                            }
                        }
                        else
                        {
                            if (MessagesController.cacheList.luisIntent == null || apiFlag.Equals("COMMON"))
                            {
                                apiFlag = "";
                            }
                            else if (MessagesController.cacheList.luisId.Equals("TIIZChatBotV3_luis_01") && MessagesController.cacheList.luisIntent.Contains("quot"))
                            {
                                apiFlag = "QUOT";
                            }
                            DButil.HistoryLog("apiFlag : " + apiFlag);
                        }


                        if (apiFlag.Equals("COMMON") && relationList.Count > 0)
                        {
                            //context.Call(new CommonDialog("", MessagesController.queryStr), this.ResumeAfterOptionDialog);
                            dlgId = "";
                            for (int m = 0; m < MessagesController.relationList.Count; m++)
                            {
                                DialogList dlg = db.SelectDialog(MessagesController.relationList[m].dlgId);
                                dlgId += Convert.ToString(dlg.dlgId) + ",";
                                Activity   commonReply    = activity.CreateReply();
                                Attachment tempAttachment = new Attachment();
                                DButil.HistoryLog("dlg.dlgType : " + dlg.dlgType);

                                if (dlg.dlgType.Equals(CARDDLG))
                                {
                                    foreach (CardList tempcard in dlg.dialogCard)
                                    {
                                        DButil.HistoryLog("tempcard.card_order_no : " + tempcard.card_order_no);
                                        if (conversationhistory.facebookPageCount > 0)
                                        {
                                            if (tempcard.card_order_no > (MAXFACEBOOKCARDS * facebookpagecount) && tempcard.card_order_no <= (MAXFACEBOOKCARDS * (facebookpagecount + 1)))
                                            {
                                                tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);
                                            }
                                            else if (tempcard.card_order_no > (MAXFACEBOOKCARDS * (facebookpagecount + 1)))
                                            {
                                                fbLeftCardCnt++;
                                                tempAttachment = null;
                                            }
                                            else
                                            {
                                                fbLeftCardCnt  = 0;
                                                tempAttachment = null;
                                            }
                                        }
                                        else if (activity.ChannelId.Equals("facebook"))
                                        {
                                            DButil.HistoryLog("facebook tempcard.card_order_no : " + tempcard.card_order_no);
                                            if (tempcard.card_order_no <= MAXFACEBOOKCARDS && fbLeftCardCnt == 0)
                                            {
                                                tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);
                                            }
                                            else
                                            {
                                                fbLeftCardCnt++;
                                                tempAttachment = null;
                                            }
                                        }
                                        else
                                        {
                                            tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);
                                        }



                                        if (tempAttachment != null)
                                        {
                                            commonReply.Attachments.Add(tempAttachment);
                                        }

                                        //2018-04-19:KSO:Carousel 만드는부분 추가
                                        if (tempcard.card_order_no > 1)
                                        {
                                            commonReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                                        }
                                    }
                                }
                                else
                                {
                                    //DButil.HistoryLog("* facebook dlg.dlgId : " + dlg.dlgId);
                                    DButil.HistoryLog("* activity.ChannelId : " + activity.ChannelId);


                                    if (activity.ChannelId.Equals("facebook") && string.IsNullOrEmpty(dlg.cardTitle) && dlg.dlgType.Equals(TEXTDLG))
                                    {
                                        commonReply.Recipient = activity.From;
                                        commonReply.Type      = "message";
                                        DButil.HistoryLog("facebook card Text : " + dlg.cardText);
                                        commonReply.Text = dlg.cardText;
                                    }
                                    else
                                    {
                                        tempAttachment = dbutil.getAttachmentFromDialog(dlg, activity);
                                        commonReply.Attachments.Add(tempAttachment);
                                    }
                                }

                                if (commonReply.Attachments.Count > 0)
                                {
                                    SetActivity(commonReply);
                                    conversationhistory.commonBeforeQustion = orgMent;
                                    replyresult = "H";
                                }
                            }
                        }
                        else
                        {
                            Debug.WriteLine("no dialogue-------------");
                            Debug.WriteLine("luisIntent : " + luisIntent);
                            string newUserID         = activity.Conversation.Id;
                            string beforeUserID      = "";
                            string beforeMessgaeText = "";
                            //string messgaeText = "";

                            Activity intentNoneReply = activity.CreateReply();

                            if (beforeUserID != newUserID)
                            {
                                beforeUserID = newUserID;
                                MessagesController.sorryMessageCnt = 0;
                            }

                            var message = MessagesController.queryStr;
                            beforeMessgaeText = message.ToString();

                            Debug.WriteLine("SERARCH MESSAGE : " + message);

                            Activity sorryReply = activity.CreateReply();
                            sorryReply.Recipient        = activity.From;
                            sorryReply.Type             = "message";
                            sorryReply.Attachments      = new List <Attachment>();
                            sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                            List <TextList> text = new List <TextList>();
                            text = db.SelectSorryDialogText("5");
                            for (int i = 0; i < text.Count; i++)
                            {
                                HeroCard plCard = new HeroCard()
                                {
                                    Title = text[i].cardTitle,
                                    Text  = text[i].cardText
                                };

                                Attachment plAttachment = plCard.ToAttachment();
                                sorryReply.Attachments.Add(plAttachment);
                            }

                            SetActivity(sorryReply);
                            replyresult = "D";
                        }

                        DateTime endTime = DateTime.Now;
                        //analysis table insert
                        //if (rc != null)
                        //{
                        int dbResult = db.insertUserQuery();

                        //}
                        //history table insert
                        db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), luisIntent, luisEntities, luisIntentScore, dlgId);
                        replyresult     = "";
                        recommendResult = "";
                    }
                }
                catch (Exception e)
                {
                    Debug.Print(e.StackTrace);
                    int sorryMessageCheck = db.SelectUserQueryErrorMessageCheck(activity.Conversation.Id, MessagesController.chatBotID);

                    ++MessagesController.sorryMessageCnt;

                    Activity sorryReply = activity.CreateReply();

                    sorryReply.Recipient   = activity.From;
                    sorryReply.Type        = "message";
                    sorryReply.Attachments = new List <Attachment>();
                    //sorryReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                    List <TextList> text = new List <TextList>();
                    if (sorryMessageCnt == 1)
                    {
                        text = db.SelectSorryDialogText("5");
                    }
                    else
                    {
                        text = db.SelectSorryDialogText("6");
                    }

                    for (int i = 0; i < text.Count; i++)
                    {
                        HeroCard plCard = new HeroCard()
                        {
                            Title = text[i].cardTitle,
                            Text  = text[i].cardText
                        };

                        Attachment plAttachment = plCard.ToAttachment();
                        sorryReply.Attachments.Add(plAttachment);
                    }

                    SetActivity(sorryReply);

                    DateTime endTime  = DateTime.Now;
                    int      dbResult = db.insertUserQuery();
                    db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), luisIntent, luisEntities, luisIntentScore, "");
                    replyresult     = "";
                    recommendResult = "";
                }
                finally
                {
                    if (reply1.Attachments.Count != 0 || reply1.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply1);
                    }
                    if (reply2.Attachments.Count != 0 || reply2.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply2);
                    }
                    if (reply3.Attachments.Count != 0 || reply3.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply3);
                    }
                    if (reply4.Attachments.Count != 0 || reply4.Text != "")
                    {
                        await connector.Conversations.SendToConversationAsync(reply4);
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }