I have some code for the bot to send a message (string) on start up.
However, instead of sending text like you see in the code below. I am trying to figure out how you would send an Adaptive Card in this case. I have sent a Card from the RootDialog before, but not from the MessageController.cs. Any direction would be great here!
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
IConversationUpdateActivity iConversationUpdated = message as IConversationUpdateActivity;
if (iConversationUpdated != null)
{
ConnectorClient connector = new ConnectorClient(new System.Uri(message.ServiceUrl));
foreach (var member in iConversationUpdated.MembersAdded ?? System.Array.Empty<ChannelAccount>())
{
// if the bot is added, then
if (member.Id == iConversationUpdated.Recipient.Id)
{
var reply = ((Activity)iConversationUpdated).CreateReply($"WELCOME MESSAGE HERE");
await connector.Conversations.ReplyToActivityAsync(reply);
}
}
}
}
Thanks
Using the code snippet you provided you should be able to copy and paste this to replace it. More information about cards in bot framework can be found in this blog
else if (message.Type == ActivityTypes.ConversationUpdate)
{
IConversationUpdateActivity iConversationUpdated = message as IConversationUpdateActivity;
if (iConversationUpdated != null)
{
ConnectorClient connector = new ConnectorClient(new System.Uri(message.ServiceUrl));
foreach (var member in iConversationUpdated.MembersAdded ?? System.Array.Empty<ChannelAccount>())
{
// if the bot is added, then
if (member.Id == iConversationUpdated.Recipient.Id)
{
Activity replyToConversation = message.CreateReply("Should go to conversation");
replyToConversation.Attachments = new List<Attachment>();
AdaptiveCard card = new AdaptiveCard();
// Specify speech for the card.
card.Speak = "<s>Your meeting about \"Adaptive Card design session\"<break strength='weak'/> is starting at 12:30pm</s><s>Do you want to snooze <break strength='weak'/> or do you want to send a late notification to the attendees?</s>";
// Add text to the card.
card.Body.Add(new TextBlock()
{
Text = "Adaptive Card design session",
Size = TextSize.Large,
Weight = TextWeight.Bolder
});
// Add text to the card.
card.Body.Add(new TextBlock()
{
Text = "Conf Room 112/3377 (10)"
});
// Add text to the card.
card.Body.Add(new TextBlock()
{
Text = "12:30 PM - 1:30 PM"
});
// Add list of choices to the card.
card.Body.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" }
}
});
// Add buttons to the card.
card.Actions.Add(new HttpAction()
{
Url = "http://foo.com",
Title = "Snooze"
});
card.Actions.Add(new HttpAction()
{
Url = "http://foo.com",
Title = "I'll be late"
});
card.Actions.Add(new HttpAction()
{
Url = "http://foo.com",
Title = "Dismiss"
});
// Create the attachment.
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
replyToConversation.Attachments.Add(attachment);
var reply = await connector.Conversations.SendToConversationAsync(replyToConversation);
}
}
}
}
Related
Hi i tried all these methods of attaching a video to a bot. All of them are working fine in bot emulator. But when i publish it to messenger it is throwing an exception . (I can't see the exception by the way i just know because of the message. Is there a way to see or log exceptions?). Is video card not supported in messenger? Or is youtube not supported as an url link?
Here are the codes:
AddStep(async (stepContext, cancellationToken) =>
{
var reply = stepContext.Context.Activity.CreateReply();
reply.Attachments = new List<Attachment>();
reply.Attachments.Add(GetVideoCard().ToAttachment());
await stepContext.Context.SendActivityAsync(reply, cancellationToken);
return await stepContext.NextAsync();
});
////////////////
private static VideoCard GetVideoCard()
{
var videoCard = new VideoCard
{
Title = "Budgeting Introduction",
Subtitle = "by Finko",
Media = new List<MediaUrl>
{
new MediaUrl()
{
Url = "https://www.youtube.com/watch?v=XLo1geVokhA",
},
},
Buttons = new List<CardAction>
{
new CardAction()
{
Title = "Learn More at Finko.PH",
Type = ActionTypes.OpenUrl,
Value = "https://m-moreno.wixsite.com/finkoph?fbclid=IwAR1NVtlyKfzZ0mYFIWva8L-d8TUv4KFpt_m1i1ij3raT-pbWr2c3-kqzB2Q",
},
},
};
return videoCard;
}
and
AddStep(async (stepContext, cancellationToken) =>
{
var activity = stepContext.Context.Activity;
await stepContext.Context.SendActivityAsync(CreateResponse(activity, CreateVideoCardAttacment()));
return await stepContext.NextAsync();
});
////////////////////////
private Activity CreateResponse(Activity activity, Attachment attachment)
{
var response = activity.CreateReply();
response.Attachments = new List<Attachment>() { attachment };
return response;
}
private Attachment CreateVideoCardAttacment()
{
return new VideoCard()
{
Title = "Are you a Seafarer? OFW? FREE PERSONAL FINANCIAL ADVICE HERE!!",
Media = new List<MediaUrl>()
{
new MediaUrl("https://www.youtube.com/watch?v=XLo1geVokhA")
},
Buttons = new List<CardAction>()
{
new CardAction()
{
Type = ActionTypes.OpenUrl,
Title = "Learn More at Finko.PH",
Value = "https://m-moreno.wixsite.com/finkoph?fbclid=IwAR1NVtlyKfzZ0mYFIWva8L-d8TUv4KFpt_m1i1ij3raT-pbWr2c3-kqzB2Q"
}
},
Subtitle = "by Finko.Ph",
Text = "Are you tired of getting bogus financial advice? Tired of having 'kape' just to find out it was networking, or a pyramid scheme? Tired of scouring the internet for HOURS but not finding what you're looking for? We're here to help! We give financial advice and will educate you on financial literacy topics, ABSOLUTELY FREE!!"
}.ToAttachment();
}
and
Activity reply = stepContext.Context.Activity.CreateReply();
var card = new VideoCard
{
Title = "Finko.ph",
Media = new List<MediaUrl>()
{
new MediaUrl("https://www.youtube.com/watch?v=XLo1geVokhA")
},
Buttons = new List<CardAction>()
{
new CardAction()
{
Type = ActionTypes.OpenUrl,
Title = "Learn More at Finko.PH",
Value = "https://m-moreno.wixsite.com/finkoph?fbclid=IwAR1NVtlyKfzZ0mYFIWva8L-d8TUv4KFpt_m1i1ij3raT-pbWr2c3-kqzB2Q"
}
},
};
reply.Attachments.Add(card.ToAttachment());
await stepContext.Context.SendActivityAsync(reply);
return await stepContext.NextAsync();
and
var reply1 = stepContext.Context.Activity.CreateReply();
var attachment1 = new Attachment
{
ContentUrl = "https://www.youtube.com/watch?v=XLo1geVokhA",
ContentType = "video/mp4",
Name = "imageName1",
};
reply1.Attachments = new List<Attachment>() { attachment1 };
await stepContext.Context.SendActivityAsync(reply1, cancellationToken);
return await stepContext.NextAsync();
All of these codes are working in bot emulator but not in messenger. Any help would be appreciated thank you.
The BotFramework converts Video Cards into Media Templates for Facebook Messenger, and per Facebook's Developer documentation, media templates do not allow any external URLs, only those on Facebook. You must either upload the video to Facebook or provide a URL directly to the mp4 file which, unfortunately, YouTube doesn't make readily available.
For more details, take a look at Facebooks documentation regarding Media Templates.
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"
});
I am trying to use the fluent API to create a simple flow. But instead of using plain text I want to use rich visual components. Here is an example.
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
var yn = Chain
.PostToChain()
.Select(m => CreateYesNoPrompt(activity)) //This is a dialog which should provide some buttons to the user
.PostToUser()
.WaitToBot()
.Select(x => x.Text)
.Switch
(
Chain.Case
(
s => s == "S",
new ContextualSelector<string, IDialog<string>>((context, item) => Chain.Return("Yes"))
),
Chain.Default<string, IDialog<string>>((context, text) => Chain.Return("No"))
)
.Unwrap()
.PostToUser();
await Conversation.SendAsync(activity, () => yn);
return Request.CreateResponse(HttpStatusCode.OK);
}
private static Activity CreateYesNoPrompt(Activity activity)
{
var reply = activity.CreateReply();
var ybutton = new CardAction(type: "postBack", title: "Yes", value: "S");
var nbutton = new CardAction(type: "postBack", title: "No", value: "N");
var buttons = new List<CardAction>() { ybutton, nbutton };
var card = new HeroCard("Would you like to start an order?", "Subtitle", buttons: buttons);
reply.Attachments = new List<Attachment> { card.ToAttachment() };
return reply;
}
Instead of the expected output, the bot is outputting Microsoft.Bot.Connector.Activity, which is the ToString() return of the Activity object.
How to I use cards within dialogs?
This shows a card when passed a DialogContext:
private static Activity ShowButtons(IDialogContext context, string strText)
{
// Create a reply Activity
Activity replyToConversation = (Activity)context.MakeMessage();
replyToConversation.Text = strText;
replyToConversation.Recipient = replyToConversation.Recipient;
replyToConversation.Type = "message";
// Call the CreateButtons utility method
// that will create 5 buttons to put on the Here Card
List<CardAction> cardButtons = CreateButtons();
// Create a Hero Card and add the buttons
HeroCard plCard = new HeroCard()
{
Buttons = cardButtons
};
// Create an Attachment
// set the AttachmentLayout as 'list'
Attachment plAttachment = plCard.ToAttachment();
replyToConversation.Attachments.Add(plAttachment);
replyToConversation.AttachmentLayout = "list";
// Return the reply to the calling method
return replyToConversation;
}
See:
Using Images, Cards, Carousels, and Buttons In The Microsoft Bot Framework
I try to show the keyboard chatting telegram using botframework, but the keyboard is not displayed. I tried send keybord like this:
Activity reply = activity.CreateReply(message);
var keyboard =new ReplyKeyboardMarkup
{
Keyboard = new[] { new[] { new KeyboardButton("Text1"), new KeyboardButton("text1") } }
};
reply.ChannelData = keyboard;
await connector.Conversations.ReplyToActivityAsync(reply);
And many other ways. But keyboard does not show up.
What could be the reason? How to make it show up?
You don't need to use ChannelData. Just send the buttons on a HeroCard:
var card = new HeroCard("Some Text");
card.Buttons = new List<CardAction>()
{
new CardAction()
{
Title = "button1",
Type=ActionTypes.ImBack,
Value="button1"
},
new CardAction()
{
Title = "button2",
Type=ActionTypes.ImBack,
Value="button2"
}
};
var reply = activity.CreateReply("");
reply.Attachments = new List<Attachment>();
reply.Attachments.Add(new Attachment()
{
ContentType = HeroCard.ContentType,
Content = card
});
return reply;