Пример #1
0
        private static Attachment GetHeroCard_facebookMore(string title, string subtitle, string text, CardAction cardAction)
        {
            var heroCard = new UserHeroCard
            {
                Title    = title,
                Subtitle = subtitle,
                Text     = text,
                Buttons  = new List <CardAction>()
                {
                    cardAction
                },
            };

            return(heroCard.ToAttachment());
        }
Пример #2
0
        public static Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, /*CardAction cardAction*/ List <CardAction> buttons)
        {
            var heroCard = new UserHeroCard
            {
                Title    = title,
                Subtitle = subtitle,
                Text     = text,
                Images   = new List <CardImage>()
                {
                    cardImage
                },
                Buttons = buttons,
            };

            return(heroCard.ToAttachment());
        }
Пример #3
0
        public Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, /*CardAction cardAction*/ List <CardAction> buttons, string cardDivision, string cardValue)
        {
            var heroCard = new UserHeroCard
            {
                Title    = title,
                Subtitle = subtitle,
                Text     = text,
                Images   = new List <CardImage>()
                {
                    cardImage
                },
                Buttons       = buttons,
                Card_division = cardDivision,
                Card_value    = cardValue,
            };

            return(heroCard.ToAttachment());
        }
Пример #4
0
        //지도 맵 추가
        public static Attachment GetHeroCard_Map(string title, string subtitle, string text, CardImage cardImage, /*CardAction cardAction*/ List <CardAction> buttons, string latitude, string longitude)
        {
            var heroCard = new UserHeroCard
            {
                Title    = title,
                Subtitle = subtitle,
                Text     = newLine + text,
                Images   = new List <CardImage>()
                {
                    cardImage
                },
                Buttons   = buttons,
                Latitude  = latitude,
                Longitude = longitude,
            };

            return(heroCard.ToAttachment());
        }
Пример #5
0
        //지도 맵 추가
        public static Attachment GetHeroCard_Map(string title, string subtitle, string text, CardImage cardImage, /*CardAction cardAction List<CardAction> buttons,*/ string latitude, string longitude, string cardDivision)
        {
            var heroCard = new UserHeroCard
            {
                Title    = title,
                Subtitle = subtitle,
                Text     = text,
                Images   = new List <CardImage>()
                {
                    cardImage
                },
                //Buttons = new List<CardAction>() { cardAction },
                Latitude      = latitude,
                Longitude     = longitude,
                Card_division = cardDivision
            };

            return(heroCard.ToAttachment());
        }
Пример #6
0
        public Attachment getAttachmentFromDialog(CardList card, Activity activity)
        {
            ConnectorClient connector        = new ConnectorClient(new Uri(activity.ServiceUrl));
            Attachment      returnAttachment = new Attachment();

            string cardDiv = "";
            string cardVal = "";

            List <CardImage>  cardImages  = new List <CardImage>();
            List <CardAction> cardButtons = new List <CardAction>();

            HistoryLog("CARD IMG START");
            if (card.imgUrl != null)
            {
                HistoryLog("FB CARD IMG " + card.imgUrl);
                cardImages.Add(new CardImage(url: card.imgUrl));
            }


            HistoryLog("CARD BTN1 START");


            if (activity.ChannelId.Equals("facebook") && card.btn1Type == null && !string.IsNullOrEmpty(card.cardDivision) && card.cardDivision.Equals("play") && !string.IsNullOrEmpty(card.cardValue))
            {
                CardAction plButton = new CardAction();
                plButton = new CardAction()
                {
                    Value = card.cardValue,
                    Type  = "openUrl",
                    Title = "영상보기"
                };
                cardButtons.Add(plButton);
            }
            else if (card.btn1Type != null)
            {
                CardAction plButton = new CardAction();
                plButton = new CardAction()
                {
                    Value = card.btn1Context,
                    Type  = card.btn1Type,
                    Title = card.btn1Title
                };
                cardButtons.Add(plButton);
            }

            if (card.btn2Type != null)
            {
                CardAction plButton = new CardAction();
                HistoryLog("CARD BTN2 START");
                plButton = new CardAction()
                {
                    Value = card.btn2Context,
                    Type  = card.btn2Type,
                    Title = card.btn2Title
                };
                cardButtons.Add(plButton);
            }

            if (card.btn3Type != null)
            {
                CardAction plButton = new CardAction();

                HistoryLog("CARD BTN3 START");
                plButton = new CardAction()
                {
                    Value = card.btn3Context,
                    Type  = card.btn3Type,
                    Title = card.btn3Title
                };
                cardButtons.Add(plButton);
            }

            if (card.btn4Type != null)
            {
                CardAction plButton = new CardAction();
                HistoryLog("CARD BTN4 START");
                plButton = new CardAction()
                {
                    Value = card.btn4Context,
                    Type  = card.btn4Type,
                    Title = card.btn4Title
                };
                cardButtons.Add(plButton);
            }



            if (!string.IsNullOrEmpty(card.cardDivision))
            {
                cardDiv = card.cardDivision;
            }

            if (!string.IsNullOrEmpty(card.cardValue))
            {
                //cardVal = priceMediaDlgList[i].cardValue.Replace();
                cardVal = card.cardValue;
            }


            if (activity.ChannelId.Equals("facebook") && cardButtons.Count < 1 && cardImages.Count < 1)
            {
                HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1");
                Activity reply_facebook = activity.CreateReply();
                reply_facebook.Recipient = activity.From;
                reply_facebook.Type      = "message";
                HistoryLog("facebook  card Text : " + card.cardText);
                reply_facebook.Text = card.cardText;
                var reply_ment_facebook = connector.Conversations.SendToConversationAsync(reply_facebook);
            }
            else
            {
                HistoryLog("!!!!!FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1");
                HeroCard plCard = new UserHeroCard();
                if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(card.cardValue))
                {
                    HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)");
                    plCard = new UserHeroCard()
                    {
                        Title   = card.cardTitle,
                        Images  = cardImages,
                        Buttons = cardButtons
                    };
                    returnAttachment = plCard.ToAttachment();
                }
                else
                {
                    HistoryLog("!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)");
                    if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(card.cardTitle))
                    {
                        HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)");
                        plCard = new UserHeroCard()
                        {
                            Title         = "선택해 주세요",
                            Text          = card.cardText,
                            Images        = cardImages,
                            Buttons       = cardButtons,
                            Card_division = cardDiv,
                            Card_value    = cardVal
                        };
                        returnAttachment = plCard.ToAttachment();
                    }
                    else
                    {
                        HistoryLog("!!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)");
                        plCard = new UserHeroCard()
                        {
                            Title         = card.cardTitle,
                            Text          = card.cardText,
                            Images        = cardImages,
                            Buttons       = cardButtons,
                            Card_division = cardDiv,
                            Card_value    = cardVal
                        };
                        returnAttachment = plCard.ToAttachment();
                    }
                }
            }

            //HeroCard plCard = new UserHeroCard()
            //{
            //    Title = card.cardTitle,
            //    Text = card.cardText,
            //    Images = cardImages,
            //    Buttons = cardButtons,
            //    Card_division = cardDiv,
            //    Card_value = cardVal
            //};
            //returnAttachment = plCard.ToAttachment();

            return(returnAttachment);
        }
Пример #7
0
        public Attachment getAttachmentFromDialog(DialogList dlg, Activity activity)
        {
            Attachment      returnAttachment = new Attachment();
            ConnectorClient connector        = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (dlg.dlgType.Equals(MessagesController.TEXTDLG))
            {
                if (!activity.ChannelId.Equals("facebook"))
                {
                    HeroCard plCard = new HeroCard()
                    {
                        Title = dlg.cardTitle,
                        Text  = dlg.cardText
                    };
                    returnAttachment = plCard.ToAttachment();
                }
            }
            else if (dlg.dlgType.Equals(MessagesController.MEDIADLG))
            {
                string cardDiv = "";
                string cardVal = "";

                List <CardImage>  cardImages  = new List <CardImage>();
                List <CardAction> cardButtons = new List <CardAction>();

                HistoryLog("CARD IMG START");
                if (dlg.mediaUrl != null)
                {
                    HistoryLog("FB CARD IMG " + dlg.mediaUrl);
                    cardImages.Add(new CardImage(url: dlg.mediaUrl));
                }


                HistoryLog("CARD BTN1 START");
                if (activity.ChannelId.Equals("facebook") && dlg.btn1Type == null && !string.IsNullOrEmpty(dlg.cardDivision) && dlg.cardDivision.Equals("play") && !string.IsNullOrEmpty(dlg.cardValue))
                {
                    CardAction plButton = new CardAction();
                    plButton = new CardAction()
                    {
                        Value = dlg.cardValue,
                        Type  = "openUrl",
                        Title = "영상보기"
                    };
                    cardButtons.Add(plButton);
                }
                else if (dlg.btn1Type != null)
                {
                    CardAction plButton = new CardAction();
                    plButton = new CardAction()
                    {
                        Value = dlg.btn1Context,
                        Type  = dlg.btn1Type,
                        Title = dlg.btn1Title
                    };
                    cardButtons.Add(plButton);
                }

                if (dlg.btn2Type != null)
                {
                    if (!(activity.ChannelId == "facebook" && dlg.btn2Title == "나에게 맞는 모델 추천"))
                    {
                        CardAction plButton = new CardAction();
                        HistoryLog("CARD BTN2 START");
                        plButton = new CardAction()
                        {
                            Value = dlg.btn2Context,
                            Type  = dlg.btn2Type,
                            Title = dlg.btn2Title
                        };
                        cardButtons.Add(plButton);
                    }
                }

                if (dlg.btn3Type != null)
                {
                    CardAction plButton = new CardAction();

                    HistoryLog("CARD BTN3 START");
                    plButton = new CardAction()
                    {
                        Value = dlg.btn3Context,
                        Type  = dlg.btn3Type,
                        Title = dlg.btn3Title
                    };
                    cardButtons.Add(plButton);
                }

                if (dlg.btn4Type != null)
                {
                    CardAction plButton = new CardAction();
                    HistoryLog("CARD BTN4 START");
                    plButton = new CardAction()
                    {
                        Value = dlg.btn4Context,
                        Type  = dlg.btn4Type,
                        Title = dlg.btn4Title
                    };
                    cardButtons.Add(plButton);
                }

                if (!string.IsNullOrEmpty(dlg.cardDivision))
                {
                    cardDiv = dlg.cardDivision;
                }

                if (!string.IsNullOrEmpty(dlg.cardValue))
                {
                    //cardVal = priceMediaDlgList[i].cardValue.Replace();
                    cardVal = dlg.cardValue;
                }
                HistoryLog("!!!!!FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1");
                HeroCard plCard = new UserHeroCard();
                if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(dlg.cardTitle))
                {
                    HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)");
                    plCard = new UserHeroCard()
                    {
                        Title         = "선택해 주세요",
                        Text          = dlg.cardText,
                        Images        = cardImages,
                        Buttons       = cardButtons,
                        Card_division = cardDiv,
                        Card_value    = cardVal
                    };
                    returnAttachment = plCard.ToAttachment();
                }
                else if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(dlg.cardValue))
                {
                    HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)");
                    plCard = new UserHeroCard()
                    {
                        Title   = dlg.cardTitle,
                        Images  = cardImages,
                        Buttons = cardButtons
                    };
                    returnAttachment = plCard.ToAttachment();
                }
                else
                {
                    HistoryLog("!!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)");
                    plCard = new UserHeroCard()
                    {
                        Title         = dlg.cardTitle,
                        Text          = dlg.cardText,
                        Images        = cardImages,
                        Buttons       = cardButtons,
                        Card_division = cardDiv,
                        Card_value    = cardVal
                    };
                    returnAttachment = plCard.ToAttachment();
                }
            }
            else
            {
                Debug.WriteLine("Dialog Type Error : " + dlg.dlgType);
            }
            return(returnAttachment);
        }
Пример #8
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);
        }
        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);
        }
        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);
        }
Пример #11
0
        private Attachment getAttachmentFromDialog(CardList card)
        {
            Attachment returnAttachment = new Attachment();

            string cardDiv = "";
            string cardVal = "";

            List <CardImage>  cardImages  = new List <CardImage>();
            List <CardAction> cardButtons = new List <CardAction>();

            if (card.imgUrl != null)
            {
                cardImages.Add(new CardImage(url: card.imgUrl));
            }

            if (card.btn1Type != null)
            {
                CardAction plButton = new CardAction()
                {
                    Value = card.btn1Context,
                    Type  = card.btn1Type,
                    Title = card.btn1Title
                };

                cardButtons.Add(plButton);
            }

            if (card.btn2Type != null)
            {
                CardAction plButton = new CardAction()
                {
                    Value = card.btn2Context,
                    Type  = card.btn2Type,
                    Title = card.btn2Title
                };

                cardButtons.Add(plButton);
            }

            if (card.btn3Type != null)
            {
                CardAction plButton = new CardAction()
                {
                    Value = card.btn3Context,
                    Type  = card.btn3Type,
                    Title = card.btn3Title
                };

                cardButtons.Add(plButton);
            }

            if (card.btn4Type != null)
            {
                CardAction plButton = new CardAction()
                {
                    Value = card.btn4Context,
                    Type  = card.btn4Type,
                    Title = card.btn4Title
                };

                cardButtons.Add(plButton);
            }

            if (!string.IsNullOrEmpty(card.cardDivision))
            {
                cardDiv = card.cardDivision;
            }

            if (!string.IsNullOrEmpty(card.cardValue))
            {
                //cardVal = priceMediaDlgList[i].cardValue.Replace();
                cardVal = card.cardValue;
            }

            HeroCard plCard = new UserHeroCard()
            {
                Title         = card.cardTitle,
                Text          = card.cardTitle,
                Images        = cardImages,
                Buttons       = cardButtons,
                Card_division = cardDiv,
                Card_value    = cardVal
            };

            returnAttachment = plCard.ToAttachment();

            return(returnAttachment);
        }
Пример #12
0
        private Attachment getAttachmentFromDialog(DialogList dlg)
        {
            Attachment returnAttachment = new Attachment();
            string     cardDiv          = "";
            string     cardVal          = "";

            if (dlg.dlgType.Equals(TEXTDLG))
            {
                HeroCard plCard = new HeroCard()
                {
                    Title = dlg.cardTitle,
                    Text  = dlg.cardText
                };
                returnAttachment = plCard.ToAttachment();
            }
            else if (dlg.dlgType.Equals(MEDIADLG))
            {
                List <CardImage>  cardImages  = new List <CardImage>();
                List <CardAction> cardButtons = new List <CardAction>();

                if (dlg.mediaUrl != null)
                {
                    cardImages.Add(new CardImage(url: dlg.mediaUrl));
                }

                if (dlg.btn1Type != null)
                {
                    CardAction plButton = new CardAction()
                    {
                        Value = dlg.btn1Context,
                        Type  = dlg.btn1Type,
                        Title = dlg.btn1Title
                    };

                    cardButtons.Add(plButton);
                }

                if (dlg.btn2Type != null)
                {
                    CardAction plButton = new CardAction()
                    {
                        Value = dlg.btn2Context,
                        Type  = dlg.btn2Type,
                        Title = dlg.btn2Title
                    };

                    cardButtons.Add(plButton);
                }

                if (dlg.btn3Type != null)
                {
                    CardAction plButton = new CardAction()
                    {
                        Value = dlg.btn3Context,
                        Type  = dlg.btn3Type,
                        Title = dlg.btn3Title
                    };

                    cardButtons.Add(plButton);
                }

                if (dlg.btn4Type != null)
                {
                    CardAction plButton = new CardAction()
                    {
                        Value = dlg.btn4Context,
                        Type  = dlg.btn4Type,
                        Title = dlg.btn4Title
                    };

                    cardButtons.Add(plButton);
                }

                if (!string.IsNullOrEmpty(dlg.cardDivision))
                {
                    cardDiv = dlg.cardDivision;
                }

                if (!string.IsNullOrEmpty(dlg.cardValue))
                {
                    //cardVal = priceMediaDlgList[i].cardValue.Replace();
                    cardVal = dlg.cardValue;
                }

                HeroCard plCard = new UserHeroCard()
                {
                    Title         = dlg.cardTitle,
                    Text          = dlg.cardTitle,
                    Images        = cardImages,
                    Buttons       = cardButtons,
                    Card_division = cardDiv,
                    Card_value    = cardVal
                };
                returnAttachment = plCard.ToAttachment();
            }
            else
            {
                Debug.WriteLine("Dialog Type Error : " + dlg.dlgType);
            }
            return(returnAttachment);
        }
Пример #13
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);
        }