public static CardAction WaitCard() { newState = TagDetect.IsPresent(); if (newState) { state = CardAction.Inserted; Hardware.PIN_State(PINS.led_D, STATE.On); } else { state = CardAction.Removed; Hardware.PIN_State(PINS.led_D, STATE.Off); } if (newState != oldState) { oldState = newState; if (oldState) { card.Id = SelectCard(); Reader.ReadCardValue(); } OnCardDetect(null, new CardEventArgs() { action = state }); } return state; }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { HttpResponseMessage response; // welcome message 출력 if (activity.Type == ActivityTypes.ConversationUpdate && activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id)) { DateTime startTime = DateTime.Now; // Db DbConnect db = new DbConnect(); List <DialogList> dlg = db.SelectInitDialog(); Debug.WriteLine("!!!!!!!!!!! : " + dlg[0].dlgId); ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); for (int n = 0; n < dlg.Count; n++) { Activity reply2 = activity.CreateReply(); reply2.Recipient = activity.From; reply2.Type = "message"; reply2.Attachments = new List <Attachment>(); reply2.AttachmentLayout = AttachmentLayoutTypes.Carousel; List <CardList> card = db.SelectDialogCard(dlg[n].dlgId); List <TextList> text = db.SelectDialogText(dlg[n].dlgId); List <MediaList> media = db.SelectDialogMedia(dlg[n].dlgId); for (int i = 0; i < text.Count; i++) { HeroCard plCard = new HeroCard() { Title = text[i].cardTitle, Subtitle = text[i].cardText }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } for (int i = 0; i < card.Count; i++) { List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); if (card[i].imgUrl != null) { cardImages.Add(new CardImage(url: card[i].imgUrl)); } if (card[i].btn1Type != null) { CardAction plButton = new CardAction() { Value = card[i].btn1Context, Type = card[i].btn1Type, Title = card[i].btn1Title }; cardButtons.Add(plButton); } if (card[i].btn2Type != null) { CardAction plButton = new CardAction() { Value = card[i].btn2Context, Type = card[i].btn2Type, Title = card[i].btn2Title }; cardButtons.Add(plButton); } if (card[i].btn3Type != null) { CardAction plButton = new CardAction() { Value = card[i].btn3Context, Type = card[i].btn3Type, Title = card[i].btn3Title }; cardButtons.Add(plButton); } HeroCard plCard = new HeroCard() { Title = card[i].cardTitle, Subtitle = card[i].cardSubTitle, Images = cardImages, Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } for (int i = 0; i < media.Count; i++) { List <MediaUrl> mediaURL = new List <MediaUrl>(); List <CardAction> cardButtons = new List <CardAction>(); if (media[i].mediaUrl != null) { mediaURL.Add(new MediaUrl(url: media[i].mediaUrl)); } if (media[i].btn1Type != null) { CardAction plButton = new CardAction() { Value = media[i].btn1Context, Type = media[i].btn1Type, Title = media[i].btn1Title }; cardButtons.Add(plButton); } if (media[i].btn2Type != null) { CardAction plButton = new CardAction() { Value = media[i].btn2Context, Type = media[i].btn2Type, Title = media[i].btn2Title }; cardButtons.Add(plButton); } if (media[i].btn3Type != null) { CardAction plButton = new CardAction() { Value = media[i].btn3Context, Type = media[i].btn3Type, Title = media[i].btn3Title }; cardButtons.Add(plButton); } VideoCard plCard = new VideoCard() { Title = media[i].cardTitle, Text = media[i].cardText, Media = mediaURL, Buttons = cardButtons, Autostart = false }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } var reply1 = await connector.Conversations.SendToConversationAsync(reply2); } DateTime endTime = DateTime.Now; Debug.WriteLine("프로그램 수행시간 : {0}/ms", ((endTime - startTime).Milliseconds)); } else if (activity.Type == ActivityTypes.Message) { string orgMent = ""; string orgENGMent_history = ""; JObject Luis = new JObject(); DbConnect db = new DbConnect(); StateClient stateClient = activity.GetStateClient(); BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id); ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); orgMent = activity.Text; //Console.WriteLine(orgMent); //Translator translateInfo = await getTranslate(orgMent); //orgENGMent_history = Regex.Replace(translateInfo.data.translations[0].translatedText, @"[^a-zA-Z0-9ㄱ-힣-\s-']", "", RegexOptions.Singleline); //orgENGMent_history = orgENGMent_history.Replace("'", "'"); Luis = await GetIntentFromBotLUIS(orgMent); Debug.WriteLine("score : " + (float)Luis["intents"][0]["score"]); Debug.WriteLine("score : " + Luis["entities"].Count()); //Debug.WriteLine("entity : " + Luis["entities"][0]["entity"]); float luisScore = (float)Luis["intents"][0]["score"]; int luisEntityCount = (int)Luis["entities"].Count(); if (luisScore > 0 && luisEntityCount > 0) { string intent = (string)Luis["intents"][0]["intent"]; string[] entity = new string[luisEntityCount]; for (int entityCount = 0; entityCount < luisEntityCount; entityCount++) { entity[entityCount] = (string)Luis["entities"][entityCount]["entity"]; entity[entityCount] = entity[entityCount].Replace("\"", ""); entity[entityCount] = entity[entityCount].Replace(" ", ""); } intent = intent.Replace("\"", ""); userData.SetProperty <string>(intent, orgENGMent_history); await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); List <LuisList> LuisDialogID = db.SelectLuis(intent, entity); if (LuisDialogID.Count == 0) { /* * Activity reply_err = activity.CreateReply(); * reply_err.Recipient = activity.From; * reply_err.Type = "message"; * * List<TextList> text = db.SelectDialogText(1005); * * for (int j = 0; j < text.Count; j++) * { * HeroCard plCard = new HeroCard() * { * Title = text[j].cardTitle, * Subtitle = text[j].cardText * }; * * Attachment plAttachment = plCard.ToAttachment(); * reply_err.Attachments.Add(plAttachment); * } * await connector.Conversations.SendToConversationAsync(reply_err); */ Activity reply_err = activity.CreateReply(); reply_err.Recipient = activity.From; reply_err.Type = "message"; reply_err.Text = "I'm sorry. I do not know what you mean."; var reply1 = await connector.Conversations.SendToConversationAsync(reply_err); } else { for (int i = 0; i < LuisDialogID.Count; i++) { Activity reply2 = activity.CreateReply(); reply2.Recipient = activity.From; reply2.Type = "message"; reply2.Attachments = new List <Attachment>(); reply2.AttachmentLayout = AttachmentLayoutTypes.Carousel; int dlgID = LuisDialogID[i].dlgId; List <DialogList> dlg = db.SelectDialog(dlgID); for (int n = 0; n < dlg.Count; n++) { string dlgType = dlg[n].dlgType; if (dlgType == TEXTDLG) { List <TextList> text = db.SelectDialogText(dlg[n].dlgId); for (int j = 0; j < text.Count; j++) { HeroCard plCard = new HeroCard() { Title = text[j].cardTitle, Subtitle = text[j].cardText }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } else if (dlgType == CARDDLG) { List <CardList> card = db.SelectDialogCard(dlg[n].dlgId); for (int j = 0; j < card.Count; j++) { List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); if (card[j].imgUrl != null) { cardImages.Add(new CardImage(url: card[j].imgUrl)); } if (card[j].btn1Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn1Context, Type = card[j].btn1Type, Title = card[j].btn1Title }; cardButtons.Add(plButton); } if (card[j].btn2Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn2Context, Type = card[j].btn2Type, Title = card[j].btn2Title }; cardButtons.Add(plButton); } if (card[j].btn3Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn3Context, Type = card[j].btn3Type, Title = card[j].btn3Title }; cardButtons.Add(plButton); } HeroCard plCard = new HeroCard() { Title = card[j].cardTitle, Subtitle = card[j].cardSubTitle, Images = cardImages, Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } else if (dlgType == MEDIADLG) { List <MediaList> media = db.SelectDialogMedia(dlg[n].dlgId); for (int j = 0; j < media.Count; j++) { List <MediaUrl> mediaURL = new List <MediaUrl>(); List <CardAction> cardButtons = new List <CardAction>(); if (media[j].mediaUrl != null) { mediaURL.Add(new MediaUrl(url: media[j].mediaUrl)); } if (media[j].btn1Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn1Context, Type = media[j].btn1Type, Title = media[j].btn1Title }; cardButtons.Add(plButton); } if (media[j].btn2Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn2Context, Type = media[j].btn2Type, Title = media[j].btn2Title }; cardButtons.Add(plButton); } if (media[j].btn3Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn3Context, Type = media[j].btn3Type, Title = media[j].btn3Title }; cardButtons.Add(plButton); } VideoCard plCard = new VideoCard() { Title = media[j].cardTitle, Text = media[j].cardText, Media = mediaURL, Buttons = cardButtons, Autostart = false }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } } var reply1 = await connector.Conversations.SendToConversationAsync(reply2); } } } else { /* * Activity reply_err = activity.CreateReply(); * reply_err.Recipient = activity.From; * reply_err.Type = "message"; * * List<TextList> text = db.SelectDialogText(1005); * * for (int j = 0; j < text.Count; j++) * { * HeroCard plCard = new HeroCard() * { * Title = text[j].cardTitle, * Subtitle = text[j].cardText * }; * * Attachment plAttachment = plCard.ToAttachment(); * reply_err.Attachments.Add(plAttachment); * } * await connector.Conversations.SendToConversationAsync(reply_err); */ Activity reply_err = activity.CreateReply(); reply_err.Recipient = activity.From; reply_err.Type = "message"; reply_err.Text = "I'm sorry. I do not know what you mean."; var reply1 = await connector.Conversations.SendToConversationAsync(reply_err); } } else { HandleSystemMessage(activity); } response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> /// the bot is running and we arnt holding up the bot while we're waiting for the API responce public async Task <HttpResponseMessage> Post([FromBody] Activity activity) // This is a http post that is looking for data // from the body // the message controller is passing the whole activity class { if (activity.Type == ActivityTypes.Message) // here the activity is a message { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); // The connector client is equating the variable connector to a new connector client with a uri that does the activity // WRITE CODE HERE StateClient stateClient = activity.GetStateClient(); BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id); contosoBot.Services.StockItem stock1; //var message = contosoBot.dbo.BuildVersion.sql; var phrase = activity.Text; HttpClient client = new HttpClient(); string rawData = await client.GetStringAsync(new Uri("http://dev.markitondemand.com/Api/v2/Quote/json?symbol=" + activity.Text)); stock1 = JsonConvert.DeserializeObject <StockItem>(rawData); string name = stock1.Name; float ChangePercentYTD = stock1.ChangePercentYTD; string Time = stock1.Timestamp; float MarketCap = stock1.MarketCap; float Open = stock1.Open; string symbol = stock1.Symbol; float LastPrice = stock1.LastPrice; // adding the HERO CARD Activity stockReply = activity.CreateReply($"Stock for the {name}"); stockReply.Recipient = activity.From; stockReply.Type = "message"; stockReply.Attachments = new List <Attachment>(); List <CardImage> cardImages = new List <CardImage>(); cardImages.Add(new CardImage(url: "http://megaicons.net/static/img/icons_title/31/98/title/ios7-stock-icon.png")); List <CardAction> cardButtons = new List <CardAction>(); CardAction plButton = new CardAction() { Value = "http://www.nasdaq.com/symbol/" + symbol + "/interactive-chart", Type = "openUrl", Title = "More Info" }; cardButtons.Add(plButton); ThumbnailCard plCard = new ThumbnailCard() { Title = name + ":", Subtitle = " On " + Time + " Stock Price is: $" + LastPrice + " With a market capitalization of: " + MarketCap + " And its Change in Year to Date percentage is: " + ChangePercentYTD + "%", Images = cardImages, Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); stockReply.Attachments.Add(plAttachment); await connector.Conversations.SendToConversationAsync(stockReply); } else { HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
public void SetNewPosition(Vector3 pos, bool endFlip = false) { action = new MoveCard(pos, movementSpeed, gameObject, endFlip); oldPos = pos; }
private static Attachment GetHeroCard_facebookMore(string title, string subtitle, string text, CardAction cardAction) { var heroCard = new UserHeroCard { Title = title, Subtitle = subtitle, Text = text, Buttons = new List <CardAction>() { cardAction }, }; return(heroCard.ToAttachment()); }
private static Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction) { var heroCard = new HeroCard { Title = title, Subtitle = subtitle, Text = text, Images = new List <CardImage>() { cardImage }, Buttons = new List <CardAction>() { cardAction }, }; return(heroCard.ToAttachment()); }
/// <summary> /// POST: api/Messages /// Recois un msg de l'usgaer et on y retourne une reponse /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { if (activity.Type == ActivityTypes.Message && activity.Text.ToLower() == "/random") { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); LineUp lineUp = RcHelpers.GetLineUp(RcContants_LineUp.REGION_GRAND_MTL); // Va chercher un index aleatoire var randomIndex = new Random(DateTime.Now.Millisecond).Next(0, lineUp.pagedList.items.Count - 1); // On extrait du tableau, l'article que nous voulons montrer a l'usager var article = lineUp.pagedList.items[randomIndex]; // Extraction du url de l'image var imageUrl = article.summaryMultimediaItem.concreteImages?.Find(x => x.dimensionRatio == "4:3")?.mediaLink.href; // Converti l'image en grandeur utilisable var imageBase64 = string.Empty; if (!string.IsNullOrEmpty(imageUrl)) { var base64 = imageUrl.TransformUrlToScaledImage(); imageBase64 = imageUrl.EndsWith("png") ? "data:image/png;base64," + base64 : "data:image/jpg;base64," + base64; } Activity reply = activity.CreateReply(""); reply.Recipient = activity.From; reply.Type = "message"; reply.Attachments = new List <Attachment>(); // Construit l'image en reponse List <CardImage> cardImages = new List <CardImage>(); cardImages.Add(new CardImage(url: imageBase64)); // Construit l'action qui va aller avec l'image List <CardAction> cardButtons = new List <CardAction>(); CardAction plButton = new CardAction() { Value = article.canonicalWebLink.href, Type = "openUrl", Title = "Voir plus" }; cardButtons.Add(plButton); // Construit la carte HeroCard plCard = new HeroCard() { Title = HttpUtility.HtmlDecode(article.title), Subtitle = "", Images = cardImages, Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); reply.Attachments.Add(plAttachment); await connector.Conversations.ReplyToActivityAsync(reply); } else if (activity.Type == ActivityTypes.Message) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); Activity reply = activity.CreateReply("Je ne connais qu'une commande. Utilisez /random"); await connector.Conversations.ReplyToActivityAsync(reply); } else { HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
public CardAction CreateShallowClone() { CardAction actionClone = new CardAction (); actionClone.Label = Label; actionClone.Id = Id; actionClone.Type = Type; return actionClone; // Not the view. never the view (don't want to hold view references for OnConfigurationChange) }
public async Task Mercadotecnia(IDialogContext context, IAwaitable <object> activity, LuisResult result) { Models.NewStartersDBEntities1 DB = new Models.NewStartersDBEntities1(); //Mis datos es literalmente todo lo de mi mismo (Bruno) se accede de la forma misDatos[0].foto var misDatos = (from dept in DB.Empleado_Departamento where dept.departamentoID == 2 select new { representate = dept.representanteID, jefe = dept.jefeID, dept = dept.departamentoID } ).ToList(); int id3 = (int)misDatos[0].dept; var datosJefe3 = (from depto in DB.Departamento where depto.departamentoID == id3 select new { ubicacion = depto.ubicacion } ).ToList(); string message = $"El departamento de Mercadotecnia se encuentra en {datosJefe3[0].ubicacion} y el contacto es:"; await context.PostAsync(message); int id = (int)misDatos[0].jefe; var datosJefe = (from jefe in DB.Empleado where jefe.empleadoID == id select new { nombre = jefe.nombre, apellido = jefe.apellido, sede = jefe.sede, foto = jefe.fotoURL, mail = jefe.mail, tel = jefe.numero } ).ToList(); int id2 = (int)misDatos[0].representate; var datosRep = (from representante in DB.Empleado where representante.empleadoID == id select new { nombre = representante.nombre, apellido = representante.apellido, sede = representante.sede } ).ToList(); List <CardImage> cardImages = new List <CardImage>(); HeroCard card = new HeroCard(); card.Title = $"{datosJefe[0].nombre} {datosJefe[0].apellido}"; card.Subtitle = "Jefe del departamento de mercadotecnia"; card.Text = $"Teléfono: {datosJefe[0].tel} \n"; card.Text += $"Correo: {datosJefe[0].mail}"; cardImages.Add(new CardImage(datosJefe[0].foto)); card.Images = cardImages; List <CardAction> cardButtons = new List <CardAction>(); CardAction callButton = new CardAction() { Value = $"tel:{datosJefe[0].tel}", Type = "call", Title = "Llamar" }; int sedeID = (int)datosJefe[0].sede; var ubicacion = (from s in DB.Sede where s.sedeID == sedeID select s.direccion).ToList(); CardAction mapButton = new CardAction() { Value = $"https://www.google.com.mx/maps/place/" + $"{ubicacion[0].Replace(" ", "+")}", Type = "openUrl", Title = "Ir a sede" }; cardButtons.Add(callButton); cardButtons.Add(mapButton); card.Buttons = cardButtons; Attachment att = card.ToAttachment(); IMessageActivity reply = context.MakeMessage(); reply.Attachments.Add(att); await context.PostAsync(reply); context.Wait(MessageReceived); return; }
public async Task NombreSublevados(IDialogContext context, IAwaitable <object> activity, LuisResult result) { string message = $""; Models.NewStartersDBEntities1 DB = new Models.NewStartersDBEntities1(); //Mis datos es literalmente todo lo de mi mismo (Bruno) se accede de la forma misDatos[0].foto var misDatos = (from yo in DB.Empleado where yo.empleadoID == 6 select new { nombre = yo.nombre, apellido = yo.apellido, jefeId = yo.jefeInmediatoID, puesto = yo.puesto, sede = yo.sede, departamentoID = yo.departamento, foto = yo.fotoURL, jerarquia = yo.jerarquia, empleadoID = yo.empleadoID } ).ToList(); int id = (int)misDatos[0].empleadoID; System.Diagnostics.Debug.WriteLine($"id: {id}"); var datosEmpleados = (from empleado in DB.Empleado where empleado.jefeInmediatoID == id select new { nombre = empleado.nombre, apellido = empleado.apellido, sede = empleado.sede, idPrueba = empleado.empleadoID, foto = empleado.fotoURL, tel = empleado.numero, mail = empleado.mail } ).ToList(); if (datosEmpleados.Count() == 0) { message += "De momento no tienes registrados empleados"; await context.PostAsync(message); context.Wait(MessageReceived); return; } else { for (int i = 0; i < datosEmpleados.Count; i++) { if (i == 0) { message += $"Tus empleados son: "; await context.PostAsync(message); } List <CardImage> cardImages = new List <CardImage>(); HeroCard card = new HeroCard(); card.Title = $"{datosEmpleados[i].nombre} {datosEmpleados[i].apellido}"; card.Subtitle = "Datos de contacto:"; card.Text = $"Teléfono: {datosEmpleados[i].tel} \n"; card.Text += $"Correo: {datosEmpleados[i].mail}"; cardImages.Add(new CardImage(datosEmpleados[i].foto)); card.Images = cardImages; List <CardAction> cardButtons = new List <CardAction>(); CardAction callButton = new CardAction() { Value = $"tel:{datosEmpleados[i].tel}", Type = "call", Title = "Llamar" }; int sedeID = (int)datosEmpleados[i].sede; var ubicacion = (from s in DB.Sede where s.sedeID == sedeID select s.direccion).ToList(); CardAction mapButton = new CardAction() { Value = $"https://www.google.com.mx/maps/place/" + $"{ubicacion[0].Replace(" ", "+")}", Type = "openUrl", Title = "Ir a sede" }; cardButtons.Add(callButton); cardButtons.Add(mapButton); card.Buttons = cardButtons; Attachment att = card.ToAttachment(); IMessageActivity reply = context.MakeMessage(); reply.Attachments.Add(att); await context.PostAsync(reply); } } await context.PostAsync(message); context.Wait(MessageReceived); return; }
public async Task FindSpeaker(IDialogContext context, LuisResult result) { var reply = context.MakeMessage(); string topic = ""; string location = ""; if (result.Entities.Count > 0) { var ent = new EntityRecommendation(); bool hasTopic = result.TryFindEntity("topic", out ent); topic = (hasTopic ? ent.Entity : ""); bool hasLocation = result.TryFindEntity("location", out ent); location = (hasLocation ? ent.Entity : ""); await context.PostAsync("Searching with *topic* = **" + topic + "** and *location* = **" + location + "**"); if (!hasLocation) { await context.PostAsync("What state do you want a speaker in?"); var adaptive = new HeroCard(); List <CardAction> cardButtons = new List <CardAction>(); CardAction p1Button = new CardAction("button") { Value = $"Find Speaker {topic} New South Wales", Title = "New South Wales", Type = ActionTypes.PostBack }; CardAction p2Button = new CardAction("button") { Value = $"Find Speaker {topic} Victoria", Title = "Victoria", Type = ActionTypes.PostBack }; CardAction p3Button = new CardAction("button") { Value = $"Find Speaker {topic} Queensland", Title = "Queensland", Type = ActionTypes.PostBack }; cardButtons.Add(p1Button); cardButtons.Add(p2Button); cardButtons.Add(p3Button); adaptive.Buttons = cardButtons; var attach = adaptive.ToAttachment(); reply.Attachments.Add(attach); await context.PostAsync(reply); context.Wait(this.MessageReceived); } else if (hasTopic && hasLocation) { if (location.Equals("nsw") || location.Equals("sydney")) { location = "new south wales"; } else if (location.Equals("qld") || location.Equals("brisbane")) { location = "queensland"; } else if (location.Equals("vic") || location.Equals("melbourne")) { location = "victoria"; } if (!(location.Equals("new south wales") || location.Equals("queensland") || location.Equals("victoria"))) { hasLocation = false; } if (hasLocation) { var db = new DocumentDbSettings(); db.Connect(); List <Profile> profiles = db.SearchTopic(topic); Random rnd = new Random(); IEnumerable <Profile> res = profiles.Where(p => p.tags.Any(m => m.Contains(topic))).Where(c => c.states.Any(m => m.Contains(location))); var filteredProfiles = res.ToList <Profile>().OrderBy(p => rnd.Next()); if (filteredProfiles.Count() > 0) { reply.Attachments.Clear(); reply.AttachmentLayout = AttachmentLayoutTypes.Carousel; foreach (Profile p in filteredProfiles) { //Site and Email buttons on each card. List <CardAction> buttons = new List <CardAction>(); CardAction siteButton = new CardAction("button") { Value = $"{p.website}", Title = "Website", Type = ActionTypes.OpenUrl }; CardAction emailButton = new CardAction("button") { Value = $"mailto:{p.email}", Title = "Email", Type = ActionTypes.OpenUrl }; buttons.Add(siteButton); buttons.Add(emailButton); var hero = new HeroCard(); hero.Subtitle = p.slogan; hero.Title = p.name; var bioText = p.bio; //var bioTrunc = TruncateText(bioText, 220); //bioTrunc += "..."; hero.Text = bioText; var image = new CardImage(); image.Url = "http://tebot2.azurewebsites.net" + p.picture; hero.Images.Add(image); hero.Buttons = buttons; var heroAttach = hero.ToAttachment(); reply.Attachments.Add(heroAttach); } await context.PostAsync(reply); context.Wait(this.MessageReceived); } } else { await context.PostAsync("Please search for speakers in New South Wales, Queensland or Victoria"); } } else { await context.PostAsync("Topic unable to be captured."); } } else { await context.PostAsync("Topic could not be found. Please try another topic."); } }
internal static FacebookQuickReply ToFacebookQuickReply(this CardAction button) { return(new FacebookQuickReply(contentType: FacebookQuickReply.ContentTypes.Text, title: button.Title, payload: button.Value, image: button.Image)); }
private void createActionMenu(CardAction action, List<Cost> costs) { List<ActionValPair> pairs = new List<ActionValPair>(); if (action.actions.Any(x => x == Toolbox.BasicAction.Source_Uses)){ pairs.Add (new ActionValPair(action.sourceVal, Toolbox.BasicAction.Source_Uses)); } if (action.actions.Any(x => x == Toolbox.BasicAction.Add_Energy_Blue)){ pairs.Add (new ActionValPair(action.blueVal, Toolbox.BasicAction.Add_Energy_Blue)); } if (action.actions.Any(x => x == Toolbox.BasicAction.Add_Energy_Red)){ pairs.Add (new ActionValPair(action.redVal, Toolbox.BasicAction.Add_Energy_Red)); } if (action.actions.Any(x => x == Toolbox.BasicAction.Add_Energy_Green)){ pairs.Add (new ActionValPair(action.greenVal, Toolbox.BasicAction.Add_Energy_Green)); } if (action.actions.Any(x => x == Toolbox.BasicAction.Add_Energy_White)){ pairs.Add (new ActionValPair(action.whiteVal, Toolbox.BasicAction.Add_Energy_White)); } if (action.actions.Any(x => x == Toolbox.BasicAction.Add_Energy_Dark)){ pairs.Add (new ActionValPair(action.darkVal, Toolbox.BasicAction.Add_Energy_Dark)); } switch (player.turnPhase) { case Toolbox.TurnPhase.Move: if (action.actions.Any(x => x == Toolbox.BasicAction.Move)){ pairs.Add (new ActionValPair(action.moveVal, Toolbox.BasicAction.Move)); } if (action.actions.Any(x => x == Toolbox.BasicAction.Heal)){ pairs.Add (new ActionValPair(action.healVal, Toolbox.BasicAction.Heal)); } break; case Toolbox.TurnPhase.Action: if(player.isBattling){ switch (player.battlePhase){ case Toolbox.BattlePhase.Ranged: if (action.actions.Any(x => x == Toolbox.BasicAction.Ranged_Attack)){ pairs.Add (new ActionValPair(action.attackVal, Toolbox.BasicAction.Ranged_Attack, action.attackColour)); } break; case Toolbox.BattlePhase.Block: if (action.actions.Any(x => x == Toolbox.BasicAction.Block)){ pairs.Add (new ActionValPair(action.blockVal, Toolbox.BasicAction.Block, action.blockColour)); } break; case Toolbox.BattlePhase.Attack: if (action.actions.Any(x => x == Toolbox.BasicAction.Attack || x == Toolbox.BasicAction.Ranged_Attack)){ pairs.Add (new ActionValPair(action.attackVal, Toolbox.BasicAction.Attack, action.attackColour)); } break; default: break; } } else { if (action.actions.Any(x => x == Toolbox.BasicAction.Influence)){ pairs.Add (new ActionValPair(action.influenceVal, Toolbox.BasicAction.Influence)); } } break; default: break; } GameObject actionsMenu; if(pairs.Count == 0){ actionsMenu = (GameObject) Instantiate(Resources.Load("Prefabs/OneButtonModal")); actionsMenu.transform.GetComponentInChildren<Button>().onClick.AddListener(() => {Destroy (actionsMenu);}); actionsMenu.transform.SetParent(player.handCanvas.transform, false); actionsMenu.transform.GetComponentInChildren<Text>().text = "No actions available at this time"; Button firstButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "First Button"); firstButton.GetComponentInChildren<Text>().text = "Exit"; firstButton.onClick.AddListener(() => {Destroy (actionsMenu);}); } else if (pairs.Count == 1) { actionsMenu = (GameObject) Instantiate(Resources.Load("Prefabs/OneButtonModal")); actionsMenu.transform.GetComponentInChildren<Button>().onClick.AddListener(() => {Destroy (actionsMenu);}); actionsMenu.transform.SetParent(player.handCanvas.transform, false); actionsMenu.transform.GetComponentInChildren<Text>().text = "Choose Action " + CostString(costs); Button firstButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "First Button"); firstButton.GetComponentInChildren<Text>().text = ButtonString(pairs[0]); ApplyActionToButton(firstButton, pairs[0], costs, actionsMenu); firstButton.onClick.AddListener(() => {Destroy (actionsMenu);}); } else if (pairs.Count == 2) { actionsMenu = (GameObject) Instantiate(Resources.Load("Prefabs/TwoButtonModal")); actionsMenu.transform.GetComponentInChildren<Button>().onClick.AddListener(() => {Destroy (actionsMenu);}); actionsMenu.transform.SetParent(player.handCanvas.transform, false); actionsMenu.transform.GetComponentInChildren<Text>().text = "Choose Action" + CostString(costs); Button firstButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "First Button"); firstButton.GetComponentInChildren<Text>().text = ButtonString(pairs[0]); ApplyActionToButton(firstButton, pairs[0], costs, actionsMenu); firstButton.onClick.AddListener(() => {Destroy (actionsMenu);}); Button secondButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "Second Button"); secondButton.GetComponentInChildren<Text>().text = pairs[1].action.ToString() + " " + pairs[1].val.ToString(); ApplyActionToButton(secondButton, pairs[1], costs, actionsMenu); firstButton.onClick.AddListener(() => {Destroy (actionsMenu);}); } else if (pairs.Count == 3) { actionsMenu = (GameObject) Instantiate(Resources.Load("Prefabs/ThreeButtonModal")); actionsMenu.transform.GetComponentInChildren<Button>().onClick.AddListener(() => {Destroy (actionsMenu);}); actionsMenu.transform.SetParent(player.handCanvas.transform, false); actionsMenu.transform.GetComponentInChildren<Text>().text = "Choose Action" + CostString(costs); Button firstButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "First Button"); firstButton.GetComponentInChildren<Text>().text = ButtonString(pairs[0]); ApplyActionToButton(firstButton, pairs[0], costs, actionsMenu); firstButton.onClick.AddListener(() => {Destroy (actionsMenu);}); Button secondButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "Second Button"); secondButton.GetComponentInChildren<Text>().text = ButtonString(pairs[1]); ApplyActionToButton(secondButton, pairs[1], costs, actionsMenu); firstButton.onClick.AddListener(() => {Destroy (actionsMenu);}); Button thirdButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "Third Button"); thirdButton.GetComponentInChildren<Text>().text = ButtonString(pairs[2]); ApplyActionToButton(thirdButton, pairs[2], costs, actionsMenu); thirdButton.onClick.AddListener(() => {Destroy (actionsMenu);}); } else if (pairs.Count == 4) { actionsMenu = (GameObject) Instantiate(Resources.Load("Prefabs/FourButtonModal")); actionsMenu.transform.GetComponentInChildren<Button>().onClick.AddListener(() => {Destroy (actionsMenu);}); actionsMenu.transform.SetParent(player.handCanvas.transform, false); actionsMenu.transform.GetComponentInChildren<Text>().text = "Choose Action" + CostString(costs); Button firstButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "First Button"); firstButton.GetComponentInChildren<Text>().text = ButtonString(pairs[0]); ApplyActionToButton(firstButton, pairs[0], costs, actionsMenu); firstButton.onClick.AddListener(() => {Destroy (actionsMenu);}); Button secondButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "Second Button"); secondButton.GetComponentInChildren<Text>().text = ButtonString(pairs[1]); ApplyActionToButton(secondButton, pairs[1], costs, actionsMenu); firstButton.onClick.AddListener(() => {Destroy (actionsMenu);}); Button thirdButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "Third Button"); thirdButton.GetComponentInChildren<Text>().text = ButtonString(pairs[2]); ApplyActionToButton(thirdButton, pairs[2], costs, actionsMenu); thirdButton.onClick.AddListener(() => {Destroy (actionsMenu);}); Button fourthButton = actionsMenu.transform.GetComponentsInChildren<Button>().First(x => x.gameObject.name == "Fourth Button"); fourthButton.GetComponentInChildren<Text>().text = ButtonString(pairs[3]); ApplyActionToButton(fourthButton, pairs[3], costs, actionsMenu); fourthButton.onClick.AddListener(() => {Destroy (actionsMenu);}); } }
public static List<Card> GenerateDeck() { List<Card> cards = new List<Card>(); Card tramway = new Card("Tramway", 4, new List<CardAction>(), null); CardAction cardAction = new CardAction(); cardAction.TypeEvent = EventEnum.CARD_BOUGHT; cardAction.LifeTime = LifeTimeEnum.ONE_SHOT; cardAction.EffectList += cardAction.ImpactVP; cardAction.ImpactedPlayers += cardAction.SelectCurrentPlayer; cardAction.Amount = 2; tramway.CardActions.Add(cardAction); cards.Add(tramway); Card tank = new Card("Tank", 4, new List<CardAction>(), null); cardAction = new CardAction(); cardAction.TypeEvent = EventEnum.CARD_BOUGHT; cardAction.LifeTime = LifeTimeEnum.ONE_SHOT; cardAction.EffectList += cardAction.ImpactVP; cardAction.Amount = 4; cardAction.ImpactedPlayers += cardAction.SelectCurrentPlayer; tank.CardActions.Add(cardAction); cardAction = new CardAction(); cardAction.TypeEvent = EventEnum.CARD_BOUGHT; cardAction.LifeTime = LifeTimeEnum.ONE_SHOT; cardAction.EffectList += cardAction.ImpactHp; cardAction.Amount = -3; cardAction.ImpactedPlayers += cardAction.SelectCurrentPlayer; tank.CardActions.Add(cardAction); cards.Add(tank); Card soin = new Card("Soin", 3, new List<CardAction>(), null); cardAction = new CardAction(); cardAction.TypeEvent = EventEnum.CARD_BOUGHT; cardAction.LifeTime = LifeTimeEnum.ONE_SHOT; cardAction.EffectList += cardAction.ImpactHp; cardAction.Amount = 2; cardAction.ImpactedPlayers = cardAction.SelectCurrentPlayer; soin.CardActions.Add(cardAction); cards.Add(soin); Card cafeDuCoin = new Card("Cafe Du Coin", 3, new List<CardAction>(), null); cardAction = new CardAction(); cardAction.TypeEvent = EventEnum.CARD_BOUGHT; cardAction.LifeTime = LifeTimeEnum.ONE_SHOT; cardAction.EffectList += cardAction.ImpactVP; cardAction.Amount = 1; cardAction.ImpactedPlayers += cardAction.SelectCurrentPlayer; cafeDuCoin.CardActions.Add(cardAction); cards.Add(cafeDuCoin); Card raffinerieDeGaz = new Card("Raffinerie de gaz", 6, new List<CardAction>(), null); cardAction = new CardAction(); cardAction.TypeEvent = EventEnum.CARD_BOUGHT; cardAction.LifeTime = LifeTimeEnum.ONE_SHOT; cardAction.EffectList += cardAction.ImpactHp; cardAction.Amount = -3; raffinerieDeGaz.CardActions.Add(cardAction); cardAction = new CardAction(); cardAction.TypeEvent = EventEnum.CARD_BOUGHT; cardAction.LifeTime = LifeTimeEnum.ONE_SHOT; cardAction.EffectList += cardAction.ImpactVP; cardAction.Amount = 2; raffinerieDeGaz.CardActions.Add(cardAction); cards.Add(raffinerieDeGaz); return CardShuffle(cards); }
public static Attachment GetThumbnailCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction) { var thumbNailCard = new ThumbnailCard { Title = title, Subtitle = subtitle, Text = text, Images = new List <CardImage>() { cardImage }, Buttons = new List <CardAction>() { cardAction }, }; return(thumbNailCard.ToAttachment()); }
public async Task NombreJefeInmediatoIntent(IDialogContext context, IAwaitable <object> activity, LuisResult result) { string message = $""; Models.NewStartersDBEntities1 DB = new Models.NewStartersDBEntities1(); HeroCard card = new HeroCard(); List <CardImage> cardImages = new List <CardImage>(); card.Title = "Jefe"; //Mis datos es literalmente todo lo de mi mismo (Bruno) se accede de la forma misDatos[0].foto var misDatos = (from yo in DB.Empleado where yo.empleadoID == 6 select new { nombre = yo.nombre, apellido = yo.apellido, jefeId = yo.jefeInmediatoID, puesto = yo.puesto, sede = yo.sede, departamentoID = yo.departamento, foto = yo.fotoURL, jerarquia = yo.jerarquia } ).ToList(); int id = (int)misDatos[0].jefeId; var datosJefe = (from jefe in DB.Empleado where jefe.empleadoID == id select new { nombre = jefe.nombre, apellido = jefe.apellido, sede = jefe.sede, foto = jefe.fotoURL, tel = jefe.numero, mail = jefe.mail } ).ToList(); cardImages.Add(new CardImage(datosJefe[0].foto)); card.Images = cardImages; card.Subtitle = $"{datosJefe[0].nombre} {datosJefe[0].apellido}"; card.Text = $"Tu jefe es {datosJefe[0].nombre} \nCorreo: {datosJefe[0].mail}"; List <CardAction> cardButtons = new List <CardAction>(); CardAction callButton = new CardAction() { Value = $"tel:{datosJefe[0].tel}", Type = "call", Title = "Llamar" }; int sedeID = (int)datosJefe[0].sede; var ubicacion = (from s in DB.Sede where s.sedeID == sedeID select s.direccion).ToList(); CardAction mapButton = new CardAction() { Value = $"https://www.google.com.mx/maps/place/" + $"{ubicacion[0].Replace(" ", "+")}", Type = "openUrl", Title = "Ir a sede" }; cardButtons.Add(callButton); cardButtons.Add(mapButton); card.Buttons = cardButtons; Attachment att = card.ToAttachment(); IMessageActivity reply = context.MakeMessage(); reply.Attachments.Add(att); await context.PostAsync(reply); context.Wait(MessageReceived); return; }
/// <summary> /// Answers current card with specified grade and calculate outcomes. No modification /// saved. /// </summary> /// <param name="card">Card instance.</param> /// <param name="grade">The grade.</param> public static CardAction Answer(this Card card, Grade grade) { CardAction cardAction = CardAction.Invalid; card.CurrentReviewTime = DateTime.Now.UnixTimestamp(); // New card if (card.IsNew()) { card.UpdateLearningStep(true); } // Handle card learning if (card.IsLearning()) { switch (grade) { case Grade.FailSevere: case Grade.FailMedium: case Grade.Fail: // TODO: If relearning, further decrease ease and interval ? cardAction = card.UpdateLearningStep(true); break; case Grade.Hard: case Grade.Good: cardAction = card.UpdateLearningStep(); break; case Grade.Easy: cardAction = card.Graduate(true); break; } } // Handle card review (graduated card) else { switch (grade) { case Grade.FailSevere: case Grade.FailMedium: case Grade.Fail: cardAction = card.Lapse(grade); break; case Grade.Hard: case Grade.Good: case Grade.Easy: cardAction = card.Review(grade); break; } } // Update card properties card.MiscState = CardMiscStateFlag.None; card.Reviews++; card.LastModified = card.CurrentReviewTime; if (cardAction == CardAction.Delete) { card.PracticeState = PracticeState.Deleted; } return(cardAction); }
public async Task NombresCompas(IDialogContext context, IAwaitable <object> activity, LuisResult result) { Models.NewStartersDBEntities1 DB = new Models.NewStartersDBEntities1(); //Mis datos es literalmente todo lo de mi mismo (Bruno) se accede de la forma misDatos[0].foto var misDatos = (from compas in DB.Empleado where compas.jefeInmediatoID == 4 select new { nombre = compas.nombre, apellido = compas.apellido, numero = compas.numero, puesto = compas.puesto, mail = compas.mail, foto = compas.fotoURL, tel = compas.numero, sede = compas.sede } ).ToList(); string message = $"Tus compañeros de trabajo de tu jerarquia son:"; await context.PostAsync(message); foreach (var item in misDatos) { if (!item.nombre.Equals("Bruno")) { List <CardImage> cardImages = new List <CardImage>(); HeroCard card = new HeroCard(); card.Title = $"{item.nombre} {item.apellido}"; card.Subtitle = $"{item.puesto}"; card.Text = $"Teléfono: {item.numero} \n"; card.Text += $"Correo: {item.mail}"; cardImages.Add(new CardImage(item.foto)); card.Images = cardImages; List <CardAction> cardButtons = new List <CardAction>(); CardAction callButton = new CardAction() { Value = $"tel:{item.tel}", Type = "call", Title = "Llamar" }; int sedeID = (int)item.sede; var ubicacion = (from s in DB.Sede where s.sedeID == sedeID select s.direccion).ToList(); CardAction mapButton = new CardAction() { Value = $"https://www.google.com.mx/maps/place/" + $"{ubicacion[0].Replace(" ", "+")}", Type = "openUrl", Title = "Ir a sede" }; cardButtons.Add(callButton); cardButtons.Add(mapButton); card.Buttons = cardButtons; Attachment att = card.ToAttachment(); IMessageActivity reply = context.MakeMessage(); reply.Attachments.Add(att); await context.PostAsync(reply); } } context.Wait(MessageReceived); return; }
/// <summary> /// Wrap BotBuilder action into AdaptiveCard submit action. /// </summary> /// <param name="action"> The instance of adaptive card submit action.</param> /// <param name="targetAction"> Target action to be adapted.</param> public static void RepresentAsBotBuilderAction(this AdaptiveCards.AdaptiveSubmitAction action, CardAction targetAction) { var wrappedAction = new CardAction { Type = targetAction.Type, Value = targetAction.Value, Text = targetAction.Text, DisplayText = targetAction.DisplayText, }; JsonSerializerSettings serializerSettings = new JsonSerializerSettings(); serializerSettings.NullValueHandling = NullValueHandling.Ignore; string jsonStr = action.DataJson == null ? "{}" : action.DataJson; JToken dataJson = JObject.Parse(jsonStr); dataJson["msteams"] = JObject.FromObject(wrappedAction, JsonSerializer.Create(serializerSettings)); action.Title = targetAction.Title; action.DataJson = dataJson.ToString(); }
public async Task CuantoCuestaItent(IDialogContext context, IAwaitable <object> activity, LuisResult result) { string toSearch = ""; toSearch = result.Query.ToString().ToLower().Replace("cuanto cuesta una ", "").Replace("cuanto cuesta un ", "").Replace("?", "").Replace(" ", "-"); try { System.Diagnostics.Debug.WriteLine("https://listado.mercadolibre.com.mx/" + toSearch); HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb(); HtmlAgilityPack.HtmlDocument doc = web.Load("https://listado.mercadolibre.com.mx/" + toSearch); var titles = doc.DocumentNode.SelectNodes("//div[@class='item__info-container ']/div/h2/a").ToList(); var prices = doc.DocumentNode.SelectNodes("//div[@class='item__info-container ']/div/div[@class='price__container']").ToList(); var images = doc.DocumentNode.SelectNodes("//a[@class='figure item-image item__js-link']/img[@src]").ToList(); var links = doc.DocumentNode.SelectNodes("//div[@class='image-content']/a[@href]").ToList(); var locations = doc.DocumentNode.SelectNodes("//div[@class='item__condition']").ToList(); await context.PostAsync("Encontré algo para ti, espero que sea de utilidad **:)**"); Random rn = new Random(); int index = rn.Next(0, images.Count); List <CardImage> cardImages = new List <CardImage>(); HeroCard card = new HeroCard(); card.Title = $"{titles[index].InnerText}"; card.Subtitle = $"Disponible en{locations[index].InnerText.Split('-')[1]}"; card.Text = $"Precio: {prices[index].InnerText}"; cardImages.Add(new CardImage(images[index].GetAttributeValue("src", null))); card.Images = cardImages; List <CardAction> cardButtons = new List <CardAction>(); CardAction buyButton = new CardAction() { Value = $"{links[index].GetAttributeValue("href", null)}", Type = "openUrl", Title = "Revisar producto" }; cardButtons.Add(buyButton); card.Buttons = cardButtons; Attachment att = card.ToAttachment(); IMessageActivity reply = context.MakeMessage(); reply.Attachments.Add(att); await context.PostAsync(reply); return; } catch (Exception e) { System.Diagnostics.Debug.WriteLine("https://listado.mercadolibre.com.mx/" + toSearch); HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb(); HtmlAgilityPack.HtmlDocument doc = web.Load("https://listado.mercadolibre.com.mx/" + toSearch); var prices = doc.DocumentNode.SelectNodes("//div[@class='item__price ']").ToList(); var images = doc.DocumentNode.SelectNodes("//a[@class='item-link item__js-link']/img[@src]").ToList(); var links = doc.DocumentNode.SelectNodes("//div[@class='carousel']/ul/li/a[@href]").ToList(); await context.PostAsync("Encontré algo para ti, espero que sea de utilidad **:)**"); Random rn = new Random(); int index = rn.Next(0, images.Count); List <CardImage> cardImages = new List <CardImage>(); HeroCard card = new HeroCard(); card.Title = $"{toSearch.Replace("-", " ")}"; card.Text = $"Precio: {prices[index].InnerText}"; cardImages.Add(new CardImage(images[index].GetAttributeValue("src", null))); card.Images = cardImages; List <CardAction> cardButtons = new List <CardAction>(); CardAction buyButton = new CardAction() { Value = $"{links[index].GetAttributeValue("href", null)}", Type = "openUrl", Title = "Revisar producto" }; cardButtons.Add(buyButton); card.Buttons = cardButtons; Attachment att = card.ToAttachment(); IMessageActivity reply = context.MakeMessage(); reply.Attachments.Add(att); await context.PostAsync(reply); } }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { //HttpResponseMessage response; var intentList = new List <string>(); var entityList = new List <string>(); //if (activity.Type == ActivityTypes.ConversationUpdate) if (activity.Type == ActivityTypes.ConversationUpdate && activity.MembersAdded.Any(m => m.Id == activity.Recipient.Id)) { DateTime startTime = DateTime.Now; Debug.WriteLine("* ConversationUpdate | DB conn : " + activity.Type); //Db DbConnect db = new DbConnect(); //if (activity.MembersAdded != null && activity.MembersAdded.Any()) { //if (activity.MembersAdded.Any()) //{ /* * foreach (var newMember in activity.MembersAdded) * { * if (newMember.Id != activity.Recipient.Id) * { */ List <DialogList> dlg = db.SelectInitDialog(); ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); Debug.WriteLine("* ConversationUpdate | dlg.Count : " + dlg.Count); for (int n = 0; n < dlg.Count; n++) { Debug.WriteLine("* ConversationUpdate | dlgId : " + n + "." + dlg[n].dlgId); Activity reply2 = activity.CreateReply(); reply2.Recipient = activity.From; reply2.Type = "message"; reply2.Attachments = new List <Attachment>(); reply2.AttachmentLayout = AttachmentLayoutTypes.Carousel; List <CardList> card = db.SelectDialogCard(dlg[n].dlgId); List <TextList> text = db.SelectDialogText(dlg[n].dlgId); List <MediaList> media = db.SelectDialogMedia(dlg[n].dlgId); for (int i = 0; i < text.Count; i++) { HeroCard plCard = new HeroCard() { Title = text[i].cardTitle, Subtitle = text[i].cardText }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } for (int i = 0; i < card.Count; i++) { List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); if (card[i].imgUrl != null) { cardImages.Add(new CardImage(url: card[i].imgUrl)); } if (card[i].btn1Type != null) { CardAction plButton = new CardAction() { Value = card[i].btn1Context, Type = card[i].btn1Type, Title = card[i].btn1Title }; cardButtons.Add(plButton); } if (card[i].btn2Type != null) { CardAction plButton = new CardAction() { Value = card[i].btn2Context, Type = card[i].btn2Type, Title = card[i].btn2Title }; cardButtons.Add(plButton); } if (card[i].btn3Type != null) { CardAction plButton = new CardAction() { Value = card[i].btn3Context, Type = card[i].btn3Type, Title = card[i].btn3Title }; cardButtons.Add(plButton); } HeroCard plCard = new HeroCard() { Title = card[i].cardTitle, Subtitle = card[i].cardSubTitle, Images = cardImages, Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } for (int i = 0; i < media.Count; i++) { List <MediaUrl> mediaURL = new List <MediaUrl>(); List <CardAction> cardButtons = new List <CardAction>(); if (media[i].mediaUrl != null) { mediaURL.Add(new MediaUrl(url: media[i].mediaUrl)); } if (media[i].btn1Type != null) { CardAction plButton = new CardAction() { Value = media[i].btn1Context, Type = media[i].btn1Type, Title = media[i].btn1Title }; cardButtons.Add(plButton); } if (media[i].btn2Type != null) { CardAction plButton = new CardAction() { Value = media[i].btn2Context, Type = media[i].btn2Type, Title = media[i].btn2Title }; cardButtons.Add(plButton); } if (media[i].btn3Type != null) { CardAction plButton = new CardAction() { Value = media[i].btn3Context, Type = media[i].btn3Type, Title = media[i].btn3Title }; cardButtons.Add(plButton); } VideoCard plCard = new VideoCard() { Title = media[i].cardTitle, Text = media[i].cardText, Media = mediaURL, Buttons = cardButtons, Autostart = false }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } var reply1 = await connector.Conversations.SendToConversationAsync(reply2); } //} //} DateTime endTime = DateTime.Now; Debug.WriteLine("프로그램 수행시간 : {0}/ms", ((endTime - startTime).Milliseconds)); Debug.WriteLine("* activity.Type : " + activity.Type); Debug.WriteLine("* activity.Recipient.Id : " + activity.Recipient.Id); Debug.WriteLine("* activity.ServiceUrl : " + activity.ServiceUrl); //var welcome = ""; //var welcomeMsg = ""; //} } else if (activity.Type == ActivityTypes.Message) { //await Conversation.SendAsync(activity, () => new Dialogs.RootDialog()); Debug.WriteLine("* activity.Type == ActivityTypes.Message "); string orgMent = ""; string orgENGMent_history = ""; JObject Luis = new JObject(); DbConnect db = new DbConnect(); StateClient stateClient = activity.GetStateClient(); BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id); ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); orgMent = activity.Text; Debug.WriteLine("* orgMent : " + orgMent); Luis = await GetIntentFromBotLUIS(orgMent); float luisScore = (float)Luis["intents"][0]["score"]; int luisEntityCount = (int)Luis["entities"].Count(); Debug.WriteLine("* Luis Entity Count : " + luisEntityCount); Debug.WriteLine("* Luis Intents Score : " + luisScore); Debug.WriteLine(Luis.ToString()); // var json = new JObject(); json.Add("Conversationid", activity.ChannelId); json.Add("Authenticationkey", activity.Recipient.Id); json.Add("answer", orgMent); //Debug.WriteLine(json.ToString()); //Debug.WriteLine("json 1"); JArray conversations = new JArray(); var jsonConversations = new JObject(); jsonConversations.Add("Luisid", "SecCSChatBot"); jsonConversations.Add("Intent", (string)Luis["intents"][0]["intent"]); jsonConversations.Add("Message", orgMent); //Debug.WriteLine("json 2 | luisEntityCount:"+ luisEntityCount); //var jsonEntities = new JObject(); //string[] jsonEntities; JArray Entities = new JArray(); var jsonEntities = new JObject(); for (int i = 0; i < luisEntityCount; i++) { //Debug.WriteLine("json 2-1"); Entities.Insert(i, new JObject(new JProperty("Entity", (string)Luis["entities"][i]["entity"]))); //Debug.WriteLine("json 2-2"); } //Debug.WriteLine("json 3"); jsonConversations.Add("Entities", Entities); conversations.Add(jsonConversations); json.Add("conversations", conversations); //Debug.WriteLine("json 4"); Debug.WriteLine(json.ToString()); String sEntity = json.ToString(); String sendResult = await SendChat(sEntity); if (luisScore > 0 && luisEntityCount > 0) { string intent = (string)Luis["intents"][0]["intent"]; string entity = (string)Luis["entities"][0]["entity"]; Debug.WriteLine("* 1.intent : " + intent + " || entity : " + entity + " || orgment : " + orgMent); Debug.WriteLine("* 1-1.ChannelId : " + activity.ChannelId + " || From : " + activity.From.Id); intent = intent.Replace("\"", ""); entity = entity.Replace("\"", ""); entity = entity.Replace(" ", ""); //Debug.WriteLine("* sessionNo : " + sessionNo ); //Debug.WriteLine("LUIS_INTENT : " + (string)(context.Session["LUIS_INTENT"])); //Debug.WriteLine("LUIS_ENTITY : " + (string)(context.Session["LUIS_ENTITY"])); // sessionNo = sessionNo + 1; // intentList.Add(intent); entityList.Add(entity); // if (intent == "customerInfo") { var luisCustomerInfo = userData.GetProperty <string>("luisCustomerInfo"); if (entity == "김설현") { luisCustomerInfo = ""; } //var luisCustomerInfo = userData.GetProperty<string>("luisCustomerInfo"); luisCustomerInfo = luisCustomerInfo + "\n" + orgMent; userData.SetProperty <string>("luisCustomerInfo", luisCustomerInfo); Debug.WriteLine("1-1.intent : customerInfo || input : " + orgMent + " || entity : " + entity + " || luisCustomerInfo : " + luisCustomerInfo); } if (intent == "end") { Debug.WriteLine("* endCS | make Json START"); } //userData.SetProperty<List>(IList, intentList); userData.SetProperty <string>("luisIntent", intent); userData.SetProperty <string>("luisEntity", entity); userData.SetProperty <string>(intent, orgENGMent_history); Debug.WriteLine("* 2. orgENGMent_history : " + orgENGMent_history); await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); Debug.WriteLine("* activity.ChannelId : " + activity.ChannelId + " || activity.From.Id : " + activity.From.Id); List <LuisList> LuisDialogID = db.SelectLuis(intent, entity); if (LuisDialogID.Count == 0) { Debug.WriteLine("* NO LuisDialogID"); Activity reply_err = activity.CreateReply(); reply_err.Recipient = activity.From; reply_err.Type = "message"; reply_err.Text = "I'm sorry. I do not know what you mean."; var reply1 = await connector.Conversations.SendToConversationAsync(reply_err); } else { Debug.WriteLine("* YES LuisDialogID || LuisDialogID.Count : " + LuisDialogID.Count); for (int i = 0; i < LuisDialogID.Count; i++) { Activity reply2 = activity.CreateReply(); reply2.Recipient = activity.From; reply2.Type = "message"; reply2.Attachments = new List <Attachment>(); reply2.AttachmentLayout = AttachmentLayoutTypes.Carousel; int dlgID = LuisDialogID[i].dlgId; List <DialogList> dlg = db.SelectDialog(dlgID); for (int n = 0; n < dlg.Count; n++) { string dlgType = dlg[n].dlgType; if (dlgType == TEXTDLG) { List <TextList> text = db.SelectDialogText(dlg[n].dlgId); for (int j = 0; j < text.Count; j++) { HeroCard plCard = new HeroCard() { Title = text[j].cardTitle, Subtitle = text[j].cardText }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } else if (dlgType == CARDDLG) { List <CardList> card = db.SelectDialogCard(dlg[n].dlgId); for (int j = 0; j < card.Count; j++) { List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); if (card[j].imgUrl != null) { cardImages.Add(new CardImage(url: card[j].imgUrl)); } if (card[j].btn1Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn1Context, Type = card[j].btn1Type, Title = card[j].btn1Title }; cardButtons.Add(plButton); } if (card[j].btn2Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn2Context, Type = card[j].btn2Type, Title = card[j].btn2Title }; cardButtons.Add(plButton); } if (card[j].btn3Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn3Context, Type = card[j].btn3Type, Title = card[j].btn3Title }; cardButtons.Add(plButton); } var strCardSubTitle = card[j].cardSubTitle; if (card[j].dlgId == 2009) { //var customerInfo = userData.GetProperty<string>("luisCustomerInfo"); strCardSubTitle = userData.GetProperty <string>("luisCustomerInfo"); } HeroCard plCard = new HeroCard() { Title = card[j].cardTitle, //Subtitle = card[j].cardSubTitle, Subtitle = strCardSubTitle, Images = cardImages, Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } else if (dlgType == MEDIADLG) { List <MediaList> media = db.SelectDialogMedia(dlg[n].dlgId); for (int j = 0; j < media.Count; j++) { List <MediaUrl> mediaURL = new List <MediaUrl>(); List <CardAction> cardButtons = new List <CardAction>(); if (media[j].mediaUrl != null) { mediaURL.Add(new MediaUrl(url: media[j].mediaUrl)); } if (media[j].btn1Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn1Context, Type = media[j].btn1Type, Title = media[j].btn1Title }; cardButtons.Add(plButton); } if (media[j].btn2Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn2Context, Type = media[j].btn2Type, Title = media[j].btn2Title }; cardButtons.Add(plButton); } if (media[j].btn3Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn3Context, Type = media[j].btn3Type, Title = media[j].btn3Title }; cardButtons.Add(plButton); } VideoCard plCard = new VideoCard() { Title = media[j].cardTitle, Text = media[j].cardText, Media = mediaURL, Buttons = cardButtons, Autostart = false }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } } var reply1 = await connector.Conversations.SendToConversationAsync(reply2); } } } else { Debug.WriteLine("* NO Luis Score.. "); Debug.WriteLine(userData.ToString()); // var intentArray = intentList.ToArray(); foreach (string intent in intentList) { Debug.WriteLine("* intent[] :" + intent); //System.Console.WriteLine(prime); } Debug.WriteLine("intentList" + intentList); Activity reply_err = activity.CreateReply(); // var luisIntent = userData.GetProperty <string>("luisIntent"); var luisEntity = userData.GetProperty <string>("luisEntity"); Debug.WriteLine("** orgMent : " + orgMent + "| luisIntent : " + luisIntent + " | luisEntity : " + luisEntity); List <LuisList> LuisDialogID = db.SelectLuisSecond(activity.Text, luisIntent, luisEntity); if (LuisDialogID.Count == 0) { Debug.WriteLine("** NO LuisDialogID"); //Activity reply_err = activity.CreateReply(); reply_err.Recipient = activity.From; reply_err.Type = "message"; reply_err.Text = "I'm sorry. I do not know what you mean."; var reply1 = await connector.Conversations.SendToConversationAsync(reply_err); } else { Debug.WriteLine("** SelectLuisSecond() YES | LuisDialogID | LuisDialogID.Count : " + LuisDialogID.Count); for (int i = 0; i < LuisDialogID.Count; i++) { Activity reply2 = activity.CreateReply(); reply2.Recipient = activity.From; reply2.Type = "message"; reply2.Attachments = new List <Attachment>(); reply2.AttachmentLayout = AttachmentLayoutTypes.Carousel; int dlgID = LuisDialogID[i].dlgId; string dlgIntent = LuisDialogID[i].dlgIntent; string dlgEntities = LuisDialogID[i].dlgEntities; userData.SetProperty <string>("luisIntent", dlgIntent); userData.SetProperty <string>("luisEntity", dlgEntities); Debug.WriteLine("** userData.SetProperty > (" + dlgID + ") luisIntent: " + dlgIntent + "| luisEntity:" + dlgEntities); await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData); // SetDialogBizTripData if (dlgID == 2015) { Debug.WriteLine("* dlgID:2015 | make Json"); var bizTripJson = new JObject(); bizTripJson.Add("Conversationid", activity.ChannelId); bizTripJson.Add("Authenticationkey", activity.Recipient.Id); bizTripJson.Add("Modelname", "WD16J7800KW"); bizTripJson.Add("Conditions", "세탁기소음"); bizTripJson.Add("Customername", "김설현"); bizTripJson.Add("phonenumber", "010-6444-3434"); bizTripJson.Add("Address", "서울특별시 마포구 신수동 234-2 번지"); String sBizTrip = bizTripJson.ToString(); //Debug.WriteLine("* sendBizTrip || bizTripJson : "+ bizTripJson); String sendBizTripResult = await sendBizTrip(sBizTrip); Debug.WriteLine("* RETURN sendBizTripResult : " + sendBizTripResult); // sendBizTripResult JSON Parse START.. JObject parse = JObject.Parse(sendBizTripResult); JArray array = JArray.Parse(parse["Dialogs"].ToString()); string status = parse["Status"].ToString(); int dialogCount = int.Parse(parse["DialogCount"].ToString()); List <DialogJson> dialogs = new List <DialogJson>(); foreach (JObject itemObj in array) { DialogJson dialogTest = new DialogJson(); dialogTest.type = itemObj["Type"].ToString(); //dialogTest.title = itemObj["Title"].ToString(); dialogTest.text = itemObj["Text"].ToString(); dialogs.Add(dialogTest); } for (int j = 0; j < dialogCount; j++) { HeroCard plCard = new HeroCard() { Title = "", Subtitle = dialogs[j].text }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } else { List <DialogList> dlg = db.SelectDialog(dlgID); for (int n = 0; n < dlg.Count; n++) { string dlgType = dlg[n].dlgType; if (dlgType == TEXTDLG) { List <TextList> text = db.SelectDialogText(dlg[n].dlgId); for (int j = 0; j < text.Count; j++) { HeroCard plCard = new HeroCard() { Title = text[j].cardTitle, Subtitle = text[j].cardText }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } else if (dlgType == CARDDLG) { List <CardList> card = db.SelectDialogCard(dlg[n].dlgId); for (int j = 0; j < card.Count; j++) { List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); if (card[j].imgUrl != null) { cardImages.Add(new CardImage(url: card[j].imgUrl)); } if (card[j].btn1Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn1Context, Type = card[j].btn1Type, Title = card[j].btn1Title }; cardButtons.Add(plButton); } if (card[j].btn2Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn2Context, Type = card[j].btn2Type, Title = card[j].btn2Title }; cardButtons.Add(plButton); } if (card[j].btn3Type != null) { CardAction plButton = new CardAction() { Value = card[j].btn3Context, Type = card[j].btn3Type, Title = card[j].btn3Title }; cardButtons.Add(plButton); } HeroCard plCard = new HeroCard() { Title = card[j].cardTitle, Subtitle = card[j].cardSubTitle, Images = cardImages, Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } else if (dlgType == MEDIADLG) { List <MediaList> media = db.SelectDialogMedia(dlg[n].dlgId); for (int j = 0; j < media.Count; j++) { List <MediaUrl> mediaURL = new List <MediaUrl>(); List <CardAction> cardButtons = new List <CardAction>(); if (media[j].mediaUrl != null) { mediaURL.Add(new MediaUrl(url: media[j].mediaUrl)); } if (media[j].btn1Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn1Context, Type = media[j].btn1Type, Title = media[j].btn1Title }; cardButtons.Add(plButton); } if (media[j].btn2Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn2Context, Type = media[j].btn2Type, Title = media[j].btn2Title }; cardButtons.Add(plButton); } if (media[j].btn3Type != null) { CardAction plButton = new CardAction() { Value = media[j].btn3Context, Type = media[j].btn3Type, Title = media[j].btn3Title }; cardButtons.Add(plButton); } VideoCard plCard = new VideoCard() { Title = media[j].cardTitle, Text = media[j].cardText, Media = mediaURL, Buttons = cardButtons, Autostart = false }; Attachment plAttachment = plCard.ToAttachment(); reply2.Attachments.Add(plAttachment); } } } } var reply1 = await connector.Conversations.SendToConversationAsync(reply2); } } } } else { HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
void _CardSystem_RequestUnitSelection(CardData c, int numSelection, Player p, CardAction action, EndCardAction done) { // assume P is going to be the current player UnitSelection flags = UnitSelection.None; if (c.Type == CardType.Healing_Card) { flags = flags | UnitSelection.Inactive; } if (c.Type == CardType.Upgrade_Card) { flags = flags | UnitSelection.Active; flags = flags | UnitSelection.NotUpgraded; } if (c.Type == CardType.Tactic_Card) { flags = flags | UnitSelection.Active; flags = flags | UnitSelection.NotTempUpgraded; } _OverworldUI.ShowUnitSelectionUI(flags); int selectedUnits = 0; UIPlayerUnitTypeIndexCallback selectUnit = null; selectUnit = (PlayerType pt, UnitType u, int i) => { Unit unit = _GameStateHolder._ActivePlayer.PlayerArmy.GetUnits(u)[i]; selectedUnits++; // perform the action each time something is selected. This will only effect healing. // we don't want the player to be stuck with no units to select action(c, p, unit); // we reached the total? if (selectedUnits == numSelection) { // don't listen for namy more and hide the UI _OverworldUI._ArmyUI.OnClickUnit -= selectUnit; _OverworldUI.HideUnitSelectionUI(); done(true, c, p, unit); } }; _OverworldUI._ArmyUI.OnClickUnit += selectUnit; }
public AdaptiveCard GetAdaptiveCardForInterviewRequest(Candidate candidate, DateTime interviewDate) { var interviewers = _recruiterService.GetAllInterviewers().GetAwaiter().GetResult(); var command = new { commandId = AppCommands.ScheduleInterview, candidateId = candidate.CandidateId }; var wrapAction = new CardAction { Title = "Schedule", Value = command }; var action = new AdaptiveSubmitAction { Data = command }; action.RepresentAsBotBuilderAction(wrapAction); return(new AdaptiveCard { Version = "1.0", Body = new List <AdaptiveElement> { new AdaptiveTextBlock { Text = $"Set interview date for {candidate.Name}", Weight = AdaptiveTextWeight.Bolder, Size = AdaptiveTextSize.Large }, new AdaptiveColumnSet { Columns = new List <AdaptiveColumn> { new AdaptiveColumn { Width = AdaptiveColumnWidth.Auto, Items = new List <AdaptiveElement> { new AdaptiveImage { Url = new Uri(candidate.ProfilePicture), Size = AdaptiveImageSize.Medium, Style = AdaptiveImageStyle.Person } } }, new AdaptiveColumn { Width = AdaptiveColumnWidth.Stretch, Items = new List <AdaptiveElement> { new AdaptiveTextBlock { Text = $"TicketID: {candidate.Position.Ticketid}", Wrap = true }, new AdaptiveTextBlock { Text = $"Status: {candidate.Position.Status}", Spacing = AdaptiveSpacing.None, Wrap = true, IsSubtle = true } } } } }, new AdaptiveChoiceSetInput { Id = "interviewerId", Style = AdaptiveChoiceInputStyle.Compact, Choices = interviewers.Select(x => new AdaptiveChoice { Value = x.RecruiterId.ToString(), Title = x.Name }).ToList(), Value = Convert.ToString(interviewers[0].RecruiterId) }, new AdaptiveDateInput { Id = "interviewDate", Placeholder = "Enter in a date for the interview", Value = interviewDate.ToShortDateString() }, new AdaptiveChoiceSetInput { Id = "interviewType", Style = AdaptiveChoiceInputStyle.Compact, IsMultiSelect = false, Choices = new List <AdaptiveChoice> { new AdaptiveChoice { Title = "Phone screen", Value = "phoneScreen" }, new AdaptiveChoice { Title = "Full loop", Value = "fullLoop" }, new AdaptiveChoice { Title = "Follow-up", Value = "followUp" } }, Value = "phoneScreen" }, new AdaptiveToggleInput { Id = "isRemote", Title = "Remote interview" } }, Actions = new List <AdaptiveAction> { action } }); }
private Attachment getRecommendDialog(int rcmdDlgId) { //MEDIA 데이터 추출 Attachment returnAttachment = new Attachment(); List <Recommend_DLG_MEDIA> SelectRecommend_DLG_MEDIA = db.SelectRecommend_DLG_MEDIA(rcmdDlgId); if (rcmdDlgId != 4) { for (int i = 0; i < SelectRecommend_DLG_MEDIA.Count; i++) { //CardImage 입력 cardImage = new CardImage() { Url = SelectRecommend_DLG_MEDIA[i].media_url }; if (SelectRecommend_DLG_MEDIA[i].btn_1_context.Length != 0) { CardAction plButton = new CardAction() { Value = SelectRecommend_DLG_MEDIA[i].btn_1_context, Type = SelectRecommend_DLG_MEDIA[i].btn_1_type, Title = SelectRecommend_DLG_MEDIA[i].btn_1_title }; cardButtons.Add(plButton); } if (SelectRecommend_DLG_MEDIA[i].btn_2_context.Length != 0) { CardAction plButton = new CardAction() { Value = SelectRecommend_DLG_MEDIA[i].btn_2_context, Type = SelectRecommend_DLG_MEDIA[i].btn_2_type, Title = SelectRecommend_DLG_MEDIA[i].btn_2_title }; cardButtons.Add(plButton); } if (SelectRecommend_DLG_MEDIA[i].btn_3_context.Length != 0) { CardAction plButton = new CardAction() { Value = SelectRecommend_DLG_MEDIA[i].btn_3_context, Type = SelectRecommend_DLG_MEDIA[i].btn_3_type, Title = SelectRecommend_DLG_MEDIA[i].btn_3_title }; cardButtons.Add(plButton); } if (SelectRecommend_DLG_MEDIA[i].btn_4_context.Length != 0) { CardAction plButton = new CardAction() { Value = SelectRecommend_DLG_MEDIA[i].btn_4_context, Type = SelectRecommend_DLG_MEDIA[i].btn_4_type, Title = SelectRecommend_DLG_MEDIA[i].btn_4_title }; cardButtons.Add(plButton); } if (SelectRecommend_DLG_MEDIA[i].btn_5_context.Length != 0) { CardAction plButton = new CardAction() { Value = SelectRecommend_DLG_MEDIA[i].btn_5_context, Type = SelectRecommend_DLG_MEDIA[i].btn_5_type, Title = SelectRecommend_DLG_MEDIA[i].btn_5_title }; cardButtons.Add(plButton); } //message.Attachments.Add(GetHeroCard(SelectRecommend_DLG_MEDIA[i].card_title, "", SelectRecommend_DLG_MEDIA[i].card_text, cardImage, cardButtons)); returnAttachment = GetHeroCard(SelectRecommend_DLG_MEDIA[i].card_title, "", SelectRecommend_DLG_MEDIA[i].card_text, cardImage, cardButtons); } } else { string domainURL = "https://bottest.hyundai.com"; List <RecommendList> RecommendList = db.SelectedRecommendList(use, important, gender, age); RecommendList recommend = new RecommendList(); for (var i = 0; i < RecommendList.Count; i++) { string main_color_view = ""; string main_color_view_nm = ""; if (!string.IsNullOrEmpty(RecommendList[i].MAIN_COLOR_VIEW_1)) { main_color_view += domainURL + "/assets/images/price/360/" + RecommendList[i].MAIN_COLOR_VIEW_1 + "/00001.jpg" + "@"; main_color_view_nm += RecommendList[i].MAIN_COLOR_VIEW_NM1 + "@"; } ; if (!string.IsNullOrEmpty(RecommendList[i].MAIN_COLOR_VIEW_2)) { main_color_view += domainURL + "/assets/images/price/360/" + RecommendList[i].MAIN_COLOR_VIEW_2 + "/00001.jpg" + "@"; main_color_view_nm += RecommendList[i].MAIN_COLOR_VIEW_NM2 + "@"; } ; if (!string.IsNullOrEmpty(RecommendList[i].MAIN_COLOR_VIEW_3)) { main_color_view += domainURL + "/assets/images/price/360/" + RecommendList[i].MAIN_COLOR_VIEW_3 + "/00001.jpg" + "@"; main_color_view_nm += RecommendList[i].MAIN_COLOR_VIEW_NM3 + "@"; } ; if (!string.IsNullOrEmpty(RecommendList[i].MAIN_COLOR_VIEW_4)) { main_color_view += domainURL + "/assets/images/price/360/" + RecommendList[i].MAIN_COLOR_VIEW_4 + "/00001.jpg" + "@"; main_color_view_nm += RecommendList[i].MAIN_COLOR_VIEW_NM4 + "@"; } ; if (!string.IsNullOrEmpty(RecommendList[i].MAIN_COLOR_VIEW_5)) { main_color_view += domainURL + "/assets/images/price/360/" + RecommendList[i].MAIN_COLOR_VIEW_5 + "/00001.jpg" + "@"; main_color_view_nm += RecommendList[i].MAIN_COLOR_VIEW_NM5 + "@"; } ; if (!string.IsNullOrEmpty(RecommendList[i].MAIN_COLOR_VIEW_6)) { main_color_view += domainURL + "/assets/images/price/360/" + RecommendList[i].MAIN_COLOR_VIEW_6 + "/00001.jpg" + "@"; main_color_view_nm += RecommendList[i].MAIN_COLOR_VIEW_NM6 + "@"; } ; if (!string.IsNullOrEmpty(RecommendList[i].MAIN_COLOR_VIEW_7)) { main_color_view += domainURL + "/assets/images/price/360/" + RecommendList[i].MAIN_COLOR_VIEW_7 + "/00001.jpg"; main_color_view_nm += RecommendList[i].MAIN_COLOR_VIEW_NM7 + "@"; } ; main_color_view = main_color_view.TrimEnd('@'); main_color_view_nm = main_color_view_nm.TrimEnd('@'); var subtitle = RecommendList[i].TRIM_DETAIL + "|" + "가격: " + RecommendList[i].TRIM_DETAIL_PRICE + "|" + main_color_view + "|" + RecommendList[i].OPTION_1_IMG_URL + "|" + RecommendList[i].OPTION_1 + "|" + RecommendList[i].OPTION_2_IMG_URL + "|" + RecommendList[i].OPTION_2 + "|" + RecommendList[i].OPTION_3_IMG_URL + "|" + RecommendList[i].OPTION_3 + "|" + RecommendList[i].OPTION_4_IMG_URL + "|" + RecommendList[i].OPTION_4 + "|" + RecommendList[i].OPTION_5_IMG_URL + "|" + RecommendList[i].OPTION_5 + "|" + main_color_view_nm; if (SelectRecommend_DLG_MEDIA[0].btn_1_title.Length != 0) { CardAction plButton = new CardAction() { Value = SelectRecommend_DLG_MEDIA[0].btn_1_context, Type = SelectRecommend_DLG_MEDIA[0].btn_1_type, Title = SelectRecommend_DLG_MEDIA[0].btn_1_title }; cardButtons.Add(plButton); } if (SelectRecommend_DLG_MEDIA[0].btn_2_title.Length != 0) { CardAction plButton = new CardAction() { Value = SelectRecommend_DLG_MEDIA[0].btn_2_context, Type = SelectRecommend_DLG_MEDIA[0].btn_2_type, Title = SelectRecommend_DLG_MEDIA[0].btn_2_title }; cardButtons.Add(plButton); } returnAttachment = GetHeroCard("trim", subtitle, "", cardImage, cardButtons); } } return(returnAttachment); }
public void SetNoAction() { action = new NoAction(); }
public async Task ResumeAfterLocationDialogAsync(IDialogContext context, IAwaitable <Place> result) { var place = await result; var lat = place.Geo.Latitude; var lng = place.Geo.Longitude; string imgUrl = $"http://maps.google.com/maps/api/staticmap?center={lat},{lng}&zoom=16&size=400x400&sensor=false&format=png32&maptype=roadmap&markers={lat},{lng}"; IMessageActivity activity = context.MakeMessage(); activity.Attachments = new List <Attachment>(); ThumbnailCard plCard2 = new ThumbnailCard() { Title = "您目前所在位置", Images = new List <CardImage>() { new CardImage(url: imgUrl) }, }; activity.Attachments.Add(plCard2.ToAttachment()); await context.PostAsync(activity); await context.PostAsync("正在搜尋離您最近的ubike站點"); // send navi #region find near station var openJson = File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/YouBikeTP.json")); List <Models.UbikeStation> stations = JsonConvert.DeserializeObject <List <Models.UbikeStation> >(openJson); var coord = new GeoCoordinate(lat, lng); var nearest = stations.Select(x => new GeoCoordinate(double.Parse(x.lat), double.Parse(x.lng), int.Parse(x.sno))) .OrderBy(x => x.GetDistanceTo(coord)) .First(); var station = stations.First(x => x.sno == nearest.Altitude.ToString().PadLeft(4, '0')); #endregion var destImg = $"http://maps.google.com/maps/api/staticmap?zoom=16&size=600x400&sensor=false&path={lat},{lng}|{station.lat},{station.lng}&markers={lat},{lng}|{station.lat},{station.lng}"; // var destImg = "http://maps.google.com/maps/api/staticmap?center={lat},{lng}&zoom=16&size=400x400&sensor=false&format=png32&maptype=roadmap&markers={lat},{lng}"; IMessageActivity replyNavi = context.MakeMessage(); replyNavi.Type = "message"; replyNavi.Attachments = new List <Attachment>(); List <CardImage> cardImages = new List <CardImage>(); cardImages.Add(new CardImage(url: destImg)); List <CardAction> cardButtons = new List <CardAction>(); CardAction plButton = new CardAction() { Value = $"http://maps.google.com/maps?daddr={station.lat},{station.lng}&ll=", Type = "openUrl", Title = "前往" }; cardButtons.Add(plButton); ThumbnailCard plCard = new ThumbnailCard() { Title = $"最近站點為:{station.sna}", Subtitle = "是否要前往導航?", Images = cardImages, Buttons = cardButtons }; replyNavi.Attachments.Add(plCard.ToAttachment()); await context.PostAsync(replyNavi); context.Wait(MessageReceived); }
private async Task ResumePlaceDialog(IDialogContext context, IAwaitable <string> result) { try { string s = await result; if (s == "yes" || s == "Yes" || s == "y" || s == "想") { var resultMessage = context.MakeMessage(); resultMessage.AttachmentLayout = AttachmentLayoutTypes.List; resultMessage.Attachments = new List <Attachment>(); List <CardAction> cardButtons = new List <CardAction>(); List <CardImage> cardImages = new List <CardImage>(); cardImages.Add(new CardImage(url: "https://www.mariowiki.com/images/9/9c/Peachicon.png")); CardAction p1Button = new CardAction() { Title = "詢問時間", Value = "領袖營幾號", Type = ActionTypes.ImBack }; CardAction p2Button = new CardAction() { Title = "詢問地點", Value = "領袖營在哪", Type = ActionTypes.ImBack }; CardAction p3Button = new CardAction() { Title = "詢問活動流程", Value = "領袖營活動", Type = ActionTypes.ImBack }; cardButtons.Add(p1Button); cardButtons.Add(p2Button); cardButtons.Add(p3Button); ThumbnailCard plCard = new ThumbnailCard() { Title = $"點點這邊的選項吧!", Buttons = cardButtons, Images = cardImages }; Attachment plAttachment = plCard.ToAttachment(); resultMessage.Attachments.Add(plAttachment); await context.PostAsync(resultMessage); context.Wait(this.MessageReceived); } else { await context.PostAsync($"不想的話可以跟我聊聊天喔~"); var resultMessage = context.MakeMessage(); resultMessage.AttachmentLayout = AttachmentLayoutTypes.List; resultMessage.Attachments = new List <Attachment>(); List <CardAction> cardButtons = new List <CardAction>(); List <CardImage> cardImages = new List <CardImage>(); cardImages.Add(new CardImage(url: "https://www.mariowiki.com/images/9/9c/Peachicon.png")); CardAction p1Button = new CardAction() { Title = "講個笑話", Value = "講個笑話", Type = ActionTypes.ImBack }; CardAction p2Button = new CardAction() { Title = "誰最漂亮", Value = "誰最漂亮", Type = ActionTypes.ImBack }; CardAction p3Button = new CardAction() { Title = "誰最帥", Value = "誰最帥", Type = ActionTypes.ImBack }; cardButtons.Add(p1Button); cardButtons.Add(p2Button); cardButtons.Add(p3Button); ThumbnailCard plCard = new ThumbnailCard() { Title = $"點我點我!", Buttons = cardButtons, Images = cardImages }; Attachment plAttachment = plCard.ToAttachment(); resultMessage.Attachments.Add(plAttachment); await context.PostAsync(resultMessage); context.Wait(this.MessageReceived); } } catch (TooManyAttemptsException) { await context.PostAsync("I'm sorry, I'm having issues understanding you. Let's try again."); //await this.Askhi(context); } }
public async Task AskFilm(IDialogContext context, LuisResult result) { string replyMessage = ""; HttpClient client = new HttpClient(); string themoviedbUrl = "https://www.themoviedb.org/movie/"; string baseUri = "https://api.themoviedb.org/3"; string imageUrl = "https://image.tmdb.org/t/p/w600_and_h900_bestv2"; string apiKey = "?api_key=e01be34ceffec7c3b4fc1c591884c2fc"; EntityRecommendation rec; ResultModel.RootObject rootObject = new ResultModel.RootObject(); if (result.TryFindEntity("Film", out rec)) { string filmName = rec.Entity; replyMessage = $"Ok, let me think.."; await context.PostAsync(replyMessage); Console.WriteLine(filmName); string searchQuery = await client.GetStringAsync(new Uri( baseUri + "/search/movie" + apiKey + "&query=" + filmName )); rootObject = JsonConvert.DeserializeObject <ResultModel.RootObject>(searchQuery); if (rootObject.total_results > 0) { int searchFilmId = rootObject.results[0].id; string recommendationQuery = await client.GetStringAsync(new Uri( baseUri + $"/movie/{searchFilmId}/recommendations" + apiKey )); rootObject = JsonConvert.DeserializeObject <ResultModel.RootObject>(recommendationQuery); int cardsLength; if (rootObject.total_results > MAX_DECK_SIZE) { cardsLength = MAX_DECK_SIZE; } else if (rootObject.total_results > 0 && rootObject.total_results < MAX_DECK_SIZE) { cardsLength = rootObject.total_results; } else { cardsLength = 0; } var reply = context.MakeMessage(); reply.AttachmentLayout = "carousel"; reply.Attachments = new List <Attachment>(); for (int i = 0; i < cardsLength; i++) { List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); ResultModel.Result resultFilm = rootObject.results[i]; CardImage ci = new CardImage($"{imageUrl}{resultFilm.poster_path}"); cardImages.Add(ci); CardAction ca = new CardAction() { Title = resultFilm.title, Type = "openUrl", Value = $"{themoviedbUrl}{resultFilm.id}" }; CardAction button = new CardAction() { Title = $"Add to watch list", Type = "postBack", Value = "<ADD FILM>{" + $"id: {resultFilm.id}," + $"title: \"{resultFilm.title}\"" + "}" }; cardButtons.Add(button); ThumbnailCard tc = new ThumbnailCard() { Title = resultFilm.title, Subtitle = resultFilm.overview, Images = cardImages, Tap = ca, Buttons = cardButtons }; reply.Attachments.Add(tc.ToAttachment()); } // send the cards await context.PostAsync(reply); context.Wait(MessageReceived); } } else // No film entity detected { replyMessage = "Please name a film for me to work off"; } await context.PostAsync(replyMessage); context.Wait(MessageReceived); }
public LinkHeroCard(String a, String b, String c, IList <CardImage> d, IList <CardAction> e, CardAction f) : base(a, b, c, d, e, f) { }
/// <summary> /// Method called after the <seealso cref="NameDialog"/> when called from the /// <seealso cref="StartAsync"/> method. /// </summary> /// <param name="context">Mandatory. The context for the execution of a dialog's conversational process.</param> /// <param name="result">Mandatory. The user's preferred name specified from the <see cref="NameDialog"/>.</param> private async Task Resume_AfterNameDialog(IDialogContext context, IAwaitable <string> result) { var activity = await result; await _messageHelper.ConversationPauseAsync(context, Pause.MediumPause); await context.PostAsync($"{activity}! what a great name"); await _messageHelper.ConversationPauseAsync(context, Pause.ShortMediumPause); await context.PostAsync("Next we need to set my personality. My style, tone and attitute " + "are dictated by my personality settings. Pick what works best with you. You can always change this setting later!"); await _messageHelper.ConversationPauseAsync(context, Pause.VeryLongPause); IMessageActivity replyToConversation = context.MakeMessage(); replyToConversation.AttachmentLayout = AttachmentLayoutTypes.Carousel; replyToConversation.Attachments = new List <Attachment>(); PersonalityChoiceHeroCard friendlyHeroCard = new PersonalityChoiceHeroCard( PersonalityChatPersona.Friendly, "Friendly", "I'm always happy to help!", "https://buddybottablestorage.blob.core.windows.net/buddybotimages/avatars/BuddyBotFriendly.png"); PersonalityChoiceHeroCard professionalHeroCard = new PersonalityChoiceHeroCard( PersonalityChatPersona.Professional, "Professional", "I'm concise and helpful.", "https://buddybottablestorage.blob.core.windows.net/buddybotimages/avatars/BuddyBotProfessional.png"); PersonalityChoiceHeroCard humorousHeroCard = new PersonalityChoiceHeroCard( PersonalityChatPersona.Humorous, "Humorous", "Hurry up and get on with it.", "https://buddybottablestorage.blob.core.windows.net/buddybotimages/avatars/BuddyBotSassy.png"); List <PersonalityChoiceHeroCard> heroCardList = new List <PersonalityChoiceHeroCard> { friendlyHeroCard, professionalHeroCard, humorousHeroCard }; foreach (PersonalityChoiceHeroCard heroCard in heroCardList) { List <CardImage> cardImages = new List <CardImage>(); cardImages.Add(new CardImage(url: heroCard.ImageUrl)); List <CardAction> cardButtons = new List <CardAction>(); CardAction plButton = new CardAction() { Value = $"{heroCard.PersonalityType}", Type = "imBack", Title = "Select" }; cardButtons.Add(plButton); HeroCard plCard = new HeroCard() { Title = $"{heroCard.Title}", Subtitle = $"{heroCard.Subtitle}", Images = cardImages, Buttons = cardButtons }; Attachment plAttachment = plCard.ToAttachment(); replyToConversation.Attachments.Add(plAttachment); } await context.PostAsync(replyToConversation); context.Wait(Resume_AfterBotPersonaChoice); }
//Create HeroCard method that takes in the data needed to construct the card, title, subtitle, image, etc.. public static Attachment GetHeroCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction) { //Create a new herocard var heroCard = new HeroCard { //set the properties of the card Title = title, Subtitle = subtitle, Text = text, Images = new List <CardImage>() { cardImage }, Buttons = new List <CardAction>() { cardAction }, }; //return it as an attachment return(heroCard.ToAttachment()); }
public async Task Book(IDialogContext context, LuisResult result) { if (result.TryFindEntity("builtin.geography.city", out EntityRecommendation city)) { string location = city.Entity.ToLower(); string api_response = "none"; if (location == "new york") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.mocky.io/v2/58d7aa3d0f0000c103dcc5d5"); try { WebResponse response = request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); api_response = reader.ReadToEnd(); } } catch (WebException ex) { WebResponse errorResponse = ex.Response; using (Stream responseStream = errorResponse.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); String errorText = reader.ReadToEnd(); } throw; } JArray objt = JArray.Parse(api_response) as JArray; dynamic obj = objt; var message = context.MakeMessage(); message.Attachments = new List <Attachment>(); message.AttachmentLayout = AttachmentLayoutTypes.Carousel; foreach (dynamic room in obj) { var heroCard = new HeroCard(); heroCard.Title = room.type; heroCard.Subtitle = "$" + room.cost + " per night"; heroCard.Text = room.available + " rooms available"; List <CardImage> images = new List <CardImage>(); images.Add(new CardImage(url: room.image.ToString())); heroCard.Images = images; List <CardAction> actions = new List <CardAction>(); CardAction action = new CardAction() { Value = "select n" + room.type, Type = "imBack", Title = "Select" }; actions.Add(action); heroCard.Buttons = actions; message.Attachments.Add(heroCard.ToAttachment()); } await context.PostAsync(message); context.Wait(MessageReceived); } else if (location == "seattle") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.mocky.io/v2/58d7aa730f0000d503dcc5d6"); try { WebResponse response = request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); api_response = reader.ReadToEnd(); } } catch (WebException ex) { WebResponse errorResponse = ex.Response; using (Stream responseStream = errorResponse.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); String errorText = reader.ReadToEnd(); } throw; } JArray objt = JArray.Parse(api_response) as JArray; dynamic obj = objt; var message = context.MakeMessage(); message.Attachments = new List <Attachment>(); message.AttachmentLayout = AttachmentLayoutTypes.Carousel; foreach (dynamic room in obj) { var heroCard = new HeroCard(); heroCard.Title = room.type; heroCard.Subtitle = "$" + room.cost + " per night"; heroCard.Text = room.available + " rooms available"; List <CardImage> images = new List <CardImage>(); images.Add(new CardImage(url: room.image.ToString())); heroCard.Images = images; List <CardAction> actions = new List <CardAction>(); CardAction action = new CardAction() { Value = "select s" + room.type, Type = "imBack", Title = "Select" }; actions.Add(action); heroCard.Buttons = actions; message.Attachments.Add(heroCard.ToAttachment()); } await context.PostAsync(message); context.Wait(MessageReceived); } else if (location == "miami") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.mocky.io/v2/58d7aadd0f0000dc03dcc5d9"); try { WebResponse response = request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); api_response = reader.ReadToEnd(); } } catch (WebException ex) { WebResponse errorResponse = ex.Response; using (Stream responseStream = errorResponse.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); String errorText = reader.ReadToEnd(); } throw; } JArray objt = JArray.Parse(api_response) as JArray; dynamic obj = objt; var message = context.MakeMessage(); message.Attachments = new List <Attachment>(); message.AttachmentLayout = AttachmentLayoutTypes.Carousel; foreach (dynamic room in obj) { var heroCard = new HeroCard(); heroCard.Title = room.type; heroCard.Subtitle = "$" + room.cost + " per night"; heroCard.Text = room.available + " rooms available"; List <CardImage> images = new List <CardImage>(); images.Add(new CardImage(url: room.image.ToString())); heroCard.Images = images; List <CardAction> actions = new List <CardAction>(); CardAction action = new CardAction() { Value = "select m" + room.type, Type = "imBack", Title = "Select" }; actions.Add(action); heroCard.Buttons = actions; message.Attachments.Add(heroCard.ToAttachment()); } await context.PostAsync(message); context.Wait(MessageReceived); } else { await context.PostAsync("Sorry, we don't have a hotel in " + location); context.Wait(MessageReceived); } } else { string message = "No city mentioned, Please mention city in request"; await context.PostAsync(message); context.Wait(MessageReceived); } }
public static Attachment GetAdaptiveCard(string title, string subtitle, string text, CardImage cardImage, CardAction cardAction) { var adaptiveCard = new AdaptiveCard { BackgroundImage = "https://thumbs.dreamstime.com/z/perspective-wood-over-blurred-restaurant-bokeh-background-foods-drinks-product-display-montage-55441300.jpg", Body = new List <CardElement> { new ColumnSet() { Columns = new List <Column>() { new AdaptiveCards.Column() { Size = "3", Items = new List <AdaptiveCards.CardElement>() { new TextBlock() { Text = title, Size = TextSize.Large, Weight = TextWeight.Bolder }, new TextBlock() { Text = subtitle }, new FactSet() { Facts = new List <AdaptiveCards.Fact>() { new AdaptiveCards.Fact() { Title = "Fact 1", Value = "Value 1" }, new AdaptiveCards.Fact() { Title = "Fact 2", Value = "Value 2" } } }, new ChoiceSet() { Id = "Times", Style = ChoiceInputStyle.Compact, Choices = new List <Choice>() { new Choice() { Title = "6 PM", Value = "6", IsSelected = true }, new Choice() { Title = "7 PM", Value = "7" }, new Choice() { Title = "8 PM", Value = "8" } } } } }, new AdaptiveCards.Column() { Items = new List <AdaptiveCards.CardElement>() { new Image() { Url = cardImage.Url, Size = ImageSize.Stretch } } } } } } }; /*//////////////////////////////////////////////////////////////// * Alternate way to create your cards, columns, textblocks, etc.. * ///////////////////////////////////////////////////////////////*/ // ColumnSet set = new ColumnSet(); // Column c1 = new Column() // { // }; // Column c2 = new Column(); // set.Columns.Add(c1); // set.Columns.Add(c2); // c1.Items.Add(new TextBlock() // { // Text = title, // Size = TextSize.Large, // Weight = TextWeight.Bolder // }); // c1.Items.Add(new TextBlock() // { // Text = subtitle // }); // c1.Items.Add(new FactSet() // { // Facts = new List<AdaptiveCards.Fact>() // { // new AdaptiveCards.Fact() {Title = "Fact 1", Value = "Value 1" }, // new AdaptiveCards.Fact() {Title = "Fact 2", Value = "Value 2" } // } // }); // // Add list of choices to the card. //c1.Items.Add(new ChoiceSet() // { // Id = "snooze", // Style = ChoiceInputStyle.Compact, // Choices = new List<Choice>() // { // new Choice() { Title = "5 minutes", Value = "5", IsSelected = true }, // new Choice() { Title = "15 minutes", Value = "15" }, // new Choice() { Title = "30 minutes", Value = "30" } // } // }); // c2.Items.Add(new Image() // { // Url = cardImage.Url, // Size = ImageSize.Stretch // }); // card.Body.Add(set); // Add text to the card. //card.Body.Add(new TextBlock() //{ // Text = title, // Size = TextSize.Large, // Weight = TextWeight.Bolder //}); // Add text to the card. //card.Body.Add(new TextBlock() //{ // Text = subtitle //}); //card.Body.Add(new Image() //{ // Url = cardImage.Url, // Size = ImageSize.Medium //}); // Create the attachment. Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = adaptiveCard }; return(attachment); }
/// <summary> /// Get list card attachment having list of favorite rooms along with buttons to manage favorites, book meeting for other rooms and refresh list. /// </summary> /// <param name="rooms">Rooms schedule response object.</param> /// <param name="startUTCDateTime">Start date time of meeting.</param> /// <param name="endUTCDateTime">End date time of meeting.</param> /// <param name="timeZone">User time zone.</param> /// <param name="activityReferenceId">Unique GUID related to activity Id from ActivityEntities table.</param> /// <returns>List card attachment having favorite rooms of user.</returns> public static Attachment GetFavoriteRoomsListAttachment(RoomScheduleResponse rooms, DateTime startUTCDateTime, DateTime endUTCDateTime, string timeZone, string activityReferenceId = null) { ListCard card = new ListCard { Title = Strings.RoomAvailability, Items = new List <ListItem>(), Buttons = new List <CardAction>(), }; // For first run, user configuration will be null. if (timeZone != null) { var startTime = TimeZoneInfo.ConvertTimeFromUtc(startUTCDateTime, TimeZoneInfo.FindSystemTimeZoneById(timeZone)); var endTime = TimeZoneInfo.ConvertTimeFromUtc(endUTCDateTime, TimeZoneInfo.FindSystemTimeZoneById(timeZone)); card.Title = string.Format(CultureInfo.CurrentCulture, "{0} | {1} - {2}", Strings.RoomAvailability, startTime.ToString("t", CultureInfo.CurrentCulture), endTime.ToString("t", CultureInfo.CurrentCulture)); } ListItem room = new ListItem(); Meeting meeting; if (rooms?.Schedules.Count > 0) { foreach (var item in rooms.Schedules) { string availability; string availabilityColor; // Schedule will be null in case room is deleted from exchange but sync service still gets room from Graph API as Graph takes time to reflect deleted item. if (item.ScheduleItems != null && item.ScheduleItems.Count == 0) { availability = Strings.Available; availabilityColor = GreenColorCode; } else { availability = Strings.Unavailable; availabilityColor = RedColorCode; } var subtitle = string.Format(CultureInfo.CurrentCulture, "{0} | <b><font color='{1}'>{2}</font></b>", item.BuildingName, availabilityColor, availability); meeting = new Meeting { EndDateTime = DateTime.SpecifyKind(endUTCDateTime, DateTimeKind.Utc).ToString("o"), RoomEmail = item.ScheduleId, RoomName = item.RoomName, StartDateTime = DateTime.SpecifyKind(startUTCDateTime, DateTimeKind.Utc).ToString("o"), BuildingName = item.BuildingName, Status = availability, Text = BotCommands.CreateMeeting, }; card.Items.Add(new ListItem { Id = item.ScheduleId, Title = item.RoomName, Subtitle = subtitle, Type = "person", Tap = new CardAction { Type = ActionTypes.MessageBack, Text = BotCommands.CreateMeeting, Title = BotCommands.CreateMeeting, Value = JsonConvert.SerializeObject(meeting) }, }); } } else { room = new ListItem { Title = Strings.NoFavoriteRooms, Type = "section", }; } card.Items.Add(room); CardAction addFavoriteButton = new TaskModuleAction(Strings.ManageFavorites, new { data = JsonConvert.SerializeObject(new AdaptiveTaskModuleCardAction { Text = BotCommands.ShowFavoriteTaskModule, ActivityReferenceId = activityReferenceId }) }); card.Buttons.Add(addFavoriteButton); CardAction otherRoomButton = new TaskModuleAction(Strings.OtherRooms, new { data = JsonConvert.SerializeObject(new AdaptiveTaskModuleCardAction { Text = BotCommands.ShowOtherRoomsTaskModule, ActivityReferenceId = activityReferenceId }) }); card.Buttons.Add(otherRoomButton); if (rooms?.Schedules.Count > 0) { CardAction refreshListButton = new CardAction { Title = Strings.Refresh, Type = ActionTypes.MessageBack, Text = BotCommands.RefreshList, Value = JsonConvert.SerializeObject(new AdaptiveTaskModuleCardAction { Text = BotCommands.RefreshList, ActivityReferenceId = activityReferenceId }), }; card.Buttons.Add(refreshListButton); } var attachment = new Attachment() { ContentType = "application/vnd.microsoft.teams.card.list", Content = card, }; return(attachment); }
public Attachment getAttachmentFromDialog(DialogList dlg, Activity activity) { Attachment returnAttachment = new Attachment(); ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); if (dlg.dlgType.Equals(MessagesController.TEXTDLG)) { if (!activity.ChannelId.Equals("facebook")) { HeroCard plCard = new HeroCard() { Title = dlg.cardTitle, Text = dlg.cardText }; returnAttachment = plCard.ToAttachment(); } } else if (dlg.dlgType.Equals(MessagesController.MEDIADLG)) { string cardDiv = ""; string cardVal = ""; List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); HistoryLog("CARD IMG START"); if (dlg.mediaUrl != null) { HistoryLog("FB CARD IMG " + dlg.mediaUrl); cardImages.Add(new CardImage(url: dlg.mediaUrl)); } HistoryLog("CARD BTN1 START"); if (activity.ChannelId.Equals("facebook") && dlg.btn1Type == null && !string.IsNullOrEmpty(dlg.cardDivision) && dlg.cardDivision.Equals("play") && !string.IsNullOrEmpty(dlg.cardValue)) { CardAction plButton = new CardAction(); plButton = new CardAction() { Value = dlg.cardValue, Type = "openUrl", Title = "영상보기" }; cardButtons.Add(plButton); } else if (dlg.btn1Type != null) { CardAction plButton = new CardAction(); plButton = new CardAction() { Value = dlg.btn1Context, Type = dlg.btn1Type, Title = dlg.btn1Title }; cardButtons.Add(plButton); } if (dlg.btn2Type != null) { if (!(activity.ChannelId == "facebook" && dlg.btn2Title == "나에게 맞는 모델 추천")) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN2 START"); plButton = new CardAction() { Value = dlg.btn2Context, Type = dlg.btn2Type, Title = dlg.btn2Title }; cardButtons.Add(plButton); } } if (dlg.btn3Type != null) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN3 START"); plButton = new CardAction() { Value = dlg.btn3Context, Type = dlg.btn3Type, Title = dlg.btn3Title }; cardButtons.Add(plButton); } if (dlg.btn4Type != null) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN4 START"); plButton = new CardAction() { Value = dlg.btn4Context, Type = dlg.btn4Type, Title = dlg.btn4Title }; cardButtons.Add(plButton); } if (!string.IsNullOrEmpty(dlg.cardDivision)) { cardDiv = dlg.cardDivision; } if (!string.IsNullOrEmpty(dlg.cardValue)) { //cardVal = priceMediaDlgList[i].cardValue.Replace(); cardVal = dlg.cardValue; } HistoryLog("!!!!!FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1"); HeroCard plCard = new UserHeroCard(); if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(dlg.cardTitle)) { HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)"); plCard = new UserHeroCard() { Title = "선택해 주세요", Text = dlg.cardText, Images = cardImages, Buttons = cardButtons, Card_division = cardDiv, Card_value = cardVal }; returnAttachment = plCard.ToAttachment(); } else if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(dlg.cardValue)) { HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)"); plCard = new UserHeroCard() { Title = dlg.cardTitle, Images = cardImages, Buttons = cardButtons }; returnAttachment = plCard.ToAttachment(); } else { HistoryLog("!!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)"); plCard = new UserHeroCard() { Title = dlg.cardTitle, Text = dlg.cardText, Images = cardImages, Buttons = cardButtons, Card_division = cardDiv, Card_value = cardVal }; returnAttachment = plCard.ToAttachment(); } } else { Debug.WriteLine("Dialog Type Error : " + dlg.dlgType); } return(returnAttachment); }
/// <summary> /// Adds an action to this card during build time. /// </summary> /// <param name="label">Label.</param> /// <param name="id">Identifier.</param> /// <param name="type">Type.</param> private void AddAction(string label, int id, int type) { CardAction cardAction = new CardAction (); cardAction.Label = label; cardAction.Id = id; cardAction.Type = type; mCardActions.Add (cardAction); }