I made a bot in C# using BotFramework, Adaptive Cards, LUIS and FormFlow. It/he is responsible for managing meetings in a team.
return new FormBuilder<MeetingRequestInput>()
...
.Field(
nameof(MeetingRequestInput.RequestedDate),
"What date would you like to meet?"
)
...
.Build();
During tests we noticed problems when a user was supposed to type the desired meeting date/time (people would type dd/mm/yy, mm/dd/yy, dd-mm-yy, only dd, etcetra) so we would like to use some kind of "Form" with formatted inputs to avoid parsing problems and retaining usability.
I think we can't change the desired keyboard type (kinda like in mobile, where sometimes the keyboard only shows numbers, or shows a DateTime Picker), nor apply a pattern auto-complete, at least using BotFramework.
To solve this, I'd like to use an AdaptiveCard with Date and Time pickers in my FormFlow prompt, at least when the user is asked to type the requested date, like so:
Input example using Adaptive Cards
In this example, the user would fill the AdaptiveDateInput and the AdaptiveTimeInput, then press the Confirm button. Doing so, it would grab the values inside the inputs, then "type and send" for the user the desired DateTime in a specific template, avoiding the previous parsing problems.
Problem is, I can't replace the "normal" FormFlow Card (who's expecting a simple string as a prompt parameter) with an entire Adaptive Card. How do I solve this problem? Are AdaptiveCards the best answer or are there alternatives?
Right now I'm displaying the card manually like so:
AdaptiveCard card = new AdaptiveCard();
card.Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = "What date would you like to meet?"
},
new AdaptiveDateInput()
{
Value = DateTime.Now.ToShortDateString(),
Id = "dateInp"
},
new AdaptiveTimeInput()
{
Value = DateTime.Now.ToShortTimeString(),
Id = "timeInp"
}
};
card.Actions = new List<AdaptiveAction>()
{
new AdaptiveSubmitAction()
{
Type = "Action.Submit",
Title = "Confirm"
}
};
var msg = context.MakeMessage();
msg.Attachments.Add(
new Attachment()
{
Content = card,
ContentType = "application/vnd.microsoft.card.adaptive",
Name = "Requested Date Adaptive Card"
}
);
await context.PostAsync(msg);
I've read this question, but I don't know if we have the exact same problem. And their solution does not apply to me: even though I made the examples above in english, the bot will actually expect inputs in other languages, so yeah we can parse "February 2th" using a Recognizer, but we don't have the same luck with "2 de Fevereiro" nor "2 Fevralya".
Using the FormBuilder.Prompter, you can customize FormFlow messages any way you like. However, since AdaptiveCards send responses in the .Value, the code will need to transfer .Value to .Text property before validation.
Here is an example of a FormFlow form that sends an AdaptiveCard for a RequestedDate field:
[Serializable]
public class AdaptiveCardsFormFlow
{
public string Name { get; set; }
public DateTime? RequestedDate { get; set; }
public static IForm<AdaptiveCardsFormFlow> BuildForm()
{
IFormBuilder<AdaptiveCardsFormFlow> formBuilder = GetFormbuilder();
var built = formBuilder
.Field(nameof(Name), "What is your name?")
.Field(nameof(RequestedDate))
.Confirm("Is this information correct? {*}")
.Build();
return built;
}
private static AdaptiveCard GetDateCard()
{
AdaptiveCard card = new AdaptiveCard();
card.Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = "What date would you like to meet?"
},
new AdaptiveDateInput()
{
Value = DateTime.Now.ToShortDateString(),
Id = "dateInp"
},
new AdaptiveTimeInput()
{
Value = DateTime.Now.ToShortTimeString(),
Id = "timeInp"
}
};
card.Actions = new List<AdaptiveAction>()
{
new AdaptiveSubmitAction()
{
Type = "Action.Submit",
Title = "Confirm"
}
};
return card;
}
private static IFormBuilder<AdaptiveCardsFormFlow> GetFormbuilder()
{
IFormBuilder<AdaptiveCardsFormFlow> formBuilder = new FormBuilder<AdaptiveCardsFormFlow>()
.Prompter(async (context, prompt, state, field) =>
{
var preamble = context.MakeMessage();
var promptMessage = context.MakeMessage();
if (prompt.GenerateMessages(preamble, promptMessage))
{
await context.PostAsync(preamble);
}
if (field != null && field.Name == nameof(AdaptiveCardsFormFlow.RequestedDate))
{
var attachment = new Attachment()
{
Content = GetDateCard(),
ContentType = AdaptiveCard.ContentType,
Name = "Requested Date Adaptive Card"
};
promptMessage.Attachments.Add(attachment);
}
await context.PostAsync(promptMessage);
return prompt;
}).Message("Please enter your information to schedule a callback.");
return formBuilder;
}
}
Using this class:
private class DateTimeInp
{
public string dateInp { get; set; }
public string timeInp { get; set; }
public DateTime? ToDateTime()
{
string fullDateTime = dateInp + " " + timeInp;
DateTime toDateTime;
if(DateTime.TryParse(fullDateTime, out toDateTime))
{
return toDateTime;
}
return null;
}
}
Then, in the Messages Controller, add the Adaptive Card's return value to the .Text property of the activity:
if(activity.Value != null)
{
DateTimeInp input = JsonConvert.DeserializeObject<DateTimeInp>(activity.Value.ToString());
var toDateTime = input.ToDateTime();
if(toDateTime != null)
{
activity.Text = toDateTime.ToString();
}
}
Related
I encountered a “date” issue with Bot in TEAMS, The date value cannot render at LeaveRequest() properly. However, the same bot works fine in Bot Emulator.
Following is my sample code. How to fix (or workaround) this issue?
Select a date from date picker and submit
System does not render the first field value.
public class EchoBot
{
public static Attachment LeaveRequest()
{
AdaptiveSchemaVersion schemaVersion = new AdaptiveSchemaVersion(1, 0);
AdaptiveCard card = new AdaptiveCard(schemaVersion);
card.Body.Add(new AdaptiveTextBlock()
{
Text = "Enter new Date",
Size = AdaptiveTextSize.Large,
Weight = AdaptiveTextWeight.Bolder
});
AdaptiveDateInput fromDate = new AdaptiveDateInput()
{
Id = "FromDate",
Placeholder = "From Date"
};
card.Body.Add(fromDate);
AdaptiveTextInput toDate = new AdaptiveTextInput()
{
Id = "ToDate",
Placeholder = "To Date",
Value = DateTime.Today.ToUniversalTime().ToString("u")
};
card.Body.Add(toDate);
card.Actions.Add(new AdaptiveSubmitAction()
{
Title = "Submit"
});
Attachment cardAttachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
return cardAttachment;
}
}
public class RootDialog : IDialog<object>
{
public async Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}
public virtual async Task MessageReceivedAsync(IDialogContext context,
IAwaitable<IMessageActivity> result)
{
var activity = await result as Activity;
Boolean first = true;
if (activity.Value != null)
{
var jObjectValue = activity.Value as JObject;
var fromDateString = jObjectValue.Value<string>("FromDate");
var toDateString = jObjectValue.Value<string>("ToDate");
await context.PostAsync($"from Date Entered: {fromDateString}");
await context.PostAsync($"to Date Entered: {toDateString}");
first = false;
}
if (first)
{
var reply = activity.CreateReply();
var card = EchoBot.LeaveRequest();
var msg = context.MakeMessage();
msg.Attachments.Add(card);
await context.PostAsync(msg);
}
}
}
Thanks for reaching out!! This is a known issue. We have a bug on this and we are working on getting this fixed.
I'm developing a Teams Message Extension and I'm using ThumbnailCard to display my results, however I wanted to use a custom adaptive card. Is that possible?
var resultCardList = GetAttachments(title);
var response = new ComposeExtensionResponse(new ComposeExtensionResult("list", "result"));
response.ComposeExtension.Attachments = resultCardList.ToList();
return response;
foreach (var contract in contractItems)
{
var lastModified = (DateTime)contract["Modified"];
var justificativa = contract["JustificativaContrato"];
var card = new ThumbnailCard
{
Title = $"{contract.Client_Title} - {lastModified.ToShortDateString()} {lastModified.ToLongTimeString()}",
Text = $"Justificativa: {justificativa}",
Tap = new CardAction { Type = "openUrl", Value = $"{Tenant}{ContractList.DefaultEditFormUrl}?ID={contract.Id}" },
Images = new List<CardImage> { new CardImage("http://lorempixel.com/640/480?rand=" + DateTime.Now.Ticks.ToString()) }
};
cardList.Add(card
.ToAttachment()
.ToComposeExtensionAttachment());
}
return cardList;
I've tried to use the below method to generate the Adaptive Card and just add it to the list:
private static Microsoft.Bot.Connector.Attachment CreateAdaptiveCardAttachment()
{
// combine path for cross platform support
string[] paths = { ".", "Cards", "welcomeCard.json" };
string fullPath = Path.Combine(paths);
var adaptiveCard = System.IO.File.ReadAllText(#"Cards\welcomeCard.json");
return new Microsoft.Bot.Connector.Attachment()
{
ContentType = "application/vnd.microsoft.card.adaptive",
Content = JsonConvert.DeserializeObject(adaptiveCard),
};
}
The messaging extension does not allow sending adaptive cards like that.
It requires using the "MessagingExtensionResult" of the framework and just the card sent in the response. The documentation is a bit lacking here.
When you get a call from the messaging extension its action is of type "composeExtension/query"
Create the general "result" list like this:
var invokeResponse = new MessagingExtensionResponse();
var results = new MessagingExtensionResult
{
AttachmentLayout = "list",
Type = "result",
Attachments = new List<MessagingExtensionAttachment>(),
};
For each result in the list you need to create a MessagingExtensionAttachment like this: (Note: Cards need to have a preview!)
results.Attachments.Add(new MessagingExtensionAttachment
{
ContentType = "application/vnd.microsoft.teams.card.adaptive",
Content = JsonConvert.DeserializeObject(cardData),
Preview = new Attachment
{
ContentType = "application/vnd.microsoft.card.thumbnail",
Content = new AttachmentContent
{
text = "Project: " + task.ProjectName,
title = task.Name,
},
}
});
Finally send the result as "InvokeResponse"
return new InvokeResponse
{
Body = invokeResponse,
Status = 200,
};
While "content" of the attachment is the full adaptive card.
You can find an example for the response in json here:
https://learn.microsoft.com/de-de/microsoftteams/platform/concepts/messaging-extensions/search-extensions#response-example
You can freely mix card types based on that, but i never got that working tho...as of now you need to limit to one specific card type as far as i know.
All above is if you're using
Microsoft.Bot.Builder.Teams
Microsoft.Bot.Connector.Teams
Microsoft.Bot.Schema.Teams
in the latest versions.
I'm trying to use Bloomberg API to get holiday information about a ticker, the request below produces the dates correctly but I would also like to include the name of the holiday
Could there be an override that will also include the name of the date as on "New Year"
ReferenceDataRequest = {
securities[] = {
LQ45 Index
}
fields[] = {
CALENDAR_HOLIDAYS
}
overrides[] = {
overrides = {
fieldId = "SETTLEMENT_CALENDAR_CODE"
value = "JA"
}
overrides = {
fieldId = "CALENDAR_START_DATE"
value = "20190101"
}
overrides = {
fieldId = "CALENDAR_END_DATE"
value = "20191231"
}
}
tableOverrides[] = {
}
}
the c# code I am using was suggested on another question that I can no longer find, and it is:
Request request = this._service.CreateRequest("ReferenceDataRequest");
Element securities = request.GetElement(BloombergConstants.SECURITIES);
securities.AppendValue(ticker);
Element fields = request.GetElement(BloombergConstants.FIELDS);
fields.AppendValue("CALENDAR_HOLIDAYS");
//Element overridefields = request.GetElement(BloombergConstants.OVERRIDES);
Element overrides = request.GetElement(BloombergConstants.OVERRIDES);
Element override1 = overrides.AppendElement();
override1.SetElement(BloombergConstants.FIELDID, "SETTLEMENT_CALENDAR_CODE");
override1.SetElement(BloombergConstants.VALUE, calendarCode);
override1 = overrides.AppendElement();
override1.SetElement(BloombergConstants.FIELDID , "CALENDAR_START_DATE");
override1.SetElement(BloombergConstants.VALUE, startDate.ToString("yyyyMMdd"));
Element override2 = overrides.AppendElement();
override2.SetElement(BloombergConstants.FIELDID, "CALENDAR_END_DATE");
override2.SetElement(BloombergConstants.VALUE, endDate.ToString("yyyyMMdd"));
Sadly not.
see Official Bloomberg API-Core-Developer-Guide.pdf
see Unofficial Bloomberg .Net API Implementation
Unfortunately it looks like there is no override code to add this behaviour. This is a bit non intuitive, but if you search for the relevant code CALENDAR_HOLIDAYS you actually receive information on the code CALENDAR_NON_SETTLEMENT_DATES (possibly this was renamed and aliased to this at some point?)
fieldInfoRequest = {
id[] = {
"CALENDAR_HOLIDAYS"
}
}
fieldResponse = {
fieldData[] = {
fieldData = {
id = "ZS090"
fieldInfo = {
mnemonic = "CALENDAR_NON_SETTLEMENT_DATES"
description = "Calendar Non-Settlement Dates"
datatype = String
categoryName[] = {
}
property[] = {
}
overrides[] = {
"ZS089", "ZS087", "ZS088"
}
ftype = BulkFormat
}
}
}
}
These overrides correspond to
id mnemonic
ZS087 SETTLEMENT_CALENDAR_CODE
ZS088 CALENDAR_START_DATE
ZS089 CALENDAR_END_DATE
Non of which adds functionality to return a description of the holiday the date corresponds to.
Within a bot,we have an adaptive card where the user has a choice to select yes or no.
On selecting YES, user is prompted to enter the keywords.
After the user gives input in the textblock in adaptive card, the input has to be captured and sent as input parameter to web api.
The user input will be given in Placeholder of the AdaptiveTextInput block.
public static Attachment GetUserInputForCustomPPT()
{
AdaptiveCard card = new AdaptiveCard()
{
Id = "GetCustomPPT",
Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = "Do you want to apply filter and customise the PPT?",
Wrap=true,
Size = AdaptiveTextSize.Small
},
new AdaptiveContainer()
{
Id = "getCustomPPTNo",
SelectAction = new AdaptiveSubmitAction()
{
Id = "getCustomPPTNo",
Title = "No",
DataJson = "{ \"Type\": \"GetCustomPPT\" }",
}
},
new AdaptiveContainer()
{
Id = "getCustomPPTYes",
Items = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = "Please select an option",
Wrap=true,
Size = AdaptiveTextSize.Small
}
}
},
},
Actions = new List<AdaptiveAction>()
{
new AdaptiveShowCardAction()
{
Id = "GetPPTYes",
Title = "Yes",
Card = new AdaptiveCard()
{
Body = new List<AdaptiveElement>()
{
new AdaptiveTextBlock()
{
Text = "Please enter your input",
Wrap = true
},
new AdaptiveTextInput()
{
Id="GetUserInputKeywords",
Placeholder="Please enter the keyword list separated by ',' Ex:RPA,FS ",
MaxLength=490,
IsMultiline=true
}
},
Actions = new List<AdaptiveAction>()
{
new AdaptiveSubmitAction()
{
Id = "contactSubmit",
Title = "Submit",
DataJson = "{ \"Type\": \"GetPPT\" }"
},
new AdaptiveOpenUrlAction()
{
Id="CallApi",
Url=new Uri("https://xyz"+"RPA")
//card.Actions.Card.AdaptiveTextInput.Placeholder
}
}
}
},
new AdaptiveShowCardAction()
{
Id = "GetPPTNo",
Title = "No",
Card = new AdaptiveCard()
{
Body = new List<AdaptiveElement>()
{
},
Actions = new List<AdaptiveAction>()
{
new AdaptiveSubmitAction()
{
Id = "contactSubmit",
Title = "Submit",
DataJson = "{ \"Type\": \"GetPPTNo\" }"
}
}
}
}
}
};
// Create the attachment with adapative card.
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
return attachment;
}
Yes, you can retrieve the input values from an AdaptiveCard and use them as parameters in an HTTP request to an API. When the user submits an AdaptiveCard, the input fields are sent to the bot through the activity in the Value attribute. You can parse the resulting JSON string with JObject and retrieve the values for your API call. See the example below.
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext.Activity.Type == ActivityTypes.Message)
{
// Check if user submitted AdaptiveCard input
if (turnContext.Activity.Value != null) {
// Convert String to JObject
String value = turnContext.Activity.Value.ToString();
JObject results = JObject.Parse(value);
// Get type from input field
String name = results.GetValue("Type").ToString();
// Get Keywords from input field
String userInputKeywords = "";
if (name == "GetPPT") {
userInputKeywords = results.GetValue("GetUserInputKeywords").ToString();
}
// Make Http request to api with paramaters
String myUrl = $"http://myurl.com/api/{userInputKeywords}";
...
// Respond to user
await turnContext.SendActivityAsync("Respond to user", cancellationToken: cancellationToken);
} else {
// Send user AdaptiveCard
var cardAttachment = GetUserInputForCustomPPT();
var reply = turnContext.Activity.CreateReply();
reply.Attachments = new List<Attachment>() { cardAttachment };
await turnContext.SendActivityAsync(reply, cancellationToken);
}
}
}
Hope this helps!
Using routing you can pass multiple parameters either on the route itself or pass parameters on the query string, via Model Binding or content value binding. For most common scenarios this actually works very well. As long as you are passing either a single complex type via a POST operation, or multiple simple types via query string or POST buffer, there's no issue. But if you need to pass multiple parameters as was easily done with WCF REST or ASP.NET AJAX things are not so obvious.
RouteTable.Routes.MapHttpRoute(
name: "ApiName",
routeTemplate: "photos/**{action}**/{title}",
defaults: new {
title = RouteParameter.Optional,
controller = "PhotoApi",
**action =** **"GetPhotos"** });
I'm using an Adaptive Card with a multiselect, in the context of Bot created with BotBuilder (Bot Framework):
var card = new AdaptiveCard();
card.Body.Add(new AdaptiveTextBlock()
{
Text = "Q1:xxxxxxxx?",
Size = AdaptiveTextSize.Default,
Weight = AdaptiveTextWeight.Bolder
});
card.Body.Add(new AdaptiveChoiceSetInput()
{
Id = "choiceset1",
Choices = new List<AdaptiveChoice>()
{
new AdaptiveChoice(){
Title="answer1",
Value="answer1"
},
new AdaptiveChoice(){
Title="answer2",
Value="answer2"
},
new AdaptiveChoice(){
Title="answer3",
Value="answer3"
}
},
Style = AdaptiveChoiceInputStyle.Expanded,
IsMultiSelect = true
});
var message = context.MakeMessage();
message.Attachments.Add(new Attachment() { Content = card, ContentType = "application/vnd.microsoft.card.adaptive"});
await context.PostAsync(message);
Now, I would like to know which elements the user has selected.
I would like to know which elements the user has selected.
You can get user's selections from message Value property, the following code snippets work for me, please refer to it.
if (message.Value != null)
{
var user_selections = Newtonsoft.Json.JsonConvert.DeserializeObject<userselections>(message.Value.ToString());
await context.PostAsync($"You selected {user_selections.choiceset1}!");
context.Wait(MessageReceivedAsync);
}
The definition of userselections class:
public class userselections
{
public string choiceset1 { get; set; }
}
Test result:
Update: Code snippet of adding AdaptiveChoiceSetInput and AdaptiveSubmitAction
card.Body.Add(new AdaptiveChoiceSetInput()
{
Id = "choiceset1",
Choices = new List<AdaptiveChoice>()
{
new AdaptiveChoice(){
Title="answer1",
Value="answer1"
},
new AdaptiveChoice(){
Title="answer2",
Value="answer2"
},
new AdaptiveChoice(){
Title="answer3",
Value="answer3"
}
},
Style = AdaptiveChoiceInputStyle.Expanded,
IsMultiSelect = true
});
card.Actions.Add(new AdaptiveSubmitAction()
{
Title = "submit"
});