Exemplo n.º 1
0
        public IHttpActionResult POST()
        {
            try
            {
                // 設定ChannelAccessToken(或抓取Web.Config)
                this.ChannelAccessToken = channelAccessToken;
                // 取得Line Event(範例,只取第一個)
                //var LineEvent = this.ReceivedMessage.events.FirstOrDefault();
                // 取得Line Event
                foreach (var LineItem in this.ReceivedMessage.events)
                {
                    //配合Line verify
                    if (LineItem.replyToken == "00000000000000000000000000000000")
                    {
                        continue;
                    }

                    //回覆訊息
                    string responseText = string.Empty;
                    switch (LineItem.type.ToLower())
                    {
                    case "join":
                        #region Join
                        responseText = "有人把我加入" + LineItem.source.type + "中了,大家好啊~";
                        // 回覆用戶
                        this.ReplyMessage(LineItem.replyToken, responseText);
                        #endregion
                        break;

                    case "message":
                        #region Message
                        switch (LineItem.message.type.ToLower())
                        {
                        case "text":         //收到文字
                            if (LineItem.message.text == "bye")
                            {
                                // 回覆用戶
                                this.ReplyMessage(LineItem.replyToken, "bye-bye");
                                // 離開
                                if (string.Equals(LineItem.source.type, "room", StringComparison.OrdinalIgnoreCase))
                                {
                                    isRock.LineBot.Utility.LeaveRoom(LineItem.source.roomId, ChannelAccessToken);
                                }
                                if (string.Equals(LineItem.source.type, "group", StringComparison.OrdinalIgnoreCase))
                                {
                                    isRock.LineBot.Utility.LeaveGroup(LineItem.source.groupId, ChannelAccessToken);
                                }
                                break;
                            }

                            // 取得用戶名稱
                            LineUserInfo UserInfo = null;
                            if (string.Equals(LineItem.source.type, "room", StringComparison.OrdinalIgnoreCase))
                            {
                                UserInfo = isRock.LineBot.Utility.GetRoomMemberProfile(
                                    LineItem.source.roomId, LineItem.source.userId, this.ChannelAccessToken);
                            }
                            if (string.Equals(LineItem.source.type, "group", StringComparison.OrdinalIgnoreCase))
                            {
                                UserInfo = isRock.LineBot.Utility.GetGroupMemberProfile(
                                    LineItem.source.groupId, LineItem.source.userId, this.ChannelAccessToken);
                            }
                            if (string.Equals(LineItem.source.type, "user", StringComparison.OrdinalIgnoreCase))
                            {
                                UserInfo = isRock.LineBot.Utility.GetUserInfo(
                                    LineItem.source.userId, this.ChannelAccessToken);

                                if (UserInfo != null)
                                {
                                    try
                                    {
                                        using (UserService userService = new UserService())
                                        {
                                            userService.AddUser(LineItem.source.userId, UserInfo.displayName);
                                        }
                                    }
                                    catch { }
                                }
                            }

                            // 顯示用戶名稱
                            if (UserInfo != null)
                            {
                                responseText = UserInfo.displayName + "\n";
                            }

                            //建立 MsQnAMaker Client
                            var helper      = new isRock.MsQnAMaker.Client(new Uri(EndPoint), QnAKey);
                            var QnAResponse = helper.GetResponse(LineItem.message.text.Trim());
                            var ret         = (from c in QnAResponse.answers
                                               orderby c.score descending
                                               select c
                                               ).Take(1);

                            // 預設
                            responseText += UnknowAnswer;
                            if (ret.FirstOrDefault()?.score > 0)
                            {
                                responseText = ret.FirstOrDefault()?.answer;
                            }

                            //回覆
                            this.ReplyMessage(LineItem.replyToken, responseText);
                            break;

                        case "sticker":         //收到貼圖
                            this.ReplyMessage(LineItem.replyToken, 1, 2);
                            break;

                        case "image":
                            break;

                        case "video":
                            break;

                        case "audio":
                            break;

                        case "file":
                            break;

                        case "location":
                            break;
                        }
                        #endregion
                        break;

                    case "follow":
                        #region Follow
                        // 顯示用戶名稱
                        if (!string.Equals(LineItem.source.type, "user", StringComparison.OrdinalIgnoreCase))
                        {
                            LineUserInfo UserInfo = isRock.LineBot.Utility.GetUserInfo(
                                LineItem.source.userId, ChannelAccessToken);

                            if (UserInfo != null)
                            {
                                try
                                {
                                    using (UserService userService = new UserService())
                                    {
                                        userService.AddUser(LineItem.source.userId, UserInfo.displayName);
                                    }
                                }
                                catch { }
                            }
                        }
                        #endregion
                        break;

                    case "unfollow":
                        #region Unfollow
                        #endregion
                        break;

                    case "leave":
                        #region Leave
                        #endregion
                        break;

                    case "postback":
                        // 抓取postback的data
                        var postdata = LineItem.postback.data;
                        // 剖析postdata
                        var data = System.Web.HttpUtility.ParseQueryString(postdata);
                        // 準備顯示訊息
                        var msg = "哈囉,我收到您的訊息\n";     // 收到訊息
                        foreach (var item in data.AllKeys)
                        {
                            //msg += $" Key:{item} value:{data[item]}";
                            if (item == "type")
                            {
                                switch (data[item])
                                {
                                case "yes":
                                    msg += "很高興您會來我的婚禮,期待與您見面。";
                                    break;

                                case "no":
                                    msg += "很可惜您不會來我的婚禮,但還是謝謝您的祝福。";
                                    break;

                                case "thinking":
                                    msg += "很期待您會來我的婚禮,也謝謝您的祝福。";
                                    break;
                                }
                            }
                        }
                        this.ReplyMessage(LineItem.replyToken, msg);
                        break;

                    case "beacon":
                        break;

                    case "accountlink":
                        break;
                    }
                }

                //response OK
                return(Ok());
            }
            catch (Exception ex)
            {
                //如果發生錯誤,傳訊息給Admin
                this.PushMessage(AdminUserId, "發生錯誤:\n" + ex.Message);
                //response OK
                return(Ok());
            }
        }
Exemplo n.º 2
0
        private void replyMessage(Event lineEvent, string replyToken)
        {
            var eventMessage  = lineEvent.message;
            var eventSource   = lineEvent.source;
            var sourceUserId  = eventSource.userId;
            var sourceRoomId  = eventSource.roomId;
            var sourceGroupId = eventSource.groupId;

            switch (lineEvent.message.type)
            {
            case "text":
                var messageText = eventMessage.text;
                var sourceType  = eventSource.type.ToLower();

                if (messageText != "bye")
                {
                    LineUserInfo userInfo = null;

                    switch (sourceType)
                    {
                    case "room":
                        userInfo = Utility.GetRoomMemberProfile(sourceRoomId, sourceUserId, _channelAccessToken);
                        break;

                    case "group":
                        userInfo = Utility.GetGroupMemberProfile(sourceGroupId, sourceUserId, _channelAccessToken);
                        break;

                    case "user":
                        userInfo = Utility.GetUserInfo(sourceUserId, _channelAccessToken);
                        break;

                    default:
                        break;
                    }

                    bot.ReplyMessage(replyToken, "你說了:" + messageText + "\n你是:" + userInfo.displayName);
                }
                else
                {
                    bot.ReplyMessage(replyToken, "bye-bye");

                    if (sourceType == "room")
                    {
                        Utility.LeaveRoom(sourceRoomId, _channelAccessToken);
                    }

                    if (sourceType == "group")
                    {
                        Utility.LeaveGroup(sourceGroupId, _channelAccessToken);
                    }
                }

                break;

            case "sticker":
                bot.ReplyMessage(replyToken, eventMessage.packageId, eventMessage.stickerId);
                break;

            default:
                break;
            }
        }
        IHttpActionResult replyMessage(Event lineEvent)
        {
            var messageType = lineEvent.message.type;
            var replayToken = lineEvent.replyToken;

            switch (messageType)
            {
            case "text":
                var sourceType   = lineEvent.source.type.ToLower();
                var receivedText = lineEvent.message.text;

                if (receivedText == "bye")
                {
                    bot.ReplyMessage(replayToken, "bye-bye");

                    if (sourceType == "room")
                    {
                        Utility.LeaveRoom(lineEvent.source.roomId, channelAccessToken);
                    }

                    if (sourceType == "group")
                    {
                        Utility.LeaveGroup(lineEvent.source.groupId, channelAccessToken);
                    }
                }
                else
                {
                    LineUserInfo userInfo        = null;
                    var          responseMessage = "你說了:" + receivedText;

                    switch (sourceType)
                    {
                    case "room":
                        userInfo = Utility.GetRoomMemberProfile(lineEvent.source.roomId, lineEvent.source.userId, channelAccessToken);
                        break;

                    case "group":
                        userInfo = Utility.GetGroupMemberProfile(lineEvent.source.groupId, lineEvent.source.userId, channelAccessToken);
                        break;

                    case "user":
                        userInfo = Utility.GetUserInfo(lineEvent.source.userId, channelAccessToken);
                        break;

                    default:
                        break;
                    }

                    responseMessage += "\n你是:" + userInfo.displayName;

                    bot.ReplyMessage(replayToken, responseMessage);
                }

                break;

            case "sticker":
                var packageId = lineEvent.message.packageId;
                var stickerId = lineEvent.message.stickerId;

                bot.ReplyMessage(replayToken, packageId, stickerId);

                break;

            default:
                break;
            }

            return(Ok());
        }
Exemplo n.º 4
0
 public Task PushMessageAsync(ILineMessage lineMessage, LineUserInfo userInfo)
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 5
0
        public IHttpActionResult POST()
        {
            //todo:請換成你自己的token
            string ChannelAccessToken = "!!!!!!請換成你自己的token!!!!";

            try
            {
                var    item    = this.ReceivedMessage.events.FirstOrDefault();
                string Message = "";

                switch (item.type)
                {
                case "join":
                    Message = $"有人把我加入{item.source.type}中了,大家好啊~";

                    //回覆用戶
                    isRock.LineBot.Utility.ReplyMessage(ReceivedMessage.events[0].replyToken, Message, ChannelAccessToken);
                    break;

                case "message":
                    if (item.message.text == "bye")
                    {
                        //回覆用戶
                        isRock.LineBot.Utility.ReplyMessage(item.replyToken, "bye-bye", ChannelAccessToken);
                        //離開
                        if (item.source.type.ToLower() == "room")
                        {
                            isRock.LineBot.Utility.LeaveRoom(item.source.roomId, ChannelAccessToken);
                        }
                        if (item.source.type.ToLower() == "group")
                        {
                            isRock.LineBot.Utility.LeaveGroup(item.source.roomId, ChannelAccessToken);
                        }

                        break;
                    }
                    Message = "你說了:" + ReceivedMessage.events[0].message.text;
                    //取得用戶名稱
                    LineUserInfo UserInfo = null;
                    if (item.source.type.ToLower() == "room")
                    {
                        UserInfo = isRock.LineBot.Utility.GetRoomMemberProfile(
                            item.source.roomId, item.source.userId, ChannelAccessToken);
                    }
                    if (item.source.type.ToLower() == "group")
                    {
                        UserInfo = isRock.LineBot.Utility.GetGroupMemberProfile(
                            item.source.groupId, item.source.userId, ChannelAccessToken);
                    }
                    //顯示用戶名稱
                    if (item.source.type.ToLower() != "user")
                    {
                        Message += "\n你是:" + UserInfo.displayName;
                    }

                    //回覆用戶
                    isRock.LineBot.Utility.ReplyMessage(item.replyToken, Message, ChannelAccessToken);
                    break;

                default:
                    break;
                }

                //回覆API OK
                return(Ok());
            }

            catch (Exception ex)
            {
                //todo:請自行處理exception
                return(Ok());
            }
        }
Exemplo n.º 6
0
        public IHttpActionResult POST()
        {
            // TODO:請換成你自己的token
            //this.ChannelAccessToken = "";

            try
            {
                // 回覆訊息
                StringBuilder sbMessage = new StringBuilder();
                var           item      = this.ReceivedMessage.events.FirstOrDefault();

                //用戶傳來message的type
                //sbMessage.Append("收到的 event 的類型為:").AppendLine(item.type);

                switch (item.type)
                {
                case "join":
                    sbMessage.Append("有人把我加入").Append(item.source.type).AppendLine("中了,大家好啊~");
                    // 回覆用戶
                    this.ReplyMessage(ReceivedMessage.events[0].replyToken, sbMessage.ToString());
                    break;

                case "message":
                    if (item.message.text == "bye")
                    {
                        // 回覆用戶
                        this.ReplyMessage(item.replyToken, "bye-bye");
                        // 離開
                        if (string.Equals(item.source.type, "room", StringComparison.OrdinalIgnoreCase))
                        {
                            isRock.LineBot.Utility.LeaveRoom(item.source.roomId, ChannelAccessToken);
                        }
                        if (string.Equals(item.source.type, "group", StringComparison.OrdinalIgnoreCase))
                        {
                            isRock.LineBot.Utility.LeaveGroup(item.source.roomId, ChannelAccessToken);
                        }

                        break;
                    }
                    sbMessage.Append("你說了:").AppendLine(ReceivedMessage.events[0].message.text);
                    // 取得用戶名稱
                    LineUserInfo UserInfo = null;
                    if (string.Equals(item.source.type, "room", StringComparison.OrdinalIgnoreCase))
                    {
                        UserInfo = isRock.LineBot.Utility.GetRoomMemberProfile(
                            item.source.roomId, item.source.userId, this.ChannelAccessToken);
                    }

                    if (string.Equals(item.source.type, "group", StringComparison.OrdinalIgnoreCase))
                    {
                        UserInfo = isRock.LineBot.Utility.GetGroupMemberProfile(
                            item.source.groupId, item.source.userId, this.ChannelAccessToken);
                    }
                    // 顯示用戶名稱
                    if (!string.Equals(item.source.type, "user", StringComparison.OrdinalIgnoreCase))
                    {
                        sbMessage.Append("\n你是:").AppendLine(UserInfo.displayName);
                    }

                    // 回覆用戶
                    this.ReplyMessage(item.replyToken, sbMessage.ToString());
                    break;

                default:
                    break;
                }

                // 回覆API OK
                return(Ok());
            }
            catch (Exception ex)
            {
                //回覆訊息
                string message = "我錯了,錯在 " + ex.Message;

                //回覆用戶
                this.PushMessage(AdminUserId, message);
                return(Ok());
            }
        }
 public async Task PushMessageAsync(ILineMessage lineMessage, LineUserInfo userInfo)
 {
     StringContent stringContent = lineMessage.GenerateStringContent();
 }
        public IHttpActionResult POST()
        {
            try
            {
                this.ChannelAccessToken = channelAccessToken;
                //取得Line Event(範例,只取第一個)
                var LineEvent = this.ReceivedMessage.events.FirstOrDefault();
                //配合Line verify
                if (LineEvent.replyToken == "00000000000000000000000000000000")
                {
                    return(Ok());
                }

                DateTime time = DateTime.UtcNow.AddHours(8);

                string       userId   = LineEvent.source.userId;
                string       groupId  = LineEvent.source.groupId;
                LineUserInfo UserInfo = null;

                //回覆訊息
                if (LineEvent.type == "message")
                {
                    if (LineEvent.message.type == "text" && LineEvent.source.groupId != null)
                    {
                        UserInfo = isRock.LineBot.Utility.GetGroupMemberProfile(groupId, userId, channelAccessToken);
                        //使用者ID和群組ID

                        LineGroupService lineGroupService = new LineGroupService(groupId);
                        if (lineGroupService.SearchLineGroup())  //尋找群組
                        {
                            //取得正在執行的活動
                            CampaignService campaignService = new CampaignService();
                            List <Campaign> campaigns       = campaignService.GetWorkingCampaign(groupId);
                            foreach (Campaign campaign in campaigns)
                            {
                                //取得留言數量(組)
                                ////因為目前Line團購只有+1+2的關鍵字,所以在第三個參數(keywordPattern)寫+1的Pattern
                                int number = CommentFilterService.KeywordFilter(LineEvent.message.text, campaign.Keyword, "+1");
                                if (number != 0 && number <= campaign.ProductGroup)
                                {
                                    //將搜尋到或新增的Customer存在lineCustomer裡
                                    LineCustomerViewModel lineCustomer = new LineCustomerViewModel();
                                    //搜尋是此訊息的人是否已存在LineCustomer資料表中
                                    if (!BotService.SearchLineCustomer(userId, UserInfo.displayName, ref lineCustomer))
                                    {
                                        //否,新增一筆
                                        lineCustomer = BotService.InsertLineCustomer(userId, UserInfo.displayName);
                                    }

                                    //開始建訂單
                                    GroupOrderViewModel groupOrder        = new GroupOrderViewModel();
                                    GroupOrderService   groupOrderService = new GroupOrderService();
                                    Product             product           = new Product();
                                    product = ProductService.GetProductById(campaign.ProductID);
                                    DateTime messageDateTime = BotService.TimestampToDateTime(LineEvent.timestamp);

                                    //若此留言要成單,所需的成團數量空間
                                    int remaningNumber = campaign.ProductGroup - number;
                                    //如果訂單人數還未滿,就拿此單來用,否則建新的
                                    if (groupOrderService.GetGroupOrder(campaign.CampaignID, remaningNumber, ref groupOrder))
                                    {
                                        decimal amount = product.UnitPrice * number;
                                        groupOrderService.InsertGroupOrder(campaign.CampaignID, messageDateTime, campaign.ProductGroup);
                                        groupOrderService.GetGroupOrder(campaign.CampaignID, remaningNumber, ref groupOrder);
                                    }

                                    //條件都達成,開始下單
                                    GroupOrderDetail groupOrderDetail = new GroupOrderDetail()
                                    {
                                        GroupOrderID    = groupOrder.GroupOrderID,
                                        LineCustomerID  = lineCustomer.LineCustomerID,
                                        ProductName     = product.ProductName,
                                        UnitPrice       = product.UnitPrice,
                                        Quantity        = number,
                                        MessageDateTime = messageDateTime
                                    };
                                    GroupOrderDetailService groupOrderDetailService = new GroupOrderDetailService();
                                    groupOrderDetailService.InsertGroupOrderDetail(groupOrderDetail);

                                    //更新清單資料
                                    int     currentNumberOfProduct = groupOrder.NumberOfProduct + number;
                                    decimal Amount  = groupOrder.Amount + groupOrderDetail.UnitPrice * groupOrderDetail.Quantity;
                                    bool    isGroup = false;
                                    if (currentNumberOfProduct == campaign.ProductGroup)
                                    {
                                        isGroup = true;
                                    }
                                    groupOrderService.UpdateGroupOrder(groupOrder.GroupOrderID, currentNumberOfProduct, Amount, isGroup);
                                    this.ReplyMessage(LineEvent.replyToken, "感謝" + UserInfo.displayName + "的下標!等待活動結束後會一併通知團購成功名單");
                                    break;
                                }
                            }
                        }
                    }
                    if (LineEvent.message.type == "sticker")
                    {
                        return(Ok());
                    }
                    if (LineEvent.message.type == "image")
                    {
                        return(Ok());
                    }
                }
                if (LineEvent.type == "join")
                {
                    DateTime timestampTotime = BotService.TimestampToDateTime(LineEvent.timestamp);

                    LineGroupService lineGroupService = new LineGroupService(groupId);

                    var linegroup = lineGroupService.GetGroupByID();
                    //新的群組
                    if (linegroup == null)
                    {
                        List <CompareStoreManager> managerId = LineBindingService.GroupNullCompare();
                        foreach (var item in managerId)
                        {
                            StoreMeanger checkProfile = BotService.CheckMeanger(groupId, item.LineID);
                            if (checkProfile.message != "Not found")
                            {
                                LineBindingService.CompareUpdateGroupid(groupId, item.StoreManagerID, timestampTotime);
                            }
                        }
                    }
                    else
                    {
                        var nullGroup = LineBindingService.GetNullGroup(linegroup.StoreManagerID);
                        //群組名字一樣,舊的改狀態新的null刪掉
                        if (nullGroup.Count == 0)
                        {
                            LineBindingService.UpdateBotGroupStatus(linegroup.GroupID, "True", timestampTotime);
                        }
                        else if (linegroup.GroupName == nullGroup.FirstOrDefault().GroupName)
                        {
                            LineBindingService.UpdateBotGroupStatus(linegroup.GroupID, "True", timestampTotime);
                            LineBindingService.DelNullGroup(nullGroup.FirstOrDefault().GroupID);
                        }
                        //群組名字不一樣,新的增加
                        else if (linegroup.GroupName != nullGroup.FirstOrDefault().GroupName)
                        {
                            LineBindingService.UpdateBotGroup(nullGroup.FirstOrDefault().GroupID, groupId, "True", timestampTotime);
                        }
                    }
                }
                if (LineEvent.type == "leave")
                {
                    int id = LineBindingService.GetIdByGroupId(groupId);
                    if (id != 0)
                    {
                        LineBindingService.UpdateGroupStatus(id, "False");
                    }
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                foreach (var AdminUserId in AdminUser)
                {
                    this.PushMessage(AdminUserId, "發生錯誤:\n" + ex.Message);
                }

                return(Ok());
            }
        }
Exemplo n.º 9
0
        public async Task <IHttpActionResult> POSTAsync()
        {
            try
            {
                //取得 http Post RawData(should be JSON)
                postData = Request.Content.ReadAsStringAsync().Result;
                //剖析JSON
                ReceivedMessage = isRock.LineBot.Utility.Parsing(postData);
                //建立 Line BOT
                LintBot = new isRock.LineBot.Bot(ChannelAccessToken);
                //取得 User 的資訊
                userInfo = LintBot.GetUserInfo(ReceivedMessage.events.FirstOrDefault().source.userId);
                switch (userInfo.displayName.Trim())
                {
                case "熊寶寶":
                    username = "******";
                    break;

                case "蔡福元":
                    username = "******";
                    break;

                case "Maggie":
                    username = "******";
                    break;

                default:
                    break;
                }
                //取得 User 所 PO 的訊息
                string userMsg = ReceivedMessage.events[0].message.text;

                //新朋友來了(或解除封鎖)
                if (ReceivedMessage.events.FirstOrDefault().type == "follow" || ReceivedMessage.events.FirstOrDefault().type == "join")
                {
                    NewJoin();
                }

                //專門處理關鍵字 - "/ShowMyID"
                if (userMsg.ToUpper().Contains("/SHOWMYID"))
                {
                    ShowMyID();
                }

                //專門處理關鍵字 - "PM2.5"
                if (userMsg.ToUpper().Contains("PM2.5") || userMsg.Contains("空氣品質") || userMsg.Contains("空污"))
                {
                    string getmsg = await CallFunction.GetAirQulity(userMsg.ToUpper());

                    isRock.LineBot.Utility.ReplyMessage(ReceivedMessage.events[0].replyToken, getmsg, ChannelAccessToken);
                    //LintBot.ReplyMessage(ReceivedMessage.events[0].replyToken, pm25);
                }

                //專門處理關鍵字 - "股價 / 股票"
                if (userMsg.ToUpper().Contains("股價") || userMsg.Contains("股票"))
                {
                    GetStock(userMsg.ToUpper());
                }

                //專門處理關鍵字 - "股價 / 股票"
                if (userMsg.ToUpper().Contains("匯率"))
                {
                    string getmsg = CallFunction.GetExchange(userMsg.ToUpper());
                    isRock.LineBot.Utility.ReplyMessage(ReceivedMessage.events[0].replyToken, getmsg, ChannelAccessToken);
                }

                ////專門處理 Q & A :前置字元為"熊熊:"
                //if (userMsg.Contains("熊熊:") || userMsg.Contains("熊熊,"))
                //{
                //    QNAMaker(userMsg);
                //}

                // 先處理以上含有特殊關鍵字,若未含特殊關鍵字就丟 Q&A (不用再判斷是否有"熊熊,"開頭)
                QNAMaker(userMsg);

                //若 Q&A 沒有處理到,就專門處理關鍵字 - "里長嬤" or "里長伯"
                if (userMsg.Contains("里長嬤"))
                {
                    District("里長嬤");
                }
                if (userMsg.Contains("里長伯"))
                {
                    District("里長伯");
                }
                //回覆API OK
                return(Ok());
            }
            catch (Exception ex)
            {
                return(InternalServerError(new Exception("Error : " + ex.Message.ToString())));
            }
        }
Exemplo n.º 10
0
        public IHttpActionResult POST()
        {
            string ChannelAccessToken = "WJ10DIkt+Y8abCGbAb/OmK/35F3iZ3h4xiB3CE8/B6SzkfTg4mLGonn/9nVI/P33o6+SnGwSBtKYjfa65YJSdfskV7Lf5RtWUAEmZajgARKdJva3ufd3cn7i/H4F/FXA685e75j18IsFjwDgSmugcQdB04t89/1O/w1cDnyilFU=";

            Microsoft.Cognitive.LUIS.LuisClient lc = new Microsoft.Cognitive.LUIS.LuisClient("ac6c1ff9-b031-4eff-bf31-442a202b1038", "61c5bbfb4ac5435b8f839a9528d50a46", true, "westus");

            Bot    LineBot  = new Bot(ChannelAccessToken);
            string postData = Request.Content.ReadAsStringAsync().Result;
            //剖析JSON
            var ReceivedMessage = Utility.Parsing(postData);
            var ReplyToken      = ReceivedMessage.events[0].replyToken;

            //取得用戶名稱
            //var UserName = LineBot.GetUserInfo(ReceivedMessage.events.FirstOrDefault().source.userId);

            //取得用戶ID
            var UserId = ReceivedMessage.events.FirstOrDefault().source.userId;
            //取得聊天室ID
            var RoomId = ReceivedMessage.events.FirstOrDefault().source.roomId;
            //取得群組ID
            var GroupId = ReceivedMessage.events.FirstOrDefault().source.groupId;
            var item    = ReceivedMessage.events[0];

            var weather_api = "https://works.ioa.tw/weather/api/all.json";

            try
            {
                LineUserInfo UserInfo = null;
                if (ReceivedMessage.events[0].type == "message")
                {
                    if (ReceivedMessage.events[0].message.type == "text")
                    {
                        var UserSays   = ReceivedMessage.events[0].message.text;
                        var LuisResult = lc.Predict(UserSays).Result;

                        if (UserSays == "安靜")
                        {
                            Global.quiet = true;
                            LineBot.ReplyMessage(ReplyToken, "找蟹安靜!!!");
                        }
                        else if (UserSays == "說話")
                        {
                            Global.quiet = false;
                        }

                        if (UserSays == "狀態")
                        {
                            if (Global.quiet == true)
                            {
                                LineBot.ReplyMessage(ReplyToken, "目前為安靜狀態");
                            }
                            else
                            {
                                LineBot.ReplyMessage(ReplyToken, "目前為說話狀態");
                            }
                        }
                        if (LuisResult.TopScoringIntent.Name == "詢問天氣" && LuisResult.TopScoringIntent.Score > 0.8)
                        {
                            if (LuisResult.Entities.FirstOrDefault().Value.FirstOrDefault().Value == "淡水")
                            {
                                Global.id   = 50;
                                Global.city = "淡水";
                            }
                            else if (LuisResult.Entities.FirstOrDefault().Value.FirstOrDefault().Value == "北投")
                            {
                                Global.id   = 9;
                                Global.city = "北投";
                            }

                            var town_weather = "https://works.ioa.tw/weather/api/weathers/" + Global.id + ".json";

                            WebClient wc = new WebClient();
                            wc.Encoding = Encoding.UTF8;

                            string  jsonStr = wc.DownloadString(town_weather);
                            JObject obj     = JsonConvert.DeserializeObject <JObject>(jsonStr);

                            var desc          = "";
                            var temperature   = "";
                            var felt_air_temp = "";
                            var humidity      = "";
                            var rainfall      = "";
                            var sunrise       = "";
                            var sunset        = "";
                            var at            = "";

                            desc          = obj["desc"].ToString();
                            temperature   = obj["temperature"].ToString();
                            felt_air_temp = obj["felt_air_temp"].ToString();
                            humidity      = obj["humidity"].ToString();
                            rainfall      = obj["rainfall"].ToString();
                            sunrise       = obj["sunrise"].ToString();
                            sunset        = obj["sunset"].ToString();
                            at            = obj["at"].ToString();
                            LineBot.ReplyMessage(ReplyToken, Global.city + "\n" + "天氣:" + desc + "\n" + "溫度:" + temperature + "度\n" + "體感溫度:" + felt_air_temp + "度\n" + "雨量:" + rainfall + "\n" + "日出時間:" + sunrise + "\n" + "日落時間:" + sunset + "\n" + "最後更新時間:" + at + "\n" + "資料每30分鐘更新");
                        }
                        else if (ReceivedMessage.events[0].message.type == "text")
                        {
                            if (UserSays == "滾")
                            {
                                if (ReceivedMessage.events[0].source.type == "user")
                                {
                                    LineBot.PushMessage(UserId, "滾屁");
                                }
                                else if (ReceivedMessage.events[0].source.type == "room")
                                {
                                    UserInfo = Utility.GetRoomMemberProfile(RoomId, UserId, ChannelAccessToken);
                                    LineBot.PushMessage(RoomId, $"{UserInfo.displayName},我記住你了\n掰掰");
                                    Utility.LeaveRoom(RoomId, ChannelAccessToken);
                                }
                                else if (ReceivedMessage.events[0].source.type == "group")
                                {
                                    UserInfo = Utility.GetGroupMemberProfile(GroupId, UserId, ChannelAccessToken);
                                    LineBot.PushMessage(GroupId, $"{UserInfo.displayName},我記住你了\n掰掰");
                                    Utility.LeaveGroup(GroupId, ChannelAccessToken);
                                }
                            }

                            /*WebClient wc = new WebClient();
                             * wc.Encoding = Encoding.UTF8;
                             *
                             * string jsonStr = wc.DownloadString(weather_api);
                             *
                             * JArray array = JsonConvert.DeserializeObject<JArray>(jsonStr);
                             *
                             * int i=0, j=0;
                             *
                             * JObject obj = (JObject)array[i];
                             *
                             * var name = obj["name"].ToString();
                             * var towns = obj["towns"][j]["name"].ToString();
                             *
                             * LineBot.PushMessage(UserId, name + "\n" + towns);*/
                        }
                        if (Global.quiet == true)
                        {
                        }
                        else if (Global.quiet == false)
                        {
                            if (ReceivedMessage.events[0].message.type == "text")
                            {
                                if (LuisResult.TopScoringIntent.Name == "尋找葛格" && LuisResult.TopScoringIntent.Score > 0.8)
                                {
                                    LineBot.ReplyMessage(ReplyToken, "嘿嘿嘿!怎麼啦?\n需要葛格提供你什麼服務嗎");
                                    if (ReceivedMessage.events[0].source.type == "user")
                                    {
                                        LineBot.PushMessage(UserId, $"這是一個天氣預報機器人\n在群組或聊天室裡說'滾'我就會離開喔\n希望能幫到你");
                                        LineBot.PushMessage(UserId, 1, 2);
                                    }
                                    else if (ReceivedMessage.events[0].source.type == "room")
                                    {
                                        LineBot.PushMessage(RoomId, $"這是一個天氣預報機器人\n在群組或聊天室裡說'滾'我就會離開喔\n希望能幫到你");
                                        LineBot.PushMessage(RoomId, 1, 2);
                                    }
                                    else if (ReceivedMessage.events[0].source.type == "group")
                                    {
                                        LineBot.PushMessage(GroupId, $"這是一個天氣預報機器人\n在群組或聊天室裡說'滾'我就會離開喔\n希望能幫到你");
                                        LineBot.PushMessage(GroupId, 1, 2);
                                    }
                                }
                                else if (LuisResult.TopScoringIntent.Name == "None" || LuisResult.TopScoringIntent.Score < 0.8)
                                {
                                    if (ReceivedMessage.events[0].source.type == "user")
                                    {
                                        LineBot.ReplyMessage(ReplyToken, UserSays);
                                    }
                                    else if (ReceivedMessage.events[0].source.type == "room")
                                    {
                                        LineBot.ReplyMessage(ReplyToken, UserSays);
                                    }
                                    else if (ReceivedMessage.events[0].source.type == "group")
                                    {
                                        LineBot.ReplyMessage(ReplyToken, UserSays);
                                    }
                                }
                            }
                        }
                    }
                    else if (ReceivedMessage.events[0].message.type == "sticker")
                    {
                        if (Global.quiet == true)
                        {
                        }
                        else if (Global.quiet == false)
                        {
                            string botMessage = "機器人看不懂貼圖你還傳";
                            if (ReceivedMessage.events[0].source.type == "user")
                            {
                                LineBot.PushMessage(UserId, botMessage);
                                LineBot.PushMessage(UserId, 3, 185);
                            }
                            else if (ReceivedMessage.events[0].source.type == "room")
                            {
                                LineBot.PushMessage(RoomId, botMessage);
                                LineBot.PushMessage(RoomId, 3, 185);
                            }
                            else if (ReceivedMessage.events[0].source.type == "group")
                            {
                                LineBot.ReplyMessage(ReplyToken, botMessage);
                                LineBot.PushMessage(GroupId, 3, 185);
                            }
                        }
                    }
                }
                else if (ReceivedMessage.events[0].type == "follow")
                {
                    UserInfo = Utility.GetUserInfo(ReceivedMessage.events[0].source.userId, ChannelAccessToken);
                    LineBot.PushMessage(UserId, $"{UserInfo.displayName},我來了!!!");
                }
                else if (ReceivedMessage.events[0].type == "join")
                {
                    if (ReceivedMessage.events[0].source.type == "room")
                    {
                        LineBot.PushMessage(RoomId, $"我來了!!!");
                    }
                    else if (ReceivedMessage.events[0].source.type == "group")
                    {
                        LineBot.PushMessage(GroupId, $"我來了!!!");
                    }
                }
                else
                {
                    string Message = ReceivedMessage.events[0].type;
                    LineBot.ReplyMessage(ReplyToken, postData);
                }
                //回覆API OK
                return(Ok());
            }
            catch (Exception ex)
            {
                string Message = "我錯了,錯在\n" + ex.Message;
                //回覆用戶
                LineBot.ReplyMessage(ReplyToken, Message);
                return(Ok());
            }
        }
Exemplo n.º 11
0
        public IHttpActionResult webhook()
        {
            string ChannelAccessToken = "pm8zf310EYYHjvJEkM347wenUZDiP8IBf/lMfqeoBIroaBQkcyNcg2Me+dQR1lmVDRBPatCB0MjIanxkFa8taRPYX9g+GcmeEuWfz2hf8Gx4SZcxRiYMLcjFVmpw3GhkejYKTkJX/uqjQoDndGNo9wdB04t89/1O/w1cDnyilFU=";

            try
            {
                this.ChannelAccessToken = ChannelAccessToken;
                string Message = "";
                var    item    = this.ReceivedMessage.events.FirstOrDefault();
                isRock.LineBot.Event LineEvent = null;

                LineUserInfo UserInfo = null;
                if (item.source.type.ToLower() == "room")
                {
                    UserInfo = Utility.GetRoomMemberProfile(
                        item.source.roomId, item.source.userId, ChannelAccessToken);
                }
                if (item.source.type.ToLower() == "group")
                {
                    UserInfo = Utility.GetGroupMemberProfile(
                        item.source.groupId, item.source.userId, ChannelAccessToken);
                }
                if (item.source.type.ToLower() == "user")
                {
                    UserInfo = Utility.GetUserInfo(item.source.userId, ChannelAccessToken);
                }

                if (item != null)
                {
                    switch (item.type)
                    {
                    case "join":
                        //Message = $"有人把我加入{item.source.type}中了,大家好啊~";
                        Message = $"初次見面多多指教,大家好ㄛ~";
                        //回覆用戶
                        Utility.ReplyMessage(ReceivedMessage.events[0].replyToken, Message, ChannelAccessToken);
                        break;

                    case "message":
                        int question_id = service.HaveQuestion(item.source.userId);
                        if (question_id != 0)
                        {
                            MessageAction[] actions  = null;
                            var             msgArray = service.NextQuestion(item.source.userId, ReceivedMessage.events[0].message.text).Split(',');
                            isRock.LineBot.ButtonsTemplate ButtonTemplate = null;
                            switch (msgArray[1])
                            {
                            case "1":
                                actions = new MessageAction[]
                                {
                                    new MessageAction {
                                        label = "威秀影城", text = "威秀"
                                    },
                                    new MessageAction {
                                        label = "國賓影城", text = "國賓"
                                    }
                                };
                                ButtonTemplate = GetButtonsTemplate(msgArray[0], msgArray[0], $"請選擇要查詢之戲院", actions);
                                Utility.ReplyTemplateMessage(item.replyToken, ButtonTemplate, ChannelAccessToken);
                                break;

                            case "2":
                                if (msgArray[2] == "VS")
                                {
                                    actions = new MessageAction[]
                                    {
                                        new MessageAction {
                                            label = "京站威秀", text = "京站"
                                        },
                                        new MessageAction {
                                            label = "信義威秀", text = "信義"
                                        },
                                        new MessageAction {
                                            label = "日新威秀", text = "日新"
                                        },
                                        new MessageAction {
                                            label = "板橋大遠百威秀", text = "板橋大遠百"
                                        }
                                    };
                                    ButtonTemplate = GetButtonsTemplate(msgArray[0], "請點選下方戲院", msgArray[0], actions);
                                    Utility.ReplyTemplateMessage(item.replyToken, ButtonTemplate, ChannelAccessToken);
                                }
                                else if (msgArray[2] == "AT")
                                {
                                    actions = new MessageAction[]
                                    {
                                        new MessageAction {
                                            label = "西門國賓", text = "西門國賓"
                                        },
                                        new MessageAction {
                                            label = "威風國賓", text = "威風國賓"
                                        },
                                        new MessageAction {
                                            label = "長春國賓", text = "長春國賓"
                                        },
                                        new MessageAction {
                                            label = "中和環球國賓", text = "中和環球國賓"
                                        }
                                    };
                                    ButtonTemplate = GetButtonsTemplate(msgArray[0], "請點選下方戲院地點(林口國賓、新莊國賓請直接輸入)", msgArray[0], actions);
                                    Utility.ReplyTemplateMessage(item.replyToken, ButtonTemplate, ChannelAccessToken);
                                }
                                break;

                            default:
                                Utility.ReplyMessage(item.replyToken, msgArray[0], ChannelAccessToken);
                                break;
                            }
                        }

                        if (item.message.type.ToLower() == "image")
                        {
                            if (imageService.isUploading(item.source.userId))
                            {
                                var byteArray = Utility.GetUserUploadedContent(item.message.id, ChannelAccessToken);
                                var link      = imageService.UploadImage(byteArray, item.source.userId, UserInfo.displayName);
                                isRock.LineBot.TextMessage  textMessage  = new isRock.LineBot.TextMessage("---Completed!---");
                                isRock.LineBot.ImageMessage imageMessage = new isRock.LineBot.ImageMessage(new Uri(link), new Uri(link));
                                var Messages = new List <MessageBase>();
                                Messages.Add(textMessage);
                                Messages.Add(imageMessage);
                                this.ReplyMessage(item.replyToken, Messages);
                            }
                        }
                        else if (item.message.type.ToLower() == "text")
                        {
                            switch (ReceivedMessage.events[0].message.text)
                            {
                            case "--exit":
                                Utility.ReplyMessage(item.replyToken, "bye-bye", ChannelAccessToken);

                                //離開
                                if (item.source.type.ToLower() == "room")
                                {
                                    Utility.LeaveRoom(item.source.roomId, ChannelAccessToken);
                                }
                                else if (item.source.type.ToLower() == "group")
                                {
                                    Utility.LeaveGroup(item.source.groupId, ChannelAccessToken);
                                }

                                break;

                            case "--upload":
                                var msg = imageService.addUploadStatus(item.source.userId);
                                if (!string.IsNullOrEmpty(msg))
                                {
                                    Message = msg;
                                    if (UserInfo != null)
                                    {
                                        Message += $"\r\n -Target user: \"{UserInfo.displayName}\"";
                                    }
                                    this.ReplyMessage(item.replyToken, Message);
                                }
                                else
                                {
                                    Message = "Plz try again. :(";
                                }
                                break;

                            case string str when str.Contains("抽老公") || str.Contains("抽帥哥"):
                                string _url = service.GetRandomGuy();

                                if (!string.IsNullOrEmpty(_url))
                                {
                                    isRock.LineBot.ImageMessage imageMessage = new isRock.LineBot.ImageMessage(new Uri(_url), new Uri(_url));
                                    var Messages = new List <MessageBase>();
                                    Messages.Add(imageMessage);
                                    this.ReplyMessage(item.replyToken, Messages);
                                }
                                else
                                {
                                    this.ReplyMessage(item.replyToken, "你沒帥哥或是正在維修中..請洽詢我老闆 :D");
                                }
                                break;

                            case "-help":
                                Message = "抽帥哥圖片(指令:抽帥哥/抽老公)\r\n========\r\n抽動物圖片(指令:抽動物)\r\n========\r\n查詢地方當前溫度(指令:xx氣溫 / xx溫度)\r\n========\r\n查詢星座今日運勢 (指令:xx座運勢)\r\n========\r\n" +
                                          "查詢電影(指令:查詢電影)如果要中斷請輸入\"取消\"\r\n========\r\n近期電影列表(指令:電影列表)";
                                break;

                            case string str when str.Contains("座運勢"):
                                Message = service.GetHoroscope(str.Substring(0, 3));

                                break;

                            case string str when str.Contains("電影列表"):
                                Message = service.GetMovieList();

                                break;

                            case "Hi":
                                Message = "Hello";
                                break;

                            case string str when str.Contains("抽動物"):
                                string ani_url = "https://" + HttpContext.Current.Request.Url.Host + service.GetAnimalImg();

                                Utility.ReplyImageMessage(item.replyToken, ani_url, ani_url, ChannelAccessToken);
                                break;

                            case "查詢電影":
                                var question = service.AddQuestion(item.source.userId);
                                if (question != "")
                                {
                                    MessageAction[] actions =
                                    {
                                        new MessageAction {
                                            label = "威秀影城", text = "威秀"
                                        },
                                        new MessageAction {
                                            label = "國賓影城", text = "國賓"
                                        }
                                    };
                                    var ButtonTemplate = GetButtonsTemplate(question, question, $"{question}", actions);
                                    Utility.ReplyTemplateMessage(item.replyToken, ButtonTemplate, ChannelAccessToken);
                                }
                                else
                                {
                                    Utility.ReplyMessage(item.replyToken, "請先結束當前問題!", ChannelAccessToken);
                                }
                                break;

                            default:
                                break;
                            }
                        }

                        //取得用戶名稱
                        //LineUserInfo UserInfo = null;
                        //if (item.source.type.ToLower() == "room")
                        //    UserInfo = Utility.GetRoomMemberProfile(
                        //        item.source.roomId, item.source.userId, ChannelAccessToken);
                        //if (item.source.type.ToLower() == "group")
                        //    UserInfo = Utility.GetGroupMemberProfile(
                        //        item.source.groupId, item.source.userId, ChannelAccessToken);
                        //顯示用戶名稱
                        //if (item.source.type.ToLower() != "user")
                        //    Message += "\n你是:" + UserInfo.displayName;
                        //回覆用戶
                        if (Message != "")
                        {
                            Utility.ReplyMessage(item.replyToken, Message, ChannelAccessToken);
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                return(Ok(HttpContext.Current.Request.Url.Host));
            }

            return(Ok());
        }
Exemplo n.º 12
0
        public IHttpActionResult POST()
        {
            string ChannelAccessToken = "zZqwp8/TJhZyXzrMdtstYXJV4xAiieUTotHC275jw9tcZF9YDdMYYzSLloWbR7YkGOg73uyzjdyapMD/ArsX5cvZOdY3FosaKxiJY27F89vp/OiPmjOrJgtmaMg1WGJp5XXn/da2ivg1QR8bc2hqRAdB04t89/1O/w1cDnyilFU=";

            try {
                //取得 http Post RawData(should be JSON)
                string postData = Request.Content.ReadAsStringAsync().Result;
                //剖析JSON
                var ReceivedMessage = Utility.Parsing(postData);
                //回覆訊息
                foreach (Event e in ReceivedMessage.events)
                {
                    if (e.source.type == "user")
                    {
                        LineUserInfo user = Utility.GetUserInfo(e.source.userId, ChannelAccessToken);
                        string       Message;
                        switch (e.type)
                        {
                        case "follow":
                            Message = "สวัสดีคุณ" + user.displayName;
                            Utility.ReplyMessage(e.replyToken, Message, ChannelAccessToken);
                            break;

                        case "message":
                            switch (e.message.type)
                            {
                            case "text":
                                //if (e.message.text.ToLower() == "#r") {
                                //    var actions = new List<TemplateActionBase>();
                                //    actions.Add(new MessageActon() {
                                //        label = "Message",
                                //        text = "Text"
                                //    });

                                //    actions.Add(new UriActon() {
                                //        label = "Uri",
                                //        uri = new Uri("http://dev.tks.co.th/ChannelOne/Home/Register?refer=")
                                //    });

                                //    actions.Add(new PostbackActon() {
                                //        label = "postback",
                                //        data = "#r"
                                //    });
                                //    var C = new List<Column>();
                                //    C.Add(new Column() {
                                //        thumbnailImageUrl = new Uri("https://dev.tks.co.th/ChannelOne/Content/img/headTemplateTh.png"),
                                //        text = "กด “ลงทะเบียน” เพื่อไปหน้าลงทะเบียน",
                                //        actions = actions
                                //    });
                                //    C.Add(new Column() {
                                //        thumbnailImageUrl = new Uri("https://dev.tks.co.th/ChannelOne/Content/img/headTemplateEn.png"),
                                //        text = "Press “Register” to continue",
                                //        actions = actions
                                //    });
                                //    var carousel = new CarouselTemplate() {
                                //        altText = "กดลงทะเบียนรับการแจ้งเตือนเอกสารธุระกรรมผ่านช่องทางไลน์ ",
                                //        columns = C
                                //    };
                                //    Utility.PushTemplateMessage(user.userId, carousel, ChannelAccessToken);
                                //} else {
                                Message = "Bot : " + e.message.text;
                                Utility.ReplyMessage(e.replyToken, Message, ChannelAccessToken);
                                //}
                                break;

                            default:
                                Message = "ขอบคุณสำหรับข้อความ!􀄃􀄄blush􏿿\nขออภัย เราไม่สามารถตอบกลับผู้ใช้ เป็นส่วนตัวได้จากบัญชีนี้้􀄃􀄑hm􏿿";
                                Utility.ReplyMessage(e.replyToken, Message, ChannelAccessToken);
                                break;
                            }
                            break;
                        }
                    }
                    //string Message;
                    //Message = "GG:" + e.message.text;
                    //isRock.LineBot.Utility.ReplyMessage(ReceivedMessage.events[0].replyToken, Message, ChannelAccessToken);
                }
                //回覆用戶

                //回覆API OK
                return(Ok());
            } catch (Exception ex) {
                return(Ok());
            }
        }
Exemplo n.º 13
0
        public async Task <IHttpActionResult> POST()
        {
            string postData = Request.Content.ReadAsStringAsync().Result;
            //剖析JSON
            var messageObject = isRock.LineBot.Utility.Parsing(postData).events.FirstOrDefault();

            if (!await VaridateSignature(Request))
            {
                isRock.LineBot.Utility.ReplyMessage(messageObject.replyToken, "驗證失敗", ChannelAccessToken);
                return(Ok());
            }

            //取得user說的話
            string message = messageObject.message.text;
            //回覆訊息
            string reply = string.Empty;
            //Message = "你說了:" + item.message.text;

            string       id       = string.Empty;
            LineUserInfo userInfo = GetUserInfoAndId(messageObject, out id);
            string       ownKey   = userInfo.userId + "Own";
            var          regex    = new Regex("\\D", RegexOptions.IgnoreCase);

            try
            {
                if (message == "大樂透")
                {
                    var numbers  = GetLetou();
                    var letouMsg = Letou.Instance.Compare(numbers);
                    reply  = $"給你一組幸運號碼: {numbers}\\n";
                    reply += letouMsg;
                }
                else if (message == "安安9527" || message == "9527安安" || message == "安安")
                {
                    Utility.ReplyMessageWithJSON(messageObject.replyToken, Demo.Show(), ChannelAccessToken);
                }
                else if (message.Contains("抽"))
                {
                    var beauty = Beauty.GetBeauty();
                    var random = new Random(new Random().Next(1, beauty.Count()));
                    var image  = beauty[random.Next(1, beauty.Count())];
                    Utility.ReplyImageMessage(messageObject.replyToken, image, image, ChannelAccessToken);
                    return(Ok());
                }
                else if (message.Contains("美食"))
                {
                    var eat  = new Eat();
                    var data = await eat.GetEatData(message.Replace("美食", ""));

                    var list = new List <TemplateModel>();

                    var model = new TemplateModel();
                    model.template         = new CarouselModel();
                    model.template.columns = new List <ThumbnailImageModel>();

                    foreach (var item in data.response.Where(x => x.restaurant != null).Take(10))
                    {
                        model.template.columns.Add(new ThumbnailImageModel()
                        {
                            thumbnailImageUrl = item.restaurant.cover_url,
                            title             = item.restaurant.name,
                            text          = item.address,
                            defaultAction = new UriModel()
                            {
                                label = "瀏覽網誌",
                                uri   = item.url.IndexOf('-') > 0 ? item.url.Substring(0, item.url.IndexOf('-')) : item.url
                            },
                            actions = new List <ActionModel>()
                            {
                                new UriModel()
                                {
                                    label = "導航",
                                    uri   = $"https://www.google.com.tw/maps/place/{item.restaurant.address}"
                                }
                            }
                        });
                    }
                    list.Add(model);

                    if (model.template.columns.Count > 0)
                    {
                        Utility.ReplyMessageWithJSON(messageObject.replyToken, JsonConvert.SerializeObject(list), ChannelAccessToken);
                    }
                    else
                    {
                        reply = "查無資料...";
                    }
                }
                else if (message.Contains("天氣"))
                {
                    var area = message.Replace("天氣", "").Replace("台", "臺").Trim();
                    var data = (await Weather.Instance.GetData()).records.location.FirstOrDefault(x => x.locationName.Contains(area));
                    var dic  = new Dictionary <string, string>();
                    foreach (var item in data.weatherElement.OrderBy(x => x.elementName))
                    {
                        foreach (var time in item.time)
                        {
                            var key = $"{time.startTime}~{time.endTime}";
                            if (!dic.Keys.Contains(key))
                            {
                                dic.Add(key, "");
                            }

                            switch (item.elementName)
                            {
                            case "Wx":
                                dic[key] += $"天氣:{time.parameter.parameterName}\\n";
                                break;

                            case "PoP":
                                dic[key] += $"降雨機率:{time.parameter.parameterName}%\\n";
                                break;

                            case "MinT":
                                dic[key] += $"低溫:{time.parameter.parameterName}C\\n";
                                break;

                            case "CI":
                                dic[key] += $"適度:{time.parameter.parameterName}\\n";
                                break;

                            case "MaxT":
                                dic[key] += $"高溫:{time.parameter.parameterName}C\\n";
                                break;

                            default:
                                break;
                            }
                        }
                    }

                    foreach (var item in dic)
                    {
                        reply += $"{item.Key}\\n{item.Value}";
                    }

                    if (reply == string.Empty)
                    {
                        reply = "查無資料... 試試台北天氣";
                    }
                }
                else if (message.ToLower().Contains("ubike"))
                {
                    var data = await UBike.Instance.GetAllData();

                    var mday        = data.FirstOrDefault().mday;
                    var refreshTime = new DateTime(Convert.ToInt16(mday.Substring(0, 4)), Convert.ToInt16(mday.Substring(4, 2)),
                                                   Convert.ToInt16(mday.Substring(6, 2)), Convert.ToInt16(mday.Substring(8, 2)),
                                                   Convert.ToInt16(mday.Substring(10, 2)), Convert.ToInt16(mday.Substring(12, 2)));
                    var location = message.ToLower().Replace("ubike", "").Trim();
                    if (location == "三重家")
                    {
                        foreach (var item in data.Where(x => x.sno == "1008" || x.sno == "1010"))
                        {
                            reply += $"[{item.sarea}-{item.sna}]車{item.sbi}空{item.bemp}\\n";
                        }

                        if (reply == string.Empty)
                        {
                            reply = "查無資料...";
                        }
                        else
                        {
                            reply += $"更新時間{refreshTime.ToString("yyyy/MM/dd HH:mm:ss")}";
                        }
                    }
                    else if (location.Contains("區"))
                    {
                        foreach (var item in data.Where(x => x.sarea == location))
                        {
                            reply += $"[{item.sarea}-{item.sna}]車{item.sbi}空{item.bemp}\\n";
                        }

                        if (reply == string.Empty)
                        {
                            reply = "查無資料...";
                        }
                        else
                        {
                            reply += $"更新時間{refreshTime.ToString("yyyy/MM/dd HH:mm:ss")}";
                        }
                    }
                    else if (location != string.Empty)
                    {
                        foreach (var item in data.Where(x => x.sna.Contains(location)))
                        {
                            reply += $"[{item.sarea}-{item.sna}]車{item.sbi}空{item.bemp}\\n";
                        }

                        if (reply == string.Empty)
                        {
                            reply = "查無資料...";
                        }
                        else
                        {
                            reply += $"更新時間{refreshTime.ToString("yyyy/MM/dd HH:mm:ss")}";
                        }
                    }
                }
                else if (message == "大樂透機率")
                {
                    reply = Letou.Instance.GetHighRateNumbers();
                }
                else if (message.Contains("大樂透"))
                {
                    var numbers = message.Split(' ')?[1];
                    if (numbers != null && numbers.Split(',').Count() == 6)
                    {
                        reply = Letou.Instance.Compare(numbers);
                    }
                }
                //else if (LuisMaster.HitLuis(message,out string luisMessage))
                //{
                //    reply = $"{luisMessage}";
                //}
                else if (message.Contains("打球了"))
                {
                    bool     isFriday = false;
                    DateTime date     = DateTime.Now;

                    if (date.DayOfWeek == DayOfWeek.Friday)
                    {
                        reply = $"今晚7點半,高品打老虎";
                    }
                    else
                    {
                        while (!isFriday)
                        {
                            if (date.DayOfWeek == DayOfWeek.Friday)
                            {
                                isFriday = true;
                            }
                            else
                            {
                                date = date.AddDays(1);
                            }
                        }

                        reply = $"{date.ToString("yyyy/M/d")} 星期五 晚上7點半, 高品集合~~";
                    }
                }
                else if (message == "猜數字")
                {
                    reply = $"{userInfo.displayName} 開始猜數字 , 請輸入: 4位數字 (ex:1234) , 時間20分鐘";
                    var number = new GuessNum().GenNum();
                    var policy = new CacheItemPolicy
                    {
                        AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(20)
                    };
                    cache.Set(ownKey, number, policy);
                    cache.Set($"{ownKey}Count", 0, policy);
                    cache.Remove(id);
                }
                else if (!regex.IsMatch(message) && message.Length == 4 && cache[ownKey] != null && cache[id] == null)
                {
                    var ans = cache[ownKey].ToString();
                    int.TryParse(cache[$"{ownKey}Count"].ToString(), out int count);
                    count++;
                    var compare = new GuessNum().Compare(ans, message, out string errorMessage);
                    if (compare.A == 4)
                    {
                        reply = $"恭喜你猜對了 : {message} [你一共猜了{count}次]";
                        cache.Remove(ownKey);
                        cache.Remove($"{ownKey}Count");
                    }
                    else if (errorMessage != string.Empty)
                    {
                        reply += $"{errorMessage}";
                    }
                    else
                    {
                        reply += $"{message}==>{compare.A} A {compare.B} B ...己經猜了{count}次";
                        cache[$"{ownKey}Count"] = count;
                    }
                }
                else if (message == "一起猜")
                {
                    reply = $"大家開始猜數字 , 請輸入: 4位數字 (ex:1234) , 時間20分鐘";
                    var number = new GuessNum().GenNum();
                    var policy = new CacheItemPolicy
                    {
                        AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(20)
                    };
                    cache.Set(id, number, policy);
                    cache.Set($"{id}Count", 0, policy);
                }
                else if (!regex.IsMatch(message) && message.Length == 4 && cache[id] != null)
                {
                    var ans = cache[id].ToString();
                    int.TryParse(cache[$"{id}Count"].ToString(), out int count);
                    count++;
                    var compare = new GuessNum().Compare(ans, message, out string errorMessage);
                    if (compare.A == 4)
                    {
                        reply += $"恭喜猜對了 : {message} [一共猜了{count}次]" +
                                 cache.Remove(id);
                        cache.Remove($"{id}Count");
                    }
                    else if (errorMessage != string.Empty)
                    {
                        reply += $"{errorMessage}";
                    }
                    else
                    {
                        reply += $"{message}==>{compare.A} A {compare.B} B ...己經猜了{count}次";
                        cache[$"{id}Count"] = count;
                    }
                }
                else if (message.Contains("PM2.5"))
                {
                    var word = message.Split('的');
                    if (word.Length == 2 && word[1].Contains("PM2.5"))
                    {
                        var area  = word[0].Replace("台", "臺");
                        var air   = new AirQuality();
                        var model = air.GetList().Where(x => x.county.Contains(area) || x.Site.Contains(area));
                        if (model.Count() > 0)
                        {
                            foreach (var item in model)
                            {
                                reply += $"{item.county}{item.Site}的PM2.5為[{item.PM25}], {item.Status}\\n";
                            }
                            reply += $"更新時間:{model.FirstOrDefault().DataCreationDate.Value}";
                        }
                        else
                        {
                            reply = "查無資料 , 有可能打錯關鍵字, 可以試試 新北市的PM2.5 或 三重的PM2.5";
                        }
                    }
                }

                //回覆API OK
                isRock.LineBot.Utility.ReplyMessage(messageObject.replyToken, $"{reply}", ChannelAccessToken);

                //Utility.ReplyMessageWithJSON(messageObject.replyToken,FlexMessage(), ChannelAccessToken);
                return(Ok());
            }
            catch (Exception ex)
            {
                //isRock.LineBot.Utility.ReplyMessage(messageObject.replyToken, $"{ex.Message}  \nitem.source.type {messageObject.source.type}", ChannelAccessToken);
                return(Ok());
            }
        }