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);
        }
Beispiel #2
0
        public async Task StartAsync(IDialogContext context)
        {
            Debug.WriteLine("luis_intent : " + luis_intent);
            Debug.WriteLine("entitiesStr : " + entitiesStr);

            // Db
            DbConnect db = new DbConnect();

            Debug.WriteLine("activity : " + context.Activity.Conversation.Id);

            newUserID = context.Activity.Conversation.Id;
            if (beforeUserID != newUserID)
            {
                beforeUserID = newUserID;
                MessagesController.sorryMessageCnt = 0;
            }

            var message = MessagesController.queryStr;

            beforeMessgaeText = message.ToString();
            if (message.ToString().Contains("코나") == true)
            {
                messgaeText = message.ToString();
                if (messgaeText.Contains("현대자동차") != true || messgaeText.Contains("현대 자동차") != true)
                {
                    messgaeText = "현대자동차 " + messgaeText;
                }
            }
            else
            {
                messgaeText = "코나 " + message.ToString();
                if (messgaeText.Contains("현대자동차") != true || messgaeText.Contains("현대 자동차") != true)
                {
                    messgaeText = "현대자동차 " + messgaeText;
                }
            }

            if (messgaeText.Contains("코나") == true && (messgaeText.Contains("현대자동차") == true || messgaeText.Contains("현대 자동차") == true))
            {
                var reply = context.MakeMessage();
                Debug.WriteLine("SERARCH MESSAGE : " + messgaeText);
                if ((messgaeText != null) && messgaeText.Trim().Length > 0)
                {
                    //Naver Search API

                    string url = "https://openapi.naver.com/v1/search/news.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //news JSON result
                                                                                                                                        //string blogUrl = "https://openapi.naver.com/v1/search/blog.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //search JSON result
                                                                                                                                        //string cafeUrl = "https://openapi.naver.com/v1/search/cafearticle.json?query=" + messgaeText + "&display=10&start=1&sort=sim"; //cafe JSON result
                                                                                                                                        //string url = "https://openapi.naver.com/v1/search/blog.xml?query=" + query; //blog XML result
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Headers.Add("X-Naver-Client-Id", "Y536Z1ZMNv93Oej6TrkF");
                    request.Headers.Add("X-Naver-Client-Secret", "cPHOFK6JYY");
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    string          status   = response.StatusCode.ToString();
                    if (status == "OK")
                    {
                        Stream       stream = response.GetResponseStream();
                        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                        string       text   = reader.ReadToEnd();

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

                        Debug.WriteLine("serarchList : " + serarchList);
                        //description

                        if (serarchList.display == 1)
                        {
                            Debug.WriteLine("SERARCH : " + Regex.Replace(serarchList.items[0].title, @"[^<:-:>-<b>-</b>]", "", RegexOptions.Singleline));

                            if (serarchList.items[0].title.Contains("코나"))
                            {
                                //Only One item
                                List <CardImage> cardImages = new List <CardImage>();
                                CardImage        img        = new CardImage();
                                img.Url = "";
                                cardImages.Add(img);

                                string searchTitle = "";
                                string searchText  = "";

                                searchTitle = serarchList.items[0].title;
                                searchText  = serarchList.items[0].description;



                                if (context.Activity.ChannelId == "facebook")
                                {
                                    searchTitle = Regex.Replace(searchTitle, @"[<][a-z|A-Z|/](.|)*?[>]", "", RegexOptions.Singleline).Replace("\n", "").Replace("<:", "").Replace(":>", "");
                                    searchText  = Regex.Replace(searchText, @"[<][a-z|A-Z|/](.|)*?[>]", "", RegexOptions.Singleline).Replace("\n", "").Replace("<:", "").Replace(":>", "");
                                }


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

                                reply.Attachments = new List <Attachment>();
                                reply.Attachments.Add(attachment);
                            }
                        }
                        else
                        {
                            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                            reply.Attachments      = new List <Attachment>();
                            for (int i = 0; i < serarchList.display; i++)
                            {
                                string searchTitle = "";
                                string searchText  = "";

                                searchTitle = serarchList.items[i].title;
                                searchText  = serarchList.items[i].description;

                                if (context.Activity.ChannelId == "facebook")
                                {
                                    searchTitle = Regex.Replace(searchTitle, @"[<][a-z|A-Z|/](.|)*?[>]", "", RegexOptions.Singleline).Replace("\n", "").Replace("<:", "").Replace(":>", "");
                                    searchText  = Regex.Replace(searchText, @"[<][a-z|A-Z|/](.|)*?[>]", "", RegexOptions.Singleline).Replace("\n", "").Replace("<:", "").Replace(":>", "");
                                }

                                if (serarchList.items[i].title.Contains("코나"))
                                {
                                    List <CardImage> cardImages = new List <CardImage>();
                                    CardImage        img        = new CardImage();
                                    img.Url = "";
                                    cardImages.Add(img);

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

                                    if (context.Activity.ChannelId == "facebook")
                                    {
                                        LinkHeroCard card = new LinkHeroCard()
                                        {
                                            Title    = searchTitle,
                                            Subtitle = null,
                                            Text     = searchText,
                                            Images   = cardImages,
                                            Buttons  = cardButtons,
                                            Link     = null
                                        };
                                        var attachment = card.ToAttachment();
                                        reply.Attachments.Add(attachment);
                                    }
                                    else
                                    {
                                        LinkHeroCard card = new LinkHeroCard()
                                        {
                                            Title    = searchTitle,
                                            Subtitle = null,
                                            Text     = searchText,
                                            Images   = cardImages,
                                            Buttons  = null,
                                            Link     = Regex.Replace(serarchList.items[i].link, "amp;", "")
                                        };
                                        var attachment = card.ToAttachment();
                                        reply.Attachments.Add(attachment);
                                    }
                                }
                            }
                        }
                        await context.PostAsync(reply);



                        if (reply.Attachments.Count == 0)
                        {
                            await this.SendSorryMessageAsync(context);
                        }
                        else
                        {
                            orgKRMent = Regex.Replace(message.ToString(), @"[^a-zA-Z0-9ㄱ-힣]", "", RegexOptions.Singleline);


                            for (int n = 0; n < Regex.Split(message.ToString(), " ").Length; n++)
                            {
                                string chgMsg = db.SelectChgMsg(Regex.Split(message.ToString(), " ")[n]);
                                if (!string.IsNullOrEmpty(chgMsg))
                                {
                                    message = message.ToString().Replace(Regex.Split(message.ToString(), " ")[n], chgMsg);
                                }
                            }


                            Translator translateInfo = await getTranslate(message.ToString());

                            orgENGMent = Regex.Replace(translateInfo.data.translations[0].translatedText, @"[^a-zA-Z0-9ㄱ-힣-\s-&#39;]", "", RegexOptions.Singleline);

                            orgENGMent = orgENGMent.Replace("&#39;", "'");

                            //int dbResult = db.insertUserQuery(orgKRMent, orgENGMent, "", "", "", 1, 'S', "", "", "", "SEARCH", MessagesController.userData.GetProperty<int>("appID"));
                            int dbResult = db.insertUserQuery(orgKRMent, "", "", "", "", 'S', MessagesController.chatBotID);
                            Debug.WriteLine("INSERT QUERY RESULT : " + dbResult.ToString());

                            DateTime endTime = DateTime.Now;

                            Debug.WriteLine("USER NUMBER : " + context.Activity.Conversation.Id);
                            Debug.WriteLine("CUSTOMMER COMMENT KOREAN : " + messgaeText.Replace("코나 ", ""));
                            Debug.WriteLine("CUSTOMMER COMMENT ENGLISH : " + translateInfo.data.translations[0].translatedText.Replace("&#39;", "'"));
                            Debug.WriteLine("CHANNEL_ID : " + context.Activity.ChannelId);
                            Debug.WriteLine("프로그램 수행시간 : {0}/ms", ((endTime - startTime).Milliseconds));

                            //int inserResult = db.insertHistory(context.Activity.Conversation.Id, messgaeText.Replace("코나 ", ""), translateInfo.data.translations[0].translatedText.Replace("&#39;", "'"), "SEARCH", context.Activity.ChannelId, ((endTime - startTime).Milliseconds), MessagesController.userData.GetProperty<int>("appID"));
                            int inserResult = db.insertHistory(context.Activity.Conversation.Id, messgaeText, "SEARCH", context.Activity.ChannelId, ((endTime - startTime).Milliseconds), MessagesController.chatBotID);
                            if (inserResult > 0)
                            {
                                Debug.WriteLine("HISTORY RESULT SUCCESS");
                            }
                            else
                            {
                                Debug.WriteLine("HISTORY RESULT FAIL");
                            }
                            HistoryLog("[ SEARCH ] ==>> userID :: [ " + context.Activity.Conversation.Id + " ]       message :: [ " + messgaeText.Replace("코나 ", "") + " ]       date :: [ " + DateTime.Now + " ]");
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("Error 발생=" + status);
                        await this.SendSorryMessageAsync(context);
                    }

                    context.Done(messgaeText);
                }
            }
            else
            {
                await this.SendSorryMessageAsync(context);
            }
            context.Done <IMessageActivity>(null);
        }