Exemplo n.º 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!! ");

                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 "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))
                    {
                        Debug.WriteLine("* CARDDLG");
                        foreach (CardList tempcard in dialogs.dialogCard)
                        {
                            tempAttachment = dbutil.getAttachmentFromDialog(tempcard, activity);
                            initReply.Attachments.Add(tempAttachment);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("* NOT CARDDLG");
                        if (activity.ChannelId.Equals("facebook") && string.IsNullOrEmpty(dialogs.cardTitle) && dialogs.dlgType.Equals(TEXTDLG))
                        {
                            Debug.WriteLine("* NOT CARDDLG - 1");
                            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
                        {
                            Debug.WriteLine("* NOT CARDDLG - 2");
                            //tempAttachment = dbutil.getAttachmentFromDialog(dialogs, activity);

                            HeroCard plCard = new UserHeroCard()
                            {
                                Title         = "Welcome",
                                Text          = "반갑습니다. 인천공항공사 챗봇입니다.",
                                Images        = null,
                                Buttons       = null,
                                Card_division = "",
                                Card_value    = ""
                            };
                            tempAttachment = plCard.ToAttachment();

                            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";
                startTime = DateTime.Now;
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                try
                {
                    Debug.WriteLine("* activity.Type == ActivityTypes.Message ");
                    channelID = activity.ChannelId;
                    string orgMent = activity.Text;

                    //
                    string strDetectLang = DetectLang(orgMent);
                    Debug.WriteLine("* strDetectLang : " + strDetectLang);

                    string qnaMakerRes = "";
                    qnaMakerRes = GetQnaMakerResult(orgMent, strDetectLang);
                    Debug.WriteLine("*** strDetectLang : " + strDetectLang + " | qnaMakerRes : " + qnaMakerRes);

                    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);
                    }
                    else if (!qnaMakerRes.Equals(""))
                    {
                        string         strReplyText = "Sorry";
                        QnAMakerResult responseQna;
                        responseQna = JsonConvert.DeserializeObject <QnAMakerResult>(qnaMakerRes);

                        if (!responseQna.Score.Equals(0))
                        {
                            //Convert.ToInt32(responseQna.Score);
                            DateTime endTime = DateTime.Now;
                            Debug.WriteLine("프로그램 수행시간 : {0}/ms", ((endTime - startTime).Milliseconds));
                            strReplyText = responseQna.Answer + " || score: " + Convert.ToInt32(responseQna.Score) + "p, " + ((endTime - startTime).Milliseconds) + "/ms";

                            DButil.QnALog(orgMent + " |*| " + responseQna.Answer + " |*| " + Convert.ToInt32(responseQna.Score) + "p," + ((endTime - startTime).Milliseconds) + "/ms");

                            string logQuestion = orgMent.Replace(" ", "");
                            string logAnswer = responseQna.Answer.Replace(" ", "").Replace(Environment.NewLine, "");
                            string strLogQuestion, strLogAnswer;
                            if (logQuestion.Length > 20)
                            {
                                strLogQuestion = logQuestion.Substring(0, 20) + "...";
                            }
                            else
                            {
                                strLogQuestion = logQuestion;
                            }

                            if (logAnswer.Length > 30)
                            {
                                strLogAnswer = logAnswer.Substring(0, 30) + "...";
                            }
                            else
                            {
                                strLogAnswer = logAnswer;
                            }

                            DButil.QnALogSub(Convert.ToInt32(responseQna.Score) + "p," + ((endTime - startTime).Milliseconds) + "/ms |*| " + strLogQuestion + " |*| " + strLogAnswer);
                        }

                        Activity reply_ment = activity.CreateReply();
                        reply_ment.Recipient = activity.From;
                        reply_ment.Type      = "message";
                        //reply_ment.Text = qnaMakerRes;
                        reply_ment.Text = strReplyText;

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

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


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

                        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;

                        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("cjchat_luis_01") && MessagesController.cacheList.luisIntent.Contains("quot"))
                            {
                                apiFlag = "QUOT";
                            }
                        }


                        if (apiFlag.Equals("COMMON") && relationList.Count > 0)
                        {
                            //context.Call(new CommonDialog("", MessagesController.queryStr), this.ResumeAfterOptionDialog);

                            for (int m = 0; m < MessagesController.relationList.Count; m++)
                            {
                                DialogList dlg            = db.SelectDialog(MessagesController.relationList[m].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 (tempAttachment != null)
                                        {
                                            commonReply.Attachments.Add(tempAttachment);
                                        }
                                    }
                                }
                                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);
                            sorryflag = true;
                            //네이버 기사 검색
                            if (sorryflag)
                            {
                                Debug.WriteLine("sorryflag : true");
                                //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
                                    };
                                    Debug.WriteLine("sorryflag : true | 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);
        }
Exemplo n.º 2
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
                {
                }
            };

            //DButil.HistoryLog("activity.Recipient.Name : " + activity.Recipient.Name);
            //DButil.HistoryLog("activity.Name : " + activity.Name);

            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 "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);
                    }
                    else
                    {
                        Debug.WriteLine("* NO bannedMsg !");
                        queryStr = orgMent;
                        //인텐트 엔티티 검출
                        //캐시 체크
                        cashOrgMent = Regex.Replace(orgMent, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);
                        cacheList   = db.CacheChk(cashOrgMent.Replace(" ", ""));                   // 캐시 체크


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

                        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;

                        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
                        {
                            DButil.HistoryLog("relationList is not NULL");
                            if (MessagesController.cacheList.luisIntent == null || apiFlag.Equals("COMMON"))
                            {
                                apiFlag = "";
                            }
                            else if (MessagesController.cacheList.luisId.Equals("kona_luis_01") && MessagesController.cacheList.luisIntent.Contains("quot"))
                            {
                                apiFlag = "QUOT";
                            }
                        }


                        if (apiFlag.Equals("COMMON") && relationList.Count > 0)
                        {
                            DButil.HistoryLog("apiFlag : COMMON | relationList.Count : " + relationList.Count);
                            //context.Call(new CommonDialog("", MessagesController.queryStr), this.ResumeAfterOptionDialog);
                            String beforeMent = "";
                            facebookpagecount = 1;
                            //int fbLeftCardCnt = 0;

                            if (conversationhistory.commonBeforeQustion != null && conversationhistory.commonBeforeQustion != "")
                            {
                                DButil.HistoryLog(fbLeftCardCnt + "{fbLeftCardCnt} :: conversationhistory.commonBeforeQustion : " + conversationhistory.commonBeforeQustion);
                                if (conversationhistory.commonBeforeQustion.Equals(orgMent) && activity.ChannelId.Equals("facebook") && fbLeftCardCnt > 0)
                                {
                                    DButil.HistoryLog("beforeMent : " + beforeMent);
                                    conversationhistory.facebookPageCount++;
                                }
                                else
                                {
                                    conversationhistory.facebookPageCount = 0;
                                    fbLeftCardCnt = 0;
                                }
                            }


                            DButil.HistoryLog("* MessagesController.relationList.Count : " + MessagesController.relationList.Count);
                            for (int m = 0; m < MessagesController.relationList.Count; m++)
                            {
                                DialogList dlg            = db.SelectDialog(MessagesController.relationList[m].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);
                                        }
                                    }
                                }
                                else
                                {
                                    DButil.HistoryLog("* facebook dlg.dlgId : " + dlg.dlgId);
                                    DButil.HistoryLog("* activity.ChannelId : " + activity.ChannelId);
                                    DButil.HistoryLog("* dlg.dlgId : " + dlg.dlgId + " | dlg.cardText : " + dlg.cardText);

                                    if (dlg.dlgId.Equals(24)) //  주문내역 dialog 일시..
                                    {
                                        DButil.HistoryLog("*** activity.Conversation.Id : " + activity.Conversation.Id + " | dlg.cardText : " + dlg.cardText + " | fullentity : " + fullentity);

                                        string[] strComment    = new string[3];
                                        string   optionComment = "";

                                        strComment[0] = db.SelectUserHistoryComment(activity.Conversation.Id, "selectDiet");
                                        strComment[1] = db.SelectUserHistoryComment(activity.Conversation.Id, "selectDelievery");
                                        //strComment[2] = db.SelectUserHistoryComment(activity.Conversation.Id, "order");
                                        DButil.HistoryLog("*** strComment[0] : " + strComment[0] + " | strComment[1] : " + strComment[1] + " | strComment[2] : " + strComment[2]);

                                        //optionComment = strComment[0] + "/" + strComment[1] + "/" + strComment[2];
                                        optionComment = strComment[0] + "/" + strComment[1] + "/" + fullentity;
                                        dlg.cardText  = dlg.cardText.Replace("#OPTIONS", optionComment);
                                    }

                                    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)
                                {
                                    DButil.HistoryLog("* commonReply.Attachments.Count : " + commonReply.Attachments.Count);

                                    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);
                         *  //네이버 기사 검색
                         *  if ((message != null) && message.Trim().Length > 0)
                         *  {
                         *      //Naver Search API
                         *
                         *      string url = "https://openapi.naver.com/v1/search/news.json?query=" + message + "&display=10&start=1&sort=sim"; //news JSON result
                         *      //string blogUrl = "https://openapi.naver.com/v1/search/blog.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //search JSON result
                         *      //string cafeUrl = "https://openapi.naver.com/v1/search/cafearticle.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //cafe JSON result
                         *      //string url = "https://openapi.naver.com/v1/search/blog.xml?query=" + query; //blog XML result
                         *      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                         *      request.Headers.Add("X-Naver-Client-Id", "Y536Z1ZMNv93Oej6TrkF");
                         *      request.Headers.Add("X-Naver-Client-Secret", "cPHOFK6JYY");
                         *      HttpWebResponse httpwebresponse = (HttpWebResponse)request.GetResponse();
                         *      string status = httpwebresponse.StatusCode.ToString();
                         *      if (status == "OK")
                         *      {
                         *          Stream stream = httpwebresponse.GetResponseStream();
                         *          StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                         *          string text = reader.ReadToEnd();
                         *
                         *          RootObject serarchList = JsonConvert.DeserializeObject<RootObject>(text);
                         *
                         *          Debug.WriteLine("serarchList : " + serarchList);
                         *          //description
                         *
                         *          if (serarchList.display == 1)
                         *          {
                         *              //Debug.WriteLine("SERARCH : " + Regex.Replace(serarchList.items[0].title, @"[^<:-:>-<b>-</b>]", "", RegexOptions.Singleline));
                         *
                         *              if (serarchList.items[0].title.Contains("코나"))
                         *              {
                         *                  //Only One item
                         *                  List<CardImage> cardImages = new List<CardImage>();
                         *                  CardImage img = new CardImage();
                         *                  img.Url = "";
                         *                  cardImages.Add(img);
                         *
                         *                  string searchTitle = "";
                         *                  string searchText = "";
                         *
                         *                  searchTitle = serarchList.items[0].title;
                         *                  searchText = serarchList.items[0].description;
                         *
                         *
                         *
                         *                  if (activity.ChannelId == "facebook")
                         *                  {
                         *                      searchTitle = Regex.Replace(searchTitle, @"[<][a-z|A-Z|/](.|)*?[>]", "", RegexOptions.Singleline).Replace("\n", "").Replace("<:", "").Replace(":>", "");
                         *                      searchText = Regex.Replace(searchText, @"[<][a-z|A-Z|/](.|)*?[>]", "", RegexOptions.Singleline).Replace("\n", "").Replace("<:", "").Replace(":>", "");
                         *                  }
                         *
                         *
                         *                  LinkHeroCard card = new LinkHeroCard()
                         *                  {
                         *                      Title = searchTitle,
                         *                      Subtitle = null,
                         *                      Text = searchText,
                         *                      Images = cardImages,
                         *                      Buttons = null,
                         *                      Link = Regex.Replace(serarchList.items[0].link, "amp;", "")
                         *                  };
                         *                  var attachment = card.ToAttachment();
                         *
                         *                  intentNoneReply.Attachments = new List<Attachment>();
                         *                  intentNoneReply.Attachments.Add(attachment);
                         *              }
                         *          }
                         *          else
                         *          {
                         *              //intentNoneReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                         *              intentNoneReply.Attachments = new List<Attachment>();
                         *              for (int i = 0; i < serarchList.display; i++)
                         *              {
                         *                  string searchTitle = "";
                         *                  string searchText = "";
                         *
                         *                  searchTitle = serarchList.items[i].title;
                         *                  searchText = serarchList.items[i].description;
                         *
                         *                  if (activity.ChannelId == "facebook")
                         *                  {
                         *                      searchTitle = Regex.Replace(searchTitle, @"[<][a-z|A-Z|/](.|)*?[>]", "", RegexOptions.Singleline).Replace("\n", "").Replace("<:", "").Replace(":>", "");
                         *                      searchText = Regex.Replace(searchText, @"[<][a-z|A-Z|/](.|)*?[>]", "", RegexOptions.Singleline).Replace("\n", "").Replace("<:", "").Replace(":>", "");
                         *                  }
                         *
                         *                  if (serarchList.items[i].title.Contains("코나"))
                         *                  {
                         *                      List<CardImage> cardImages = new List<CardImage>();
                         *                      CardImage img = new CardImage();
                         *                      img.Url = "";
                         *                      cardImages.Add(img);
                         *
                         *                      List<CardAction> cardButtons = new List<CardAction>();
                         *                      CardAction[] plButton = new CardAction[1];
                         *                      plButton[0] = new CardAction()
                         *                      {
                         *                          Value = Regex.Replace(serarchList.items[i].link, "amp;", ""),
                         *                          Type = "openUrl",
                         *                          Title = "기사 바로가기"
                         *                      };
                         *                      cardButtons = new List<CardAction>(plButton);
                         *
                         *                      if (activity.ChannelId == "facebook")
                         *                      {
                         *                          LinkHeroCard card = new LinkHeroCard()
                         *                          {
                         *                              Title = searchTitle,
                         *                              Subtitle = null,
                         *                              Text = searchText,
                         *                              Images = cardImages,
                         *                              Buttons = cardButtons,
                         *                              Link = null
                         *                          };
                         *                          var attachment = card.ToAttachment();
                         *                          intentNoneReply.Attachments.Add(attachment);
                         *                      }
                         *                      else
                         *                      {
                         *                          LinkHeroCard card = new LinkHeroCard()
                         *                          {
                         *                              Title = searchTitle,
                         *                              Subtitle = null,
                         *                              Text = searchText,
                         *                              Images = cardImages,
                         *                              Buttons = null,
                         *                              Link = Regex.Replace(serarchList.items[i].link, "amp;", "")
                         *                          };
                         *                          var attachment = card.ToAttachment();
                         *                          intentNoneReply.Attachments.Add(attachment);
                         *                      }
                         *                  }
                         *              }
                         *          }
                         *          //await connector.Conversations.SendToConversationAsync(intentNoneReply);
                         *          //replyresult = "S";
                         *
                         *          if (intentNoneReply.Attachments.Count == 0)
                         *          {
                         *              sorryflag = true;
                         *          }
                         *          else
                         *          {
                         *              //await connector.Conversations.SendToConversationAsync(intentNoneReply);
                         *              SetActivity(intentNoneReply);
                         *              replyresult = "S";
                         *          }
                         *
                         *      }
                         *      else
                         *      {
                         *          //System.Diagnostics.Debug.WriteLine("Error 발생=" + status);
                         *          sorryflag = true;
                         *      }
                         *  }
                         *  else
                         *  {
                         *      sorryflag = true;
                         *  }
                         *  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

                        Debug.WriteLine("* insertHistory | Conversation.Id : " + activity.Conversation.Id + "ChannelId : " + activity.ChannelId);

                        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
                {
                    // facebook 환경에서 text만 있는 멘트를 제외하고 carousel 등록
                    if (!(activity.ChannelId == "facebook" && reply1.Text != ""))
                    {
                        reply1.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    }
                    if (!(activity.ChannelId == "facebook" && reply2.Text != ""))
                    {
                        reply2.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    }
                    if (!(activity.ChannelId == "facebook" && reply3.Text != ""))
                    {
                        reply3.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    }
                    if (!(activity.ChannelId == "facebook" && reply4.Text != ""))
                    {
                        reply4.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    }



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

                    //페이스북에서 남은 카드가 있는경우
                    if (activity.ChannelId.Equals("facebook") && fbLeftCardCnt > 0)
                    {
                        Activity replyToFBConversation = activity.CreateReply();
                        replyToFBConversation.Recipient        = activity.From;
                        replyToFBConversation.Type             = "message";
                        replyToFBConversation.Attachments      = new List <Attachment>();
                        replyToFBConversation.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                        replyToFBConversation.Attachments.Add(
                            GetHeroCard_facebookMore(
                                "", "",
                                fbLeftCardCnt + "개의 컨테츠가 더 있습니다.",
                                new CardAction(ActionTypes.ImBack, "더 보기", value: MessagesController.queryStr))
                            );
                        await connector.Conversations.SendToConversationAsync(replyToFBConversation);

                        replyToFBConversation.Attachments.Clear();
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }
Exemplo n.º 3
0
        private static String GetQnaMakerResult(string strMsg, string strLang)
        {
            string responseString = string.Empty;
            string resAnswer      = "";

            var knowledgebaseId         = "911ff048-cd54-45bb-ade2-cf425b7a1bb5"; // Use knowledge base id created.
            var qnamakerSubscriptionKey = "6c22182afe1d4b5fbbc85f072d9df773";     //Use subscription key assigned to you.

            if (strLang.Equals("ko"))
            {
                knowledgebaseId = "911ff048-cd54-45bb-ade2-cf425b7a1bb5"; // Use knowledge base id created.
            }
            else if (strLang.Equals("en"))
            {
                knowledgebaseId = "022f23ce-fa79-4a96-97e9-cf81922c4334"; // Use knowledge base id created.
            }
            else if (strLang.Equals("zh-CHS"))
            {
                knowledgebaseId = "224aa759-1019-4d91-98e8-d54f60dad784"; // Use knowledge base id created.
            }
            else if (strLang.Equals("ja"))
            {
                knowledgebaseId = "2e7aeef6-0817-48f1-bf38-d4c33ab3b632"; // Use knowledge base id created.
            }

            //Build the URI
            Uri qnamakerUriBase = new Uri("https://westus.api.cognitive.microsoft.com/qnamaker/v1.0");
            var builder         = new UriBuilder($"{qnamakerUriBase}/knowledgebases/{knowledgebaseId}/generateAnswer");

            //Add the question as part of the body
            var postBody = $"{{\"question\": \"{strMsg}\"}}";

            Debug.WriteLine("* builder : " + builder + " | builder.Uri : " + builder.Uri);
            Debug.WriteLine("* postBody : " + postBody);

            //Send the POST request
            using (WebClient client = new WebClient())
            {
                //Set the encoding to UTF8
                client.Encoding = System.Text.Encoding.UTF8;

                //Add the subscription key header
                client.Headers.Add("Ocp-Apim-Subscription-Key", qnamakerSubscriptionKey);
                client.Headers.Add("Content-Type", "application/json");
                responseString = client.UploadString(builder.Uri, postBody);
                Debug.WriteLine("*** orgMent : " + strMsg + " | responseString : " + responseString);
                DButil.HistoryLog("*** orgMent : " + strMsg + " | responseString : " + responseString);
            }

            /*
             * QnAMakerResult responseQna;
             * try
             * {
             *  responseQna = JsonConvert.DeserializeObject<QnAMakerResult>(responseString);
             *  Debug.WriteLine("*** answer : " + responseQna.Answer + " | score : " + responseQna.Score);
             *  resAnswer = responseQna.Answer;
             * }
             * catch
             * {
             *  throw new Exception("Unable to deserialize QnA Maker response string.");
             * }
             * return resAnswer;
             */

            return(responseString);
        }
Exemplo n.º 4
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 "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);
                    }
                    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, cacheList.luisEntitiesValue);
                        }
                        ///////////////////////////////////////////////////////////////////////////////////////////////

                        luisId       = cacheList.luisId;
                        luisIntent   = cacheList.luisIntent;
                        luisEntities = cacheList.luisEntities;

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

                        ///////////////////////////////////////////////////////////////////////
                        //물량정보조회3의 entitites를 가격으로 임의 지정
                        //if (luisIntent.Equals("물량정보조회2") || luisIntent.Equals("물량정보조회3") || luisIntent.Equals("물량정보조회4") || luisIntent.Equals("물량정보조회5"))
                        //{
                        //    cacheList.luisEntities = "가격";  //임시설정
                        //}
                        //if (luisIntent.Equals("문자안내재전송"))
                        //{
                        //    cacheList.luisEntities = "reSendMsg";
                        //}
                        //if (luisIntent.Equals("등록신청"))
                        //{
                        //    cacheList.luisEntities = "insertEtcComment";
                        //}

                        ////orgMent 변경(문자수신 시나리오)
                        //if (luisIntent.Equals("문자수신시나리오") || orgMent.Equals("예") || orgMent.Equals("아니오")
                        //    || orgMent.Equals("예스") || orgMent.Equals("노") || orgMent.Equals("yes") || orgMent.Equals("no"))
                        //{
                        //    luisIntent = "문자수신시나리오";
                        //    cacheList.luisEntities = "smsScenario";
                        //}

                        //if (luisIntent.Equals("물량그룹건수조회"))
                        //{
                        //    cacheList.luisEntities = "groupperentity";
                        //}

                        //DButil.HistoryLog("luisEntities : " + luisEntities);
                        ///////////////////////////////////////////////////////////////////////



                        //String fullentity = db.SearchCommonEntities;
                        //DButil.HistoryLog("fullentity : " + fullentity);

                        if (apiFlag.Equals("COMMON"))
                        {
                            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("cjlogisticsChatBot_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);

                            for (int m = 0; m < MessagesController.relationList.Count; m++)
                            {
                                DialogList dlg            = db.SelectDialog(MessagesController.relationList[m].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
                                {
                                    //DLG 출력
                                    tempAttachment = dbutil.getAttachmentFromDialog(dlg, activity);

                                    if (luisIntent == "통화가능시간")
                                    {
                                        info += "정보 : " + orgMent + "||\r\n";
                                    }
                                    else if (luisIntent == "연락처")
                                    {
                                        info += "통화가능시간 : " + orgMent + "||\r\n";
                                    }
                                    else if (luisIntent == "지역")
                                    {
                                        info += "연락처 : " + orgMent + "||\r\n";
                                    }
                                    else if (luisIntent == "정보수집")
                                    {
                                        info += "지역 : " + orgMent + " " + ((Microsoft.Bot.Connector.HeroCard)tempAttachment.Content).Text;
                                    }

                                    Debug.WriteLine("info===" + info + " " + ((Microsoft.Bot.Connector.HeroCard)tempAttachment.Content).Text);
                                    Debug.WriteLine("Title===" + ((Microsoft.Bot.Connector.HeroCard)tempAttachment.Content).Title);

                                    if (((Microsoft.Bot.Connector.HeroCard)tempAttachment.Content).Text == "정보확인")
                                    {
                                        ((Microsoft.Bot.Connector.HeroCard)tempAttachment.Content).Text = info.Replace("정보확인", "");
                                    }

                                    commonReply.Attachments.Add(tempAttachment);
                                }

                                if (commonReply.Attachments.Count > 0)
                                {
                                    SetActivity(commonReply);
                                    conversationhistory.commonBeforeQustion = orgMent;
                                    replyresult = "H";
                                }
                            }
                        }
                        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 <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));
                        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("8");
                    }
                    else
                    {
                        //text = db.SelectSorryDialogText("6");
                    }
                    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);

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

                //초기 다이얼로그 호출
                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://nanetChatBot.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);//해당금칙어에 대한 답변

                    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
                    {
                        String checkBookIntent = "";
                        String checkIntent     = "";
                        String bookName        = "";
                        if (activity.Text.Contains("[") && activity.Text.Contains("]"))
                        {
                            int apiIntentS = activity.Text.IndexOf("[");
                            int apiIntentE = activity.Text.IndexOf("]");
                            bookName = activity.Text.Substring(apiIntentS + 1, (apiIntentE - 1) - apiIntentS);

                            Debug.WriteLine("bookName-------------" + bookName);
                        }



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

                        Debug.WriteLine("smalltalk 로 intent 찾기");
                        String apiActiveText = Regex.Replace(activity.Text, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);//공백 및 특수문자 제거

                        Activity apiMakerReply = activity.CreateReply();

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

                        string smallTalkConfirm = "";
                        String sampleData       = "";

                        /************************
                         * 임시로 책장보는 하드코딩 한다.
                         *************************/
                        String   bookData      = "삼국지,조선왕조실록,90년생이온다,여행의이유,호모커넥서스,임나일본부해부";
                        String[] bookDataArray = bookData.Split(',');
                        for (int i = 0; i < bookDataArray.Length; i++)
                        {
                            if (cashOrgMent.Contains(bookDataArray[i]))
                            {
                                checkBookIntent = "F_도서검색";
                                searchWord      = bookDataArray[i];
                            }
                        }

                        //이용안내TIP
                        if (apiActiveText.Equals("이용안내TIP"))
                        {
                            checkIntent = "F_이용안내TIP";
                        }
                        else
                        {
                            if (checkBookIntent.Equals("") || checkBookIntent == null)
                            {
                                //checkIntent = db.getIntentFromSmallTalk(orgMent);
                                String   IntentDataFromRelation      = db.getIntentDataFromRelation().Substring(1);
                                String[] IntentDataFromRelationArray = IntentDataFromRelation.Split('%');
                                for (int j = 0; j < IntentDataFromRelationArray.Length; j++)
                                {
                                    String[] checkData    = IntentDataFromRelationArray[j].Split(':');
                                    String   intentString = checkData[0];
                                    String   EntityString = checkData[1];

                                    if (EntityString.Contains(","))
                                    {
                                        String[] checkEntityArray = EntityString.Split(',');
                                        for (int ii = 0; ii < checkEntityArray.Length; ii++)
                                        {
                                            if (apiActiveText.Contains(checkEntityArray[ii]))
                                            {
                                                checkIntent = intentString;
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (apiActiveText.Contains(EntityString))
                                        {
                                            checkIntent = intentString;
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                checkIntent = checkBookIntent;
                            }
                        }

                        if (checkIntent.Equals("") || checkIntent == null)
                        {
                            relationList = null;
                            //INTENT 가 없으니까 SORRY MESSAGE
                            Activity sorryReply = activity.CreateReply();

                            string queryStr = activity.Text;

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

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

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

                            text = db.SelectSorryDialogText("5");
                            for (int i = 0; i < text.Count; i++)
                            {
                                UserHeroCard plCard = new UserHeroCard()
                                {
                                    Title = text[i].cardTitle,
                                    Text  = text[i].cardText,
                                    //Buttons = cardButtons
                                };

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

                            SetActivity(sorryReply);

                            //db.InsertError(activity.Conversation.Id, e.Message);

                            DateTime endTime1  = DateTime.Now;
                            int      dbResult1 = db.insertUserQuery(null, "", "", "", "", "E", queryStr);
                            //db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), "", "", "", "","E");
                            db.insertHistory(null, activity.Conversation.Id, activity.ChannelId, ((endTime1 - MessagesController.startTime).Milliseconds), "", "", "", "", "E", queryStr);
                        }
                        else if (checkIntent.Equals("F_도서검색"))
                        {
                            relationList = null;

                            /************************************************************
                             * 네이버 API 적용
                             * ******************************************************/


                            if (apiActiveText.Contains("도서자료") && !string.IsNullOrEmpty(bookName))
                            {
                                //bookName = System.Web.HttpUtility.UrlEncode(bookName);
                                int currentPage = 1;
                                if (queryStr.IndexOf("페이지") > 0)
                                {
                                    string[] pageResult = queryStr.Split(' ');

                                    Debug.WriteLine(pageResult[1]);
                                    currentPage = Convert.ToInt32(Regex.Replace(pageResult[1], @"\D", ""));
                                }


                                string url = "https://openapi.naver.com/v1/search/book.json?query=" + System.Web.HttpUtility.UrlEncode(bookName) + "&display=10&start=" + currentPage + "&sort=sim"; //news JSON result
                                //string blogUrl = "https://openapi.naver.com/v1/search/blog.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //search JSON result
                                //string cafeUrl = "https://openapi.naver.com/v1/search/cafearticle.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //cafe JSON result
                                //string url = "https://openapi.naver.com/v1/search/blog.xml?query=" + query; //blog XML result
                                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                                request.Headers.Add("X-Naver-Client-Id", "8V_GHk868_ggD3d1Kr7x");
                                request.Headers.Add("X-Naver-Client-Secret", "EUIOkjlFKX");
                                HttpWebResponse httpwebresponse = (HttpWebResponse)request.GetResponse();
                                string          status          = httpwebresponse.StatusCode.ToString();

                                if (status == "OK")
                                {
                                    Stream       stream = httpwebresponse.GetResponseStream();
                                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                                    string       text   = reader.ReadToEnd();

                                    RootObject serarchList = JsonConvert.DeserializeObject <RootObject>(text);

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

                                    int searchTotal = 0;
                                    searchTotal = serarchList.total;
                                    Activity apiMakerReply1 = activity.CreateReply();

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

                                    UserHeroCard plCard1 = new UserHeroCard()
                                    {
                                        Title = "",
                                        Text  = "도서자료 <strong>" + bookName + "</strong> 검색결과<br>검색건수 : " + searchTotal + "건" + " 현재페이지 : " + currentPage,
                                    };

                                    Attachment plattachment1 = plCard1.ToAttachment();
                                    apiMakerReply1.Attachments.Add(plattachment1);
                                    SetActivity(apiMakerReply1);


                                    for (int i = 0; i < serarchList.display; i++)
                                    {
                                        string searchTitle     = "";
                                        string searchSubTitle  = "";
                                        string searchText      = "";
                                        string searchImageUrl  = "";
                                        string searchAuthor    = "";
                                        string searchPublisher = "";


                                        searchTitle     = serarchList.items[i].title;
                                        searchAuthor    = serarchList.items[i].author;
                                        searchPublisher = serarchList.items[i].publisher;
                                        searchImageUrl  = serarchList.items[i].image;
                                        searchText      = serarchList.items[i].description;
                                        searchImageUrl  = serarchList.items[i].image;


                                        searchSubTitle = "저자 : " + searchAuthor + " | " + "출판사 : " + searchPublisher;

                                        List <CardImage> cardImages = new List <CardImage>();
                                        CardImage        img        = new CardImage();
                                        img.Url = searchImageUrl;
                                        cardImages.Add(img);

                                        List <CardAction> cardButtons = new List <CardAction>();
                                        CardAction[]      plButton    = new CardAction[1];
                                        plButton[0] = new CardAction()
                                        {
                                            Value = Regex.Replace(serarchList.items[i].link, "amp;", ""),
                                            Type  = "openUrl",
                                            Title = "자세히보기"
                                        };
                                        cardButtons = new List <CardAction>(plButton);

                                        LinkHeroCard card = new LinkHeroCard()
                                        {
                                            Title    = searchTitle,
                                            Subtitle = searchSubTitle,
                                            Text     = searchText,
                                            Images   = cardImages,
                                            Buttons  = cardButtons,
                                            //Link = Regex.Replace(serarchList.items[i].link, "amp;", "")
                                            Link = null
                                        };
                                        var attachment = card.ToAttachment();
                                        apiMakerReply.Attachments.Add(attachment);
                                    }
                                    //apiMakerReply.Attachments.Add(attachment);
                                }

                                SetActivity(apiMakerReply);

                                Activity apiMakerReplyPageing = activity.CreateReply();

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

                                List <CardAction> cardPagingButtons = new List <CardAction>();

                                if (currentPage == 1)
                                {
                                    int nextMovePage = currentPage + 1;

                                    CardAction plButtonPaging_new = new CardAction();

                                    plButtonPaging_new = new CardAction()
                                    {
                                        Value = "도서자료[" + bookName + "] " + nextMovePage + "페이지로 이동",
                                        Type  = "imBack",
                                        Title = "다음 페이지"
                                    };
                                    cardPagingButtons.Add(plButtonPaging_new);
                                }
                                else
                                {
                                    int nextMovePage = currentPage + 1;
                                    int preMovePage  = currentPage - 1;

                                    CardAction[] plButtonPaging_new = new CardAction[2];

                                    for (int pageCnt = 0; pageCnt < 2; pageCnt++)
                                    {
                                        if (pageCnt == 0)
                                        {
                                            plButtonPaging_new[pageCnt] = new CardAction()
                                            {
                                                Value = "도서자료[" + bookName + "] " + preMovePage + "페이지로 이동",
                                                Type  = "imBack",
                                                Title = "이전 페이지"
                                            };
                                        }
                                        else
                                        {
                                            plButtonPaging_new[pageCnt] = new CardAction()
                                            {
                                                Value = "도서자료[" + bookName + "] " + nextMovePage + "페이지로 이동",
                                                Type  = "imBack",
                                                Title = "다음 페이지"
                                            };
                                        }

                                        cardPagingButtons.Add(plButtonPaging_new[pageCnt]);
                                    }
                                }


                                //cardPagingButtons = new List<CardAction>(plButtonPaging);
                                //cardPagingButtons.Add(plButtonPaging);

                                UserHeroCard plCardPageing = new UserHeroCard()
                                {
                                    Title   = null,
                                    Text    = "다음 페이지로 이동합니다.",
                                    Buttons = cardPagingButtons
                                };

                                Attachment plAttachmentPageing = plCardPageing.ToAttachment();
                                apiMakerReplyPageing.Attachments.Add(plAttachmentPageing);
                                SetActivity(apiMakerReplyPageing);
                            }
                            else
                            {
                                List <CardAction> cardButtons = new List <CardAction>();

                                CardAction bookButton1 = new CardAction();
                                bookButton1 = new CardAction()
                                {
                                    Type  = "imBack",
                                    Value = "전체자료[" + searchWord + "]",
                                    Title = "전체자료(30건)"
                                };
                                cardButtons.Add(bookButton1);

                                CardAction bookButton2 = new CardAction();
                                bookButton2 = new CardAction()
                                {
                                    Type  = "imBack",
                                    Value = "학위논문[" + searchWord + "]",
                                    Title = "학위논문(0건)"
                                };
                                cardButtons.Add(bookButton2);

                                CardAction bookButton3 = new CardAction();
                                bookButton3 = new CardAction()
                                {
                                    Type  = "imBack",
                                    Value = "특종기사[" + searchWord + "]",
                                    Title = "특종기사(21건)"
                                };
                                cardButtons.Add(bookButton3);

                                CardAction bookButton4 = new CardAction();
                                bookButton4 = new CardAction()
                                {
                                    Type  = "imBack",
                                    Value = "도서자료[" + searchWord + "]",
                                    Title = "도서자료(7건)"
                                };
                                cardButtons.Add(bookButton4);

                                CardAction bookButton5 = new CardAction();
                                bookButton5 = new CardAction()
                                {
                                    Type  = "imBack",
                                    Value = "인터넷자료[" + searchWord + "]",
                                    Title = "인터넷자료(2건)"
                                };
                                cardButtons.Add(bookButton5);

                                UserHeroCard plCard = new UserHeroCard()
                                {
                                    Title   = "",
                                    Text    = "아래와 같이 자료에 대해서 알려 드릴 수 있습니다.",
                                    Buttons = cardButtons,
                                };
                                Attachment plAttachment = plCard.ToAttachment();
                                apiMakerReply.Attachments.Add(plAttachment);
                                SetActivity(apiMakerReply);
                            }
                        }
                        else if (checkIntent.Equals("F_이용안내TIP"))
                        {
                            relationList = null;
                            UserHeroCard plCard = new UserHeroCard()
                            {
                                Title = "NALI 이용안내",
                                Text  = "1. 대화예시문<br>저자 검색 :<br>예시)<br>&nbsp;&nbsp; 박경리가 쓴 책을 알려줘<br>&nbsp;&nbsp; 저자 박경리 검색해줘<br>자료명 검색 :<br>&nbsp;예시)<br>&nbsp;&nbsp;  삼국지 검색해줘<br>&nbsp;&nbsp;  수호지 찾아줘<br><br> &nbsp;2. 결과내 검색<br>&nbsp;&nbsp;  검색 후 결과내 검색을 클릭 후 검색하시면 됩니다.<br><br> &nbsp;3. 결과 더 보기<br>&nbsp;&nbsp;  결과 더보기를 클릭하시면 전체 검색결과를 확인 할 수 있습니다.",
                            };
                            Attachment plAttachment = plCard.ToAttachment();
                            apiMakerReply.Attachments.Add(plAttachment);
                            SetActivity(apiMakerReply);
                        }
                        else
                        {
                            relationList = db.DefineTypeChkSpare(checkIntent, luisEntities);
                        }


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

                        if (relationList != null)
                        {
                            dlgId = "";
                            for (int m = 0; m < relationList.Count; m++)
                            {
                                DialogList dlg = db.SelectDialog(relationList[m].dlgId, "MOBILE");
                                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
                        {
                        }

                        DateTime endTime  = DateTime.Now;
                        int      dbResult = db.insertUserQuery(relationList, luisId, luisIntent, luisEntities, luisIntentScore, replyresult, orgMent);
                        db.insertHistory(null, activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), luisIntent, luisEntities, luisIntentScore, dlgId, replyresult, orgMent);
                        replyresult = "";
                        luisIntent  = "";
                    }
                }
                catch (Exception e)
                {
                    Debug.Print(e.StackTrace);
                    DButil.HistoryLog("ERROR===" + e.Message);

                    Activity sorryReply = activity.CreateReply();

                    string queryStr = activity.Text;

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

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

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

                    text = db.SelectSorryDialogText("5");
                    for (int i = 0; i < text.Count; i++)
                    {
                        UserHeroCard plCard = new UserHeroCard()
                        {
                            Title = text[i].cardTitle,
                            Text  = text[i].cardText,
                            //Buttons = cardButtons
                        };

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

                    SetActivity(sorryReply);

                    //db.InsertError(activity.Conversation.Id, e.Message);

                    DateTime endTime  = DateTime.Now;
                    int      dbResult = db.insertUserQuery(null, "", "", "", "", "E", queryStr);
                    //db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), "", "", "", "","E");
                    db.insertHistory(null, activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds), "", "", "", "", "E", queryStr);
                }
                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);
        }
Exemplo n.º 6
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;
                //파라메터 호출
                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 "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
                    {
                        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);

                qTempTable = new Hashtable();
                qTempTable.Add(1, "VPN+");
                qTempTable.Add(2, "워터마크+해지");
                qTempTable.Add(3, "비업무사이트+");
                qTempTable.Add(4, "USB+");
                //qTempTable.Add(5, "파일업로드+인터넷,파일업로드");
                qTempTable.Add(5, "파일업로드+권한,인터넷,파일업로드");
            }
            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;

                    /*
                     * 들어온 데이터가 숫자인지 아닌지 판단
                     * 숫자가 들어오면 임시해시테이블을 통해서 검색어를 재조정한다.
                     */
                    bool     checkNum       = Regex.IsMatch(orgMent, @"^\d+$");
                    String[] msgEntity      = null;
                    String   newMessageTemp = null;
                    String   newMessage     = null;
                    String   plusEntity     = "";
                    if (checkNum)
                    {
                        int tempMessageNum = Int32.Parse(orgMent);
                        newMessageTemp = (String)qTempTable[tempMessageNum];
                        msgEntity      = newMessageTemp.Split('+');
                        newMessage     = msgEntity[0];
                        if (msgEntity[1] == null || msgEntity[1] == "")
                        {
                            plusEntity = msgEntity[1];
                        }
                        else
                        {
                            plusEntity = "," + msgEntity[1];
                        }

                        orgMent = newMessage;
                    }

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


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

                        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;

                        //String fullentity = db.SearchCommonEntities;
                        String   fullentity_   = db.SearchCommonEntities + plusEntity;
                        String[] DupCheckArray = fullentity_.Split(',');
                        String[] DupCheck      = DupCheckArray.Distinct().ToArray();
                        //Array.Sort(DupCheck);
                        String fullentity_make = "";
                        String fullentity      = "";
                        for (int i = 0; i < DupCheck.Length; i++)
                        {
                            if (i == 0)
                            {
                                fullentity_make = DupCheck[i];
                            }
                            else
                            {
                                fullentity_make = fullentity_make + "," + DupCheck[i];
                            }
                        }
                        fullentity = db.EntityOrder(fullentity_make);
                        DButil.HistoryLog("fullentity : " + fullentity);
                        Debug.WriteLine("fullentity log : " + 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("kona_luis_01") && MessagesController.cacheList.luisIntent.Contains("quot"))
                            {
                                apiFlag = "QUOT";
                            }
                        }


                        if (apiFlag.Equals("COMMON") && relationList.Count > 0)
                        {
                            //context.Call(new CommonDialog("", MessagesController.queryStr), this.ResumeAfterOptionDialog);
                            for (int m = 0; m < MessagesController.relationList.Count; m++)
                            {
                                DialogList dlg = db.SelectDialog(MessagesController.relationList[m].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);
                                        }
                                    }
                                }
                                else
                                {
                                    qTempTable = new Hashtable();
                                    String test         = dlg.cardText;
                                    String test2        = Regex.Replace(test, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);
                                    String onlyNumCheck = Regex.Replace(test2, @"\D", "");

                                    Regex cntStr      = new Regex("12345"); //1.2.3.4. 이런식으로 넘어갈 테니까...답변 중에 12345 가 연속적으로 나오는 것은 없다.
                                    int   cntStrCount = int.Parse(cntStr.Matches(onlyNumCheck, 0).Count.ToString());

                                    if (cntStrCount > 0)
                                    {
                                        for (int i = 0; i < 10; i++)
                                        {
                                            test2 = test2.Replace("1", "#");
                                            test2 = test2.Replace("2", "#");
                                            test2 = test2.Replace("3", "#");
                                            test2 = test2.Replace("4", "#");
                                            test2 = test2.Replace("5", "#");
                                            test2 = test2.Replace("6", "#");
                                            test2 = test2.Replace("7", "#");
                                            test2 = test2.Replace("8", "#");
                                            test2 = test2.Replace("9", "#");
                                        }
                                        test2.Replace("##", "#");

                                        String[] tempData = test2.Split('#');

                                        for (int j = 0; j < tempData.Length; j++)
                                        {
                                            //여기의 데이터는 예외사항이다.
                                            if (tempData[j].Equals("사용기간") ||
                                                tempData[j].Equals("결재라인") ||
                                                tempData[j].Equals("요청서작성방법") ||
                                                tempData[j].Equals("대리신청") ||
                                                tempData[j].Equals("권한회수") ||
                                                tempData[j].Equals("권한상태") ||
                                                tempData[j].Equals("웹하드사이트접속") ||
                                                tempData[j].Equals("쇼핑사이트접속")
                                                )
                                            {
                                                qTempTable.Add(j, tempData[j] + "+");//위의값은 공통사항이다.
                                            }
                                            else
                                            {
                                                qTempTable.Add(j, tempData[j] + "+" + fullentity);//entity 값도 같이 넣는다.
                                            }
                                        }
                                    }
                                    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);

                            sorryflag = true;
                            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");
                                    text = db.SelectSorryDialogText("4"); //원래 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");
                        text = db.SelectSorryDialogText("4");
                    }
                    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 != "")
                    {
                        Debug.WriteLine("* reply1 : " + 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);
        }
Exemplo n.º 7
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            //수정시작
            if (activity != null)
            {
                try
                {
                    switch (activity.GetActivityType())
                    {
                    case ActivityTypes.Message:
                        activity.Text = activity.RemoveRecipientMention();
                        await Conversation.SendAsync(activity, () => new ProactiveBusiness());

                        break;

                    case ActivityTypes.Event:
                        IEventActivity trigger = (IEventActivity)activity;
                        DButil.HistoryLog("****** Trigger Test ******");
                        var message = JsonConvert.DeserializeObject <QueueMessage>(((JObject)trigger.Value).GetValue("Message").ToString());
                        if (!string.IsNullOrEmpty(message.MessageText))
                        {
                            var messageactivity = (Activity)message.ResumptionCookie.GetMessage();

                            var client = new ConnectorClient(new Uri(messageactivity.ServiceUrl));
                            activity.Text = activity.RemoveRecipientMention();

                            Activity replyToConversation = messageactivity.CreateReply();
                            replyToConversation.Recipient = activity.From;
                            replyToConversation.Type      = "message";

                            replyToConversation.Attachments = new List <Attachment>();
                            List <CardImage> cardImages = new List <CardImage>();
                            cardImages.Add(new CardImage(url: " http://cdn.wonderfulengineering.com/wp-content/uploads/2016/02/iron-man-wallpaper-22.jpg"));
                            List <CardAction> cardButtons = new List <CardAction>();
                            CardAction        plButton    = new CardAction()
                            {
                                Value = "https://en.wikipedia.org/wiki/Iron_Man",
                                Type  = "openUrl",
                                Title = "Ironman Wiki"
                            };
                            cardButtons.Add(plButton);
                            HeroCard plCard = new HeroCard()
                            {
                                Title    = message.MessageText,
                                Subtitle = "Triggered Iron Man Card",
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };
                            Attachment plAttachment = plCard.ToAttachment();
                            replyToConversation.Attachments.Add(plAttachment);
                            await client.Conversations.ReplyToActivityAsync(replyToConversation);
                        }
                        break;
                    }
                }
                catch (Exception ex)
                {
                }
            }
            //수정끝


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


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

                        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;

                        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("TimeSolution_luis_01") && MessagesController.cacheList.luisIntent.Contains("quot"))
                            {
                                apiFlag = "QUOT";
                            }
                        }


                        if (apiFlag.Equals("COMMON") && relationList.Count > 0)
                        {
                            //context.Call(new CommonDialog("", MessagesController.queryStr), this.ResumeAfterOptionDialog);

                            for (int m = 0; m < MessagesController.relationList.Count; m++)
                            {
                                DialogList dlg            = db.SelectDialog(MessagesController.relationList[m].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);
                            //네이버 기사 검색
                            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);
        }
        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 "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;
                    string tranText = "";

                    //캐시 체크
                    cashOrgMent = Regex.Replace(orgMent, @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);


                    Debug.WriteLine("* activity.Type == cashOrgMent " + cashOrgMent);

                    if (cashOrgMent == "DoosanInfracore工程机械事业部门构筑了挖掘机轮式装载机铰接式翻斗车等产品系列在全球各地确保着生产销售及流通网络成为名符其实的全球综合工程机械公司")
                    {
                        tranText = "두산인프라코어 건설기계 사업부문은 굴삭기와 휠로더, 굴절식 덤프트럭까지 라인업을 구축하고 전 세계 각지에 생산, 판매 및 유통망을 확보함으로써 명실상부한 글로벌 종합 건설기계 회사로 자리매김했습니다";
                    }
                    else if (cashOrgMent == "DoosanBobcat具备小型铲车迷你挖掘机增益装备utilityequipment伸缩臂叉装车等业内最高级的小型设备与移动动力配件等多种业务项目")
                    {
                        tranText = "두산밥캣은 소형 로더, 미니 굴삭기, 유틸리티 장비, 텔레스코픽핸들러 등 업계 최고의 소형 장비와 포터블파워, 어태치먼트 등 다양한 사업 포트폴리오를 갖추고 있습니다.";
                    }
                    else if (cashOrgMent == "工程机械DoosanInfracore工程机械事业部门构筑了挖掘机轮式装载机铰接式翻斗车等产品系列在全球各地确保着生产销售及流通网络成为名符其实的全球综合工程机械公司")
                    {
                        tranText = "건설기계 두산인프라코어 건설기계 사업부문은 굴삭기와 휠로더, 굴절식 덤프트럭까지 라인업을 구축하고 전 세계 각지에 생산, 판매 및 유통망을 확보함으로써 명실상부한 글로벌 종합 건설기계 회사로 자리매김했습니다";
                    }
                    else if (cashOrgMent == "工程机械事业部门构筑了挖掘机轮式装载机铰接式翻斗车等产品系列在全球各地确保着生产销售及流通网络成为名符其实的全球综合工程机械公司")
                    {
                        tranText = "건설기계 사업부문은 굴삭기와 휠로더, 굴절식 덤프트럭까지 라인업을 구축하고 전 세계 각지에 생산, 판매 및 유통망을 확보함으로써 명실상부한 글로벌 종합 건설기계 회사로 자리매김했습니다";
                    }
                    else if (cashOrgMent == "具备小型铲车迷你挖掘机增益装备utilityequipment伸缩臂叉装车等业内最高级的小型设备与移动动力配件等多种业务项目")
                    {
                        tranText = "소형 로더, 미니 굴삭기, 유틸리티 장비, 텔레스코픽핸들러 등 업계 최고의 소형 장비와 포터블파워, 어태치먼트 등 다양한 사업 포트폴리오를 갖추고 있습니다.";
                    }
                    else
                    {
                        Debug.WriteLine("* activity.Type ==>" + activity.Text);
                        Translator textZhKoTranslate = new Translator();
                        textZhKoTranslate = await DButil.getTranslate(activity.Text);

                        tranText = textZhKoTranslate.data.translations[0].translatedText;
                        DButil.HistoryLog("taanText 11 ====>" + tranText);
                    }


                    //오타 수정 API
                    string tranText2 = DButil.getEditTypo(tranText);
                    DButil.HistoryLog("taanText 22 ====>" + tranText);
                    Debug.WriteLine("* taanText ==>" + tranText);

                    apiFlag = "COMMON";

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

                    DButil.HistoryLog("orgMent : " + orgMent);

                    queryStr = orgMent;

                    string newUserID = activity.Conversation.Id;

                    Activity sorryReply = activity.CreateReply();

                    HeroCard plCard = new HeroCard()
                    {
                        Title = "",
                        Text  = tranText
                    };

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

                    SetActivity(sorryReply);
                    replyresult = "D";

                    DateTime endTime = DateTime.Now;

                    int dbResult = db.insertUserQuery();

                    db.insertHistory(activity.Conversation.Id, activity.ChannelId, ((endTime - MessagesController.startTime).Milliseconds));
                    replyresult     = "";
                    recommendResult = "";
                    tranText        = "";
                }
                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);
                    }
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }
Exemplo n.º 10
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);
        }