public StatusCodeResult OnPost() { var ReceivedMsg = isRock.LineBot.Bot.ParsingReceivedMessage(Request.Body); if (ReceivedMsg.events[0].replyToken == "00000000000000000000000000000000") { return(Ok()); } //var touserId = ""; var token = ""; isRock.LineBot.Bot bot = new isRock.LineBot.Bot(token); isRock.LineBot.TextMessage msg; if (ReceivedMsg.events.Count > 0 && ReceivedMsg.events[0].message != null && !string.IsNullOrEmpty(ReceivedMsg.events[0].message.text)) { msg = new isRock.LineBot.TextMessage("you said : " + ReceivedMsg.events[0].message.text); } else { msg = new isRock.LineBot.TextMessage("test"); } bot.ReplyMessage(ReceivedMsg.events[0].replyToken, msg); return(Ok()); }
private bool ProcessCommand(isRock.LineBot.Event e) { var msg = e.message.text.Trim(); if (msg.ToLower() == "/today") { //今日花費 var n = Utility.GetTodaySpend(e.source.userId); //回覆QuickReply isRock.LineBot.Bot b = new isRock.LineBot.Bot(); isRock.LineBot.TextMessage TextMessage = new isRock.LineBot.TextMessage( $"您今天總花費金額為 ${n}"); b.ReplyMessage(e.replyToken, TextMessage); return(true); } if (msg.ToLower() == "/month") { //本月花費 var n = Utility.GetThisMonthSpend(e.source.userId); //回覆QuickReply isRock.LineBot.Bot b = new isRock.LineBot.Bot(); isRock.LineBot.TextMessage TextMessage = new isRock.LineBot.TextMessage( $"您本月總花費金額為 ${n}"); b.ReplyMessage(e.replyToken, TextMessage); return(true); } return(false); }
public IActionResult Post() { //取得Line Event(範例,只取第一個) try { var LineEvent = this.ReceivedMessage.events.FirstOrDefault(); //配合Line verify if (LineEvent.replyToken == "00000000000000000000000000000000") { return(Ok()); } var ret = new List <isRock.LineBot.MessageBase>(); if (LineEvent.type == "message") { var text = new isRock.LineBot.TextMessage("你說了" + LineEvent.message.text); ret.Add(text); } var bot = new isRock.LineBot.Bot(ChannelAccessToken); bot.ReplyMessage(LineEvent.replyToken, ret); return(Ok()); } catch (System.Exception ex) { return(Ok()); } }
protected void Button1_Click(object sender, EventArgs e) { //建立一個TextMessage物件 isRock.LineBot.TextMessage m = new isRock.LineBot.TextMessage("請在底下選擇一個選項"); //在TextMessage物件的quickReply屬性中加入items m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"一般標籤", "點選後顯示的text文字")); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"有圖示的標籤", "點選後顯示的text文字", new Uri(IconUrl))); //加入QuickReplyDatetimePickerAction m.quickReply.items.Add( new isRock.LineBot.QuickReplyDatetimePickerAction( "選時間", "選時間", isRock.LineBot.DatetimePickerModes.datetime, new Uri(IconUrl))); //加入QuickReplyLocationAction m.quickReply.items.Add( new isRock.LineBot.QuickReplyLocationAction( "選地點", new Uri(IconUrl))); //加入QuickReplyCameraAction m.quickReply.items.Add( new isRock.LineBot.QuickReplyCameraAction( "Show Camera", new Uri(IconUrl))); //加入QuickReplyCamerarollAction m.quickReply.items.Add( new isRock.LineBot.QuickReplyCamerarollAction( "Show Cameraroll", new Uri(IconUrl))); //建立bot instance isRock.LineBot.Bot bot = new isRock.LineBot.Bot(ChannelAccessToken); //透過Push發送訊息 bot.PushMessage(AdminUserId, m); }
public IActionResult OnPost() { var bot = new isRock.LineBot.Bot(ChannelAccessToken); var msg = new isRock.LineBot.TextMessage("Hello World"); bot.PushMessage(AdminUserId, msg); return(Page()); }
static void Main(string[] args) { //建立 Bot instance isRock.LineBot.Bot bot = new isRock.LineBot.Bot(ChannelAccessToken); //建立文字訊息 var TextMsg = new isRock.LineBot.TextMessage("嗨,我是老闆"); TextMsg.sender.name = "老闆"; //改變暱稱 TextMsg.sender.iconUrl = new Uri("https://i.imgur.com/CkJkfQY.png"); //改變頭像 bot.PushMessage(AdminUserId, TextMsg); //建立文字訊息 var TextMsg2 = new isRock.LineBot.TextMessage("嗨,我是小編"); TextMsg2.sender.name = "小編"; //改變暱稱 TextMsg2.sender.iconUrl = new Uri("https://i.imgur.com/tB236xb.png"); //改變頭像 bot.PushMessage(AdminUserId, TextMsg2); Console.WriteLine("press ENTER to continue..."); Console.ReadLine(); }
public IHttpActionResult POST() { isRock.LineBot.Event LineEvent = null; //取得Web.config中的 app settings var token = System.Configuration.ConfigurationManager.AppSettings["ChannelAccessToken"]; var CLIENT_ID = System.Configuration.ConfigurationManager.AppSettings["Imgur_CLIENT_ID"]; var CLIENT_SECRET = System.Configuration.ConfigurationManager.AppSettings["Imgur_CLIENT_SECRET"]; try { //抓取Line Event LineEvent = this.ReceivedMessage.events.FirstOrDefault(); //設定抓取Web.Config //this.ChannelAccessToken = channelAccessToken; //取得Line Event(範例,只取第一個) //配合Line verify if (LineEvent.replyToken == "00000000000000000000000000000000") { return(Ok()); } //回覆訊息 if (LineEvent.type == "message") { if (LineEvent.message.type == "text") //收到文字 { this.ReplyMessage(LineEvent.replyToken, "你說了:" + LineEvent.message.text); } if (LineEvent.message.type == "sticker") //收到貼圖 { this.ReplyMessage(LineEvent.replyToken, 1, 2); } //收到用戶傳來的圖片(重點在這一段) if (LineEvent.message.type == "image") { //建立 ImgurClient var client = new ImgurClient(CLIENT_ID, CLIENT_SECRET); var endpoint = new ImageEndpoint(client); IImage image; //從LineEvent取得用戶上傳的圖檔bytes var byteArray = isRock.LineBot.Utility.GetUserUploadedContent(LineEvent.message.id, token); //取得圖片檔案FileStream Stream stream = new MemoryStream(byteArray); using (stream) { image = endpoint.UploadImageStreamAsync(stream).GetAwaiter().GetResult(); } //上傳成功之後,image.Link會回傳 url //建立文字訊息 isRock.LineBot.TextMessage TextMsg = new isRock.LineBot.TextMessage(image.Link); //建立圖形訊息(用上傳後的網址) isRock.LineBot.ImageMessage imageMsg = new isRock.LineBot.ImageMessage(new Uri(image.Link), new Uri(image.Link)); //建立集合 var Messages = new List <isRock.LineBot.MessageBase>(); Messages.Add(TextMsg); Messages.Add(imageMsg); //一次把集合中的多則訊息回覆給用戶 this.ReplyMessage(LineEvent.replyToken, Messages); } } //response OK return(Ok()); } catch (Exception ex) { //如果發生錯誤,傳訊息給Admin this.ReplyMessage(LineEvent.replyToken, "發生錯誤:\n" + ex.Message); //response OK return(Ok()); } }
public IActionResult POST() { //get configuration from appsettings.json var token = _config.GetSection("LINE-Bot-Setting:channelAccessToken"); var AdminUserId = _config.GetSection("LINE-Bot-Setting:adminUserID"); var body = ""; //for JSON Body //create vot instance var bot = new isRock.LineBot.Bot(token.Value); isRock.LineBot.MessageBase responseMsg = null; //message collection for response multi-message List <isRock.LineBot.MessageBase> responseMsgs = new List <isRock.LineBot.MessageBase>(); try { //get JSON Body using (StreamReader reader = new StreamReader(Request.Body, System.Text.Encoding.UTF8)) { body = reader.ReadToEndAsync().Result; } //parsing JSON var ReceivedMessage = isRock.LineBot.Utility.Parsing(body); //Get LINE Event var LineEvent = ReceivedMessage.events.FirstOrDefault(); //prepare reply message if (LineEvent.type.ToLower() == "message") { switch (LineEvent.message.type.ToLower()) { case "text": //add text response responseMsg = new isRock.LineBot.TextMessage($"you said : {LineEvent.message.text}"); responseMsgs.Add(responseMsg); //add ButtonsTemplate if user say "/Show ButtonsTemplate" if (LineEvent.message.text.ToLower().Contains("/show buttonstemplate")) { //define actions var act1 = new isRock.LineBot.MessageAction() { text = "test action1", label = "test action1" }; var act2 = new isRock.LineBot.MessageAction() { text = "test action2", label = "test action2" }; var tmp = new isRock.LineBot.ButtonsTemplate() { text = "Button Template text", title = "Button Template title", thumbnailImageUrl = new Uri("https://i.imgur.com/wVpGCoP.png"), }; tmp.actions.Add(act1); tmp.actions.Add(act2); //add TemplateMessage into responseMsgs responseMsgs.Add(new isRock.LineBot.TemplateMessage(tmp)); } break; case "sticker": responseMsg = new isRock.LineBot.StickerMessage(1, 2); responseMsgs.Add(responseMsg); break; default: responseMsg = new isRock.LineBot.TextMessage($"None handled message type : { LineEvent.message.type}"); responseMsgs.Add(responseMsg); break; } } else { responseMsg = new isRock.LineBot.TextMessage($"None handled event type : { LineEvent.type}"); responseMsgs.Add(responseMsg); } //回覆訊息 bot.ReplyMessage(LineEvent.replyToken, responseMsgs); //response OK return(Ok()); } catch (Exception ex) { //如果有錯誤,push給admin bot.PushMessage(AdminUserId.Value, "Exception : \n" + ex.Message); //response OK return(Ok()); } }
private string ProcessText(isRock.LineBot.Event e) { const string HelpMsg = "嗨,您好。\n如果希望我幫您記帳,你可以直接輸入金額唷...\n\n例如:\n 180 \n 或\n 180 麥當勞\n然後再選取或輸入分類即可。"; //取得User Id var UserId = e.source.userId; var msg = e.message.text; //如果沒有狀態 if (string.IsNullOrEmpty(Utility.GetState(UserId))) { //預期msg是金額數字 //去除空白和不必要的字 msg = msg.Replace("$", "").Replace("元", "").Trim(); //全形轉半形 //msg = Strings.StrConv(msg, VbStrConv.Narrow, 0); //如果當前沒有狀態,預期的是純數字 //先以 ' ' 分割 var item = msg.Split(' '); if (item.Length <= 0) { return(HelpMsg); } float num = 0; string memo = ""; if (float.TryParse(item[0], out num) == false) { return(HelpMsg); } if (item.Length == 2) { memo = item[1].Trim(); } //如果資料沒問題, 保存起來 Utility.SetState(UserId + "-Amount", num.ToString()); Utility.SetState(UserId + "-Memo", memo); //回覆QuickReply isRock.LineBot.Bot b = new isRock.LineBot.Bot(); isRock.LineBot.TextMessage TextMessage = new isRock.LineBot.TextMessage($"請選擇或直接輸入這筆金額'{num}'的記帳類別"); var Types = Utility.GetTypes(UserId); foreach (var type in Types) { TextMessage.quickReply.items.Add(new isRock.LineBot.QuickReplyMessageAction(type, type)); } b.ReplyMessage(e.replyToken, TextMessage); //設定狀態 Utility.SetState(UserId, "等待分類名稱"); return(""); } //如果有狀態,且為正等待分類名稱 if (Utility.GetState(UserId) == "等待分類名稱") { //取回應該有的數字 if (string.IsNullOrEmpty(Utility.GetState(UserId + "-Amount"))) { Utility.SetState(UserId, ""); return(HelpMsg); } //取回數字 float num = 0; if (float.TryParse(Utility.GetState(UserId + "-Amount"), out num) == false) { return(HelpMsg); } string memo = Utility.GetState(UserId + "-Memo"); //有了數字num以及分類名稱 var AccountType = msg.Trim(); //清空狀態 Utility.SetState(UserId, ""); //紀錄 if (Utility.SaveToDB(UserId, num, AccountType, memo)) { return($"${num} 已記錄為 {AccountType}"); } else { return("記錄失敗"); } } return(""); }
public IHttpActionResult POST() { isRock.LineBot.Event LineEvent = null; //取得Web.config中的 app settings var token = System.Configuration.ConfigurationManager.AppSettings["g2cfcaiQgAc9+Sg9JcAnO4OvXqvvNkrIDeFEy089oG7cmO8yXRshePGa+wgTzAQ2aoDinj9TBGu2471l4BqtZXQJWCraicw5S5V8HgyBdoNtLQos4MMJdanGMaC24jSUvWkHbMj6xt66bvhLl11MbAdB04t89/1O/w1cDnyilFU="]; var CLIENT_ID = System.Configuration.ConfigurationManager.AppSettings["fdd30319757d1cf"]; var CLIENT_SECRET = System.Configuration.ConfigurationManager.AppSettings["b4ee94f79457430cd201f82f69cfd85f2aa72518"]; try { //抓取Line Event LineEvent = this.ReceivedMessage.events.FirstOrDefault(); //設定抓取Web.Config //this.ChannelAccessToken = channelAccessToken; //取得Line Event(範例,只取第一個) //配合Line verify if (LineEvent.replyToken == "00000000000000000000000000000000") { return(Ok()); } //回覆訊息 if (LineEvent.type == "message") { if (LineEvent.message.type == "text") //收到文字 { this.ReplyMessage(LineEvent.replyToken, "你說了:" + LineEvent.message.text); } if (LineEvent.message.type == "sticker") //收到貼圖 { this.ReplyMessage(LineEvent.replyToken, 1, 2); } //收到用戶傳來的圖片(重點在這一段) if (LineEvent.message.type == "image") { //建立 ImgurClient var client = new ImgurClient(CLIENT_ID, CLIENT_SECRET); var endpoint = new ImageEndpoint(client); IImage image; //從LineEvent取得用戶上傳的圖檔bytes var byteArray = isRock.LineBot.Utility.GetUserUploadedContent(LineEvent.message.id, token); //取得圖片檔案FileStream Stream stream = new MemoryStream(byteArray); using (stream) { image = endpoint.UploadImageStreamAsync(stream).GetAwaiter().GetResult(); } //上傳成功之後,image.Link會回傳 url //建立文字訊息 isRock.LineBot.TextMessage TextMsg = new isRock.LineBot.TextMessage(image.Link); //建立圖形訊息(用上傳後的網址) isRock.LineBot.ImageMessage imageMsg = new isRock.LineBot.ImageMessage(new Uri(image.Link), new Uri(image.Link)); //建立集合 var Messages = new List <isRock.LineBot.MessageBase>(); Messages.Add(TextMsg); Messages.Add(imageMsg); //一次把集合中的多則訊息回覆給用戶 this.ReplyMessage(LineEvent.replyToken, Messages); } } //response OK return(Ok()); } catch (Exception ex) { //如果發生錯誤,傳訊息給Admin this.ReplyMessage(LineEvent.replyToken, "發生錯誤:\n" + ex.Message); //response OK return(Ok()); } }
/// <summary> /// 處理照片 /// </summary> /// <param name="LineEvent"></param> /// <param name="token"></param> /// <returns></returns> private List <isRock.LineBot.MessageBase> ProcessImage(isRock.LineBot.Event LineEvent, string token) { //web.config var ComputerVisionServiceKey = System.Configuration.ConfigurationManager.AppSettings["ComputerVisionServiceKey"]; var ComputerVisionServiceEndpoint = System.Configuration.ConfigurationManager.AppSettings["ComputerVisionServiceEndpoint"]; string Msg = ""; //取得照片 //從LineEvent取得用戶上傳的圖檔bytes var byteArray = isRock.LineBot.Utility.GetUserUploadedContent(LineEvent.message.id, token); //取得圖片檔案FileStream, 分別作為繪圖與分析用 Stream MemStream1 = new MemoryStream(byteArray); Stream MemStream2 = new MemoryStream(byteArray); //繪圖用 System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(MemStream1); Graphics g = Graphics.FromImage(bmp); //ComputerVision instance var visionClient = new Microsoft.ProjectOxford.Vision.VisionServiceClient( ComputerVisionServiceKey, ComputerVisionServiceEndpoint); //分析用 using (MemStream2) { //分析圖片 var Results = visionClient.AnalyzeImageAsync( MemStream2, new VisualFeature[] { VisualFeature.Faces, VisualFeature.Description }).Result; //分別保存性別數量 int isM = 0, isF = 0; //如果找到臉,就畫方框標示出來 foreach (var item in Results.Faces) { var faceRect = item.FaceRectangle; //畫框 g.DrawRectangle( new Pen(Brushes.Red, 3), new Rectangle(faceRect.Left, faceRect.Top, faceRect.Width, faceRect.Height)); //在方框旁邊顯示年紀 var age = 0; if (item.Gender.StartsWith("F")) { age = item.Age - 2; } else { age = item.Age; } //劃出數字 g.DrawString(age.ToString(), new Font(SystemFonts.DefaultFont.FontFamily, 24, FontStyle.Bold), new SolidBrush(Color.Black), faceRect.Left + 3, faceRect.Top + 3); //紀錄性別數量 if (item.Gender.StartsWith("M")) { isM += 1; } else { isF += 1; } } //圖片分析結果 Msg += $"\n圖片說明:\n{Results.Description.Captions[0].Text}"; //如果update了照片,則顯示新圖 if (Results.Faces.Count() > 0) { Msg += String.Format("\n找到{0}張臉, \n{1}男 {2}女", Results.Faces.Count(), isM, isF); } } string ImgurURL = ""; using (MemoryStream m = new MemoryStream()) { bmp.Save(m, System.Drawing.Imaging.ImageFormat.Png); ImgurURL = UploadImage2Imgur(m.ToArray()); } //上傳成功之後,image.Link會回傳 url //建立文字訊息 isRock.LineBot.TextMessage TextMsg = new isRock.LineBot.TextMessage(Msg); //建立圖形訊息(用上傳後的網址) isRock.LineBot.ImageMessage imageMsg = new isRock.LineBot.ImageMessage(new Uri(ImgurURL), new Uri(ImgurURL)); //建立集合 var Messages = new List <isRock.LineBot.MessageBase>(); Messages.Add(TextMsg); Messages.Add(imageMsg); //一次把集合中的多則訊息回覆給用戶 return(Messages); }
public IHttpActionResult POST() { try { //設定ChannelAccessToken(或抓取Web.Config) this.ChannelAccessToken = channelAccessToken; //取得Line Event(範例,只取第一個) var LineEvent = this.ReceivedMessage.events.FirstOrDefault(); //配合Line verify if (LineEvent.replyToken == "00000000000000000000000000000000") { return(Ok()); } //回覆訊息 if (LineEvent.type == "message") { if (LineEvent.message.type == "text") //收到文字 { if (LineEvent.message.text.Contains("RPG-")) { //進到RPG指令區 if (LineEvent.message.text.Contains("TeM")) { List <isRock.LineBot.MessageBase> RetuenMessage = MessageCommand.RPGTeMCommand(LineEvent.message.text, LineEvent.source.roomId, LineEvent.source.userId); this.ReplyMessage(LineEvent.replyToken, RetuenMessage); } else { string RetuenMessage = MessageCommand.RPGCommand(LineEvent.message.text, LineEvent.source.roomId, LineEvent.source.userId); this.ReplyMessage(LineEvent.replyToken, RetuenMessage); } } else if (LineEvent.message.text.Contains("多圖片問答-")) { isRock.LineBot.Bot bot; bot = new isRock.LineBot.Bot(channelAccessToken); //取得 http Post RawData(should be JSO string postData = Request.Content.ReadAsStringAsync().Result; var ReceivedMessage = isRock.LineBot.Utility.Parsing(postData); //建立actions,作為ButtonTemplate的用戶回覆行為 var actions = new List <isRock.LineBot.TemplateActionBase>(); actions.Add(new isRock.LineBot.MessageActon() { label = "標題-文字回覆", text = "回覆文字" }); actions.Add(new isRock.LineBot.UriActon() { label = "標題-Google", uri = new Uri("http://www.google.com") }); actions.Add(new isRock.LineBot.PostbackActon() { label = "標題-發生postack", data = "abc=aaa&def=111" }); //單一Column var Column = new isRock.LineBot.Column { text = "ButtonsTemplate文字訊息", title = "ButtonsTemplate標題", //設定圖片 thumbnailImageUrl = new Uri("https://arock.blob.core.windows.net/blogdata201706/22-124357-ad3c87d6-b9cc-488a-8150-1c2fe642d237.png"), actions = actions //設定回覆動作 }; //建立CarouselTemplate var CarouselTemplate = new isRock.LineBot.CarouselTemplate(); //這是範例,所以用一組樣板建立三個 CarouselTemplate.columns.Add(Column); CarouselTemplate.columns.Add(Column); CarouselTemplate.columns.Add(Column); this.ReplyMessage(LineEvent.replyToken, new isRock.LineBot.TemplateMessage(CarouselTemplate)); } else if (LineEvent.message.text.Contains("圖片問答-")) { isRock.LineBot.Bot bot; bot = new isRock.LineBot.Bot(channelAccessToken); //取得 http Post RawData(should be JSO string postData = Request.Content.ReadAsStringAsync().Result; var ReceivedMessage = isRock.LineBot.Utility.Parsing(postData); //建立actions,作為ButtonTemplate的用戶回覆行為 var act1 = new isRock.LineBot.MessageAction() { text = "test action1", label = "test action1" }; var act2 = new isRock.LineBot.MessageAction() { text = "test action2", label = "test action2" }; var tmp = new isRock.LineBot.ButtonsTemplate() { text = "Button Template text", title = "Button Template title", thumbnailImageUrl = new Uri("https://i.imgur.com/wVpGCoP.png"), }; tmp.actions.Add(act1); tmp.actions.Add(act2); //var UserID = isRock.LineBot.Utility.Parsing(postData).events[0].source.userId; //bot.PushMessage(UserID, ButtonTemplate); this.ReplyMessage(LineEvent.replyToken, new isRock.LineBot.TemplateMessage(tmp)); } else if (LineEvent.message.text.Contains("圖-")) { //isRock.LineBot.ImagemapMessage img = new isRock.LineBot.ImagemapMessage(new Uri("http://")); this.ReplyMessage(LineEvent.replyToken, new Uri("https://i.imgur.com/QqjmONg.png")); } else if (LineEvent.message.text.Contains("相關代號")) { string 回覆訊息 = ""; 回覆訊息 += "房間編號: " + LineEvent.source.roomId + "\n"; 回覆訊息 += "玩家編號: " + LineEvent.source.userId + "\n"; this.ReplyMessage(LineEvent.replyToken, 回覆訊息); } else if (LineEvent.message.text.Contains("測試")) { List <isRock.LineBot.MessageBase> responseMsgs = new List <isRock.LineBot.MessageBase>(); isRock.LineBot.MessageBase responseMsg = null; //add text response responseMsg = new isRock.LineBot.TextMessage($"you said : {LineEvent.message.text}"); responseMsgs.Add(responseMsg); //add ButtonsTemplate if user say "/Show ButtonsTemplate" if (LineEvent.message.text.ToLower().Contains("show buttonstemplate")) { //define actions var act1 = new isRock.LineBot.MessageAction() { text = "test action1", label = "test action1" }; var act2 = new isRock.LineBot.MessageAction() { text = "test action2", label = "test action2" }; var tmp = new isRock.LineBot.ButtonsTemplate() { text = "Button Template text", title = "Button Template title", thumbnailImageUrl = new Uri("https://i.imgur.com/wVpGCoP.png"), }; tmp.actions.Add(act1); tmp.actions.Add(act2); //add TemplateMessage into responseMsgs responseMsgs.Add(new isRock.LineBot.TemplateMessage(tmp)); } this.ReplyMessage(LineEvent.replyToken, responseMsgs); } } //else //{ // this.ReplyMessage(LineEvent.replyToken, "你說了:" + LineEvent.message.text); //} if (LineEvent.message.type == "sticker") //收到貼圖 { this.ReplyMessage(LineEvent.replyToken, 1, 2); } } //response OK return(Ok()); } catch (Exception ex) { var LineEvent = this.ReceivedMessage.events.FirstOrDefault(); this.ReplyMessage(LineEvent.replyToken, "發生錯誤:\n" + ex.Message); //如果發生錯誤,傳訊息給Admin this.PushMessage(AdminUserId, "發生錯誤:\n" + ex.Message); //response OK return(Ok()); } }
public IActionResult POST() { var AdminUserId = "U3642fd7bd605b4781e64effed44ec97e"; try { //設定ChannelAccessToken this.ChannelAccessToken = "dt0W9B9ztQWfHmg1e3ifpp+xEvHTarYhi4SnIvrxuODgAVq5qgi19pWLPIAKqJ4VQnfPt9BTg5EkLshGWLbVM5u/C0RAzHXWs2EMdwxMLJNdJ0uHazOIDgI9NDHTdxZNy0NGNUwvzJpy6k1s467+dwdB04t89/1O/w1cDnyilFU="; //取得Line Event var LineEvent = this.ReceivedMessage.events.FirstOrDefault(); var profile = GetUserInfo(LineEvent.source.userId); //配合Line verify if (LineEvent.replyToken == "00000000000000000000000000000000") { return(Ok()); } var responseMsg = ""; //準備回覆訊息 if (LineEvent.type.ToLower() == "follow") { isRock.LineBot.TextMessage m = new isRock.LineBot.TextMessage($"{profile.displayName},使用Smart AI Sports幫助你一起健身吧!"); //在TextMessage物件的quickreply屬性中加入items m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"想健身", "我想健身" )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"身體資訊", "想知道身體資訊" )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"聯絡我們", "聯絡我們" )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyLocationAction( "搜尋附近的健身房")); this.ReplyMessage(LineEvent.replyToken, m); //response OK return(Ok()); } //設定用戶回傳訊息類型為image時的回覆 else if (LineEvent.type.ToLower() == "message" && LineEvent.message.type == "image") { Uri imgUri = new Uri("https://i.imgur.com/o9uT3Aa.png"); var msgs = new List <isRock.LineBot.MessageBase>(); var msgadd = new isRock.LineBot.TextMessage($"這照片真讚\n{profile.displayName}要運動了嗎"); msgadd.quickReply.items.Add( new isRock.LineBot.QuickReplyLocationAction( "找附近的健身房")); //add messages to msgs.Add(new isRock.LineBot.ImageMessage(imgUri, imgUri)); msgs.Add(msgadd); this.ReplyMessage(LineEvent.replyToken, msgs); //response OK return(Ok()); } //設定用戶回傳訊息類型為text時的回覆 else if (LineEvent.type.ToLower() == "message" && LineEvent.message.type == "text") { var ret = MakeRequest(LineEvent.message.text); //用戶回傳訊息為BMI時 此段為判斷intent="身體" 後 接續quickreply為BMI/TDEE的計算 if (LineEvent.message.text.ToUpper() == "BMI") { isRock.LineBot.Bot bot = new isRock.LineBot.Bot(this.ChannelAccessToken); var msgs = new List <isRock.LineBot.MessageBase>(); var msgadd1 = new isRock.LineBot.TextMessage("感謝您!"); var msgadd2 = new isRock.LineBot.TextMessage("-BMI\n身高:\n體重:"); //add messages to msgs.Add(new isRock.LineBot.TextMessage("請複製下面表格並填入資料後回覆~")); msgs.Add(msgadd1); msgs.Add(msgadd2); this.ReplyMessage(LineEvent.replyToken, msgs); //response OK return(Ok()); } else if (LineEvent.message.text.ToUpper() == "TDEE") { isRock.LineBot.Bot bot = new isRock.LineBot.Bot(this.ChannelAccessToken); var msgs = new List <isRock.LineBot.MessageBase>(); var msgadd = new isRock.LineBot.TextMessage("-TDEE\n身高:\n體重:\n年齡:\n性別:男/女"); //add messages to msgs.Add(new isRock.LineBot.TextMessage("請複製下面表格並填入資料後回覆~")); msgs.Add(msgadd); this.ReplyMessage(LineEvent.replyToken, msgs); //response OK return(Ok()); } else if (LineEvent.message.text.Contains("-BMI")) // 算BMI { float height = float.Parse(LineEvent.message.text.Split("\n")[1].Split(":")[1]) / 100; float weight = float.Parse(LineEvent.message.text.Split("\n")[2].Split(":")[1]); float userbmi = weight / (height * height); var bmiResult = String.Format($"Your BMI : {userbmi:0.00} "); isRock.LineBot.Bot bot = new isRock.LineBot.Bot(this.ChannelAccessToken); var msgs = new List <isRock.LineBot.MessageBase>(); msgs.Add(new isRock.LineBot.TextMessage("經過我快速精密的計算過後....")); var msgadd2 = new isRock.LineBot.TextMessage($"{bmiResult}"); msgs.Add(msgadd2); this.ReplyMessage(LineEvent.replyToken, msgs); return(Ok()); } else if (LineEvent.message.text.Contains("-TDEE")) // 算TDEE { double height = double.Parse(LineEvent.message.text.Split("\n")[1].Split(":")[1]); double weight = double.Parse(LineEvent.message.text.Split("\n")[2].Split(":")[1]); double age = double.Parse(LineEvent.message.text.Split("\n")[3].Split(":")[1]); string sex = LineEvent.message.text.Split("\n")[4].Split(":")[1]; int light, medi, high; double BMR; if (sex == "男") { BMR = (13.7 * weight) + (5 * height) - (6.8 * age) + 66; light = Convert.ToInt32(BMR * 1.2); medi = Convert.ToInt32(BMR * 1.375); high = Convert.ToInt32(BMR * 1.55); } else if (sex == "女") { BMR = (9.6 * weight) + (1.8 * height) - (4.7 * age) + 655; light = Convert.ToInt32(BMR * 1.2); medi = Convert.ToInt32(BMR * 1.375); high = Convert.ToInt32(BMR * 1.55); } else { responseMsg = "請輸入正確資料。"; this.ReplyMessage(LineEvent.replyToken, responseMsg); //response OK return(Ok()); } string userbmi = (weight / (height * height)).ToString(); var tdeeResult = String.Format($"Your 基礎代謝: {BMR:0.00}\n每日總消耗熱量\n久坐:{light}\n輕量活動:{medi}\n中量活動:{high}"); //一次回復訊息及計算結果 isRock.LineBot.Bot bot = new isRock.LineBot.Bot(this.ChannelAccessToken); var msgs = new List <isRock.LineBot.MessageBase>(); msgs.Add(new isRock.LineBot.TextMessage("經過我快速精密的計算過後....")); var msgadd2 = new isRock.LineBot.TextMessage($"{tdeeResult}"); msgs.Add(msgadd2); this.ReplyMessage(LineEvent.replyToken, msgs); //response OK return(Ok()); } //若intent為打招呼 回傳default功能的Quickreply else if (ret.topScoringIntent.intent.Contains("打招呼")) { isRock.LineBot.TextMessage m = new isRock.LineBot.TextMessage($"你好!{profile.displayName}!\n歡迎使用Smart AI Sports\n我能為你做下列的事情喔"); //在TextMessage物件的quickreply屬性中加入items m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"想健身", "我想健身", new Uri("https://image.flaticon.com/295/png/512/1616/1616456.png?size=1200x630f") )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"身體資訊", "想知道身體資訊", new Uri("https://image.flaticon.com/219/png/512/1754/1754237.png?size=1200x630f") )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"聯絡我們", "聯絡我們", new Uri("https://i.imgur.com/rwwI5XW.png") )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyLocationAction( "搜尋附近的健身房", new Uri("https://image.flaticon.com/179/png/512/458/458369.png?size=1200x630f"))); this.ReplyMessage(LineEvent.replyToken, m); //response OK return(Ok()); } else if (ret.topScoringIntent.intent.Contains("訓練")) { isRock.LineBot.Bot bot = new isRock.LineBot.Bot(this.ChannelAccessToken); //建立buttonsTemplate var button = new isRock.LineBot.ButtonsTemplate() { altText = "altText", text = "提供姿勢偵測", title = "Smart AI Sports", thumbnailImageUrl = new Uri("https://i.imgur.com/qOmWNyi.jpg") }; //actions button.actions.Add(new isRock.LineBot.UriAction() { label = "棒式動作示範", uri = new Uri("https://www.youtube.com/watch?v=UiklJLUh6qU") }); button.actions.Add(new isRock.LineBot.UriAction() { label = "二頭彎舉示範", uri = new Uri("https://www.youtube.com/watch?v=d71MiVhUBlw&t=395s") }); button.actions.Add(new isRock.LineBot.UriAction() { label = "臀推動作示範", uri = new Uri("https://www.youtube.com/watch?v=7i8iqg3s5sY") }); // button.actions.Add(new isRock.LineBot.CamerarollAction() { label = "上傳你的照片" }); // var msgs = new List <isRock.LineBot.MessageBase>(); // msgs.Add(new isRock.LineBot.TextMessage("請複製下面表格並填入資料後回覆O_o")); foreach (var showlist in ret.entities) { Console.WriteLine(showlist.type); Console.WriteLine(showlist.entity); var trainlist = ""; if (showlist.type == "訓練名稱") { trainlist += showlist.entity; msgs.Add(new isRock.LineBot.TextMessage($"看來你今天想練{trainlist}\n目前提供以下訓練選擇")); } else { msgs.Add(new isRock.LineBot.TextMessage($"請問你今天想練甚麼?\n目前提供以下訓練選擇")); } var ButtonsTmp = new isRock.LineBot.TemplateMessage(button); msgs.Add(ButtonsTmp); var msgadd2 = new isRock.LineBot.TextMessage("請用電腦開啟以下網站進行姿勢偵測"); msgs.Add(msgadd2); var msgadd3 = new isRock.LineBot.TextMessage("http://192.168.36.30:3000/fitness"); msgs.Add(msgadd3); this.ReplyMessage(LineEvent.replyToken, msgs); //response OK return(Ok()); } } else if (ret.topScoringIntent.intent.Contains("身體")) { isRock.LineBot.TextMessage m = new isRock.LineBot.TextMessage($"請問你想知道哪種資訊"); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"BMI(身體質量指數)", "BMI" )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"TDEE(基礎代謝率)", "TDEE" )); this.ReplyMessage(LineEvent.replyToken, m); //response OK return(Ok()); } else if (ret.topScoringIntent.intent.Contains("客服")) { isRock.LineBot.Bot bot = new isRock.LineBot.Bot(this.ChannelAccessToken); var msgs = new List <isRock.LineBot.MessageBase>(); var msgadd = new isRock.LineBot.TextMessage($"{profile.displayName},這是我們能提供的服務"); // new isRock.LineBot.TextMessage m = //在TextMessage物件的quickreply屬性中加入items msgadd.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"想健身", "我想健身", new Uri("https://image.flaticon.com/295/png/512/1616/1616456.png?size=1200x630f"))); msgadd.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"身體資訊", "想知道身體資訊", new Uri("https://image.flaticon.com/219/png/512/1754/1754237.png?size=1200x630f"))); msgadd.quickReply.items.Add( new isRock.LineBot.QuickReplyLocationAction( "搜尋附近的健身房", new Uri("https://image.flaticon.com/179/png/512/458/458369.png?size=1200x630f"))); //add messages to msgs.Add(new isRock.LineBot.TextMessage("連絡電話:0911-222-333\n連絡信箱:[email protected]")); msgs.Add(msgadd); this.ReplyMessage(LineEvent.replyToken, msgs); //response OK return(Ok()); } else if (ret.topScoringIntent.intent.Contains("感謝")) { Uri imgUri = new Uri("https://i.imgur.com/o9uT3Aa.png"); var msgs = new List <isRock.LineBot.MessageBase>(); var msgadd = new isRock.LineBot.ImageMessage(imgUri, imgUri); //add messages to msgs.Add(new isRock.LineBot.TextMessage("很高興能幫助到您!要繼續運動保持健康喔!")); msgs.Add(msgadd); this.ReplyMessage(LineEvent.replyToken, msgs); //response OK return(Ok()); } else if (ret.topScoringIntent.intent.Contains("None")) { isRock.LineBot.TextMessage m = new isRock.LineBot.TextMessage($"Sorry~{profile.displayName},我不太清楚你的意思,不過我能為你做下列的事情喔"); //在TextMessage物件的quickreply屬性中加入items m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"想健身", "我想健身", new Uri("https://image.flaticon.com/295/png/512/1616/1616456.png?size=1200x630f") )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"身體資訊", "想知道身體資訊", new Uri("https://image.flaticon.com/219/png/512/1754/1754237.png?size=1200x630f") )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyMessageAction( $"聯絡我們", "聯絡我們", new Uri("https://i.imgur.com/rwwI5XW.png") )); m.quickReply.items.Add( new isRock.LineBot.QuickReplyLocationAction( "搜尋附近的健身房", new Uri("https://image.flaticon.com/179/png/512/458/458369.png?size=1200x630f"))); this.ReplyMessage(LineEvent.replyToken, m); //response OK return(Ok()); } // else if (LineEvent.message.text.Contains("自訂文字")) // { // // ... // } } else if (LineEvent.type.ToLower() == "message" && LineEvent.message.type == "sticker") { responseMsg = $"{profile.displayName}有空傳貼圖,倒不如多做兩個伏地挺身"; this.ReplyMessage(LineEvent.replyToken, responseMsg); //response OK return(Ok()); } else if (LineEvent.type.ToLower() == "message" && LineEvent.message.type == "location") { double locx = LineEvent.message.latitude; double locy = LineEvent.message.longitude; string gymlink = $"打開以下連結查看你附近的健身房\nhttps://www.google.com.tw/maps/search/%E5%81%A5%E8%BA%AB%E6%88%BF/@{locx},{locy},15z/"; isRock.LineBot.Bot bot = new isRock.LineBot.Bot(this.ChannelAccessToken); var msgs = new List <isRock.LineBot.MessageBase>(); var msgadd = new isRock.LineBot.TextMessage(gymlink); //add messages to msgs.Add(new isRock.LineBot.TextMessage($"{profile.displayName}....你是不是在{LineEvent.message.address.Substring(3)}想找健身房")); msgs.Add(msgadd); this.ReplyMessage(LineEvent.replyToken, msgs); //response OK return(Ok()); } else { responseMsg = $"收到 event : {LineEvent.type} "; } //回覆訊息 this.ReplyMessage(LineEvent.replyToken, responseMsg); //response OK return(Ok()); } catch (Exception ex) { //回覆訊息 this.PushMessage(AdminUserId, "發生錯誤:\n" + ex.Message); //response OK return(Ok()); } }
public async Task <IActionResult> POST() { StickerList = Array.ConvertAll(_config.GetSection("Sticker:StickerList").Get <string> ().Split(","), int.Parse).ToList(); PackageId = _config.GetSection("Sticker:PackageId").Get <int> (); //get configuration from appsettings.json var token = _config.GetSection("channelAccessToken"); var AdminUserId = _config.GetSection("adminUserID"); var body = ""; //for JSON Body //create vot instance var bot = new isRock.LineBot.Bot(token.Value); isRock.LineBot.MessageBase responseMsg = null; //message collection for response multi-message List <isRock.LineBot.MessageBase> responseMsgs = new List <isRock.LineBot.MessageBase> (); try { //get JSON Body using (StreamReader reader = new StreamReader(Request.Body, System.Text.Encoding.UTF8)) { body = reader.ReadToEndAsync().Result; } //parsing JSON var ReceivedMessage = isRock.LineBot.Utility.Parsing(body); //Get LINE Event var LineEvent = ReceivedMessage.events.FirstOrDefault(); //prepare reply message if (LineEvent.type.ToLower() == "message") { switch (LineEvent.message.type.ToLower()) { case "text": Random random = new Random(); //add text response responseMsg = new isRock.LineBot.StickerMessage(PackageId, StickerList[random.Next(StickerList.Count - 1)]); responseMsgs.Add(responseMsg); //add ButtonsTemplate if user say "/Show ButtonsTemplate" if (LineEvent.message.text.ToLower().Contains("/show buttonstemplate")) { //define actions var act1 = new isRock.LineBot.MessageAction() { text = "test action1", label = "test action1" }; var act2 = new isRock.LineBot.MessageAction() { text = "test action2", label = "test action2" }; var tmp = new isRock.LineBot.ButtonsTemplate() { text = "Button Template text", title = "Button Template title", thumbnailImageUrl = new Uri("https://i.imgur.com/wVpGCoP.png"), }; tmp.actions.Add(act1); tmp.actions.Add(act2); //add TemplateMessage into responseMsgs responseMsgs.Add(new isRock.LineBot.TemplateMessage(tmp)); } else if (LineEvent.message.text.Contains("股票")) { string stockNo = Regex.Split(LineEvent.message.text, "股票.")[1]; var webCrawlerHelper = new WebCrawerHelper(_config); string data = webCrawlerHelper.getDatas(stockNo).Result; responseMsg = new isRock.LineBot.TextMessage(data); responseMsgs.Add(responseMsg); } break; case "sticker": responseMsg = new isRock.LineBot.StickerMessage(1, 2); responseMsgs.Add(responseMsg); break; default: var random2 = new Random(); // responseMsg = new isRock.LineBot.TextMessage($"None handled message type : { LineEvent.message.type}"); responseMsg = new isRock.LineBot.StickerMessage(PackageId, StickerList[random2.Next(StickerList.Count - 1)]); responseMsgs.Add(responseMsg); break; } } else { responseMsg = new isRock.LineBot.TextMessage($"None handled event type : { LineEvent.type}"); responseMsgs.Add(responseMsg); } await Task.CompletedTask; //回覆訊息 bot.ReplyMessage(LineEvent.replyToken, responseMsgs); //response OK return(Ok()); } catch (Exception ex) { //如果有錯誤,push給admin bot.PushMessage(AdminUserId.Value, "Exception : \n" + ex.Message); //response OK return(Ok()); } }