Pesan yang dipertukarkan antara pengguna dan bot dapat berisi lampiran media, seperti gambar, video, audio, dan file. Bot Framework SDK mendukung tugas mengirim pesan kaya kepada pengguna. Untuk menentukan jenis pesan kaya yang didukung saluran (Facebook, Slack, dan sebagainya), lihat dokumentasi saluran untuk informasi tentang batasan.
Catatan
Bot Framework JavaScript, C#, dan Python SDK akan terus didukung, namun, Java SDK dihentikan dengan dukungan jangka panjang akhir yang berakhir pada November 2023.
Bot yang ada yang dibangun dengan Java SDK akan terus berfungsi.
Properti AttachmentsActivity objek berisi array Attachment objek yang mewakili lampiran media dan kartu kaya yang dilampirkan ke pesan. Untuk menambahkan lampiran media ke pesan, buat objek untuk reply aktivitas dan atur ContentTypeproperti , ContentUrl, dan Name .Attachment
Untuk membuat pesan balasan, tentukan teks lalu siapkan lampiran. Menetapkan lampiran ke balasan sama untuk setiap jenis lampiran, namun berbagai lampiran disiapkan dan didefinisikan secara berbeda, seperti yang terlihat dalam cuplikan berikut. Kode di bawah ini menyiapkan balasan untuk lampiran sebaris:
Bot/AttachmentsBot.cs
{
reply = MessageFactory.Text("This is an inline attachment.");
Selanjutnya, kita melihat jenis lampiran. Pertama adalah lampiran sebaris:
Bot/AttachmentsBot.cs
{
var imagePath = Path.Combine(Environment.CurrentDirectory, @"Resources", "architecture-resize.png");
var imageData = Convert.ToBase64String(File.ReadAllBytes(imagePath));
return new Attachment
{
Name = @"Resources\architecture-resize.png",
ContentType = "image/png",
ContentUrl = $"data:image/png;base64,{imageData}",
};
}
Kemudian, lampiran yang diunggah:
Bot/AttachmentsBot.cs
{
if (string.IsNullOrWhiteSpace(serviceUrl))
{
throw new ArgumentNullException(nameof(serviceUrl));
}
if (string.IsNullOrWhiteSpace(conversationId))
{
throw new ArgumentNullException(nameof(conversationId));
}
var imagePath = Path.Combine(Environment.CurrentDirectory, @"Resources", "architecture-resize.png");
var connector = turnContext.TurnState.Get<IConnectorClient>() as ConnectorClient;
var attachments = new Attachments(connector);
var response = await attachments.Client.Conversations.UploadAttachmentAsync(
conversationId,
new AttachmentData
{
Name = @"Resources\architecture-resize.png",
OriginalBase64 = File.ReadAllBytes(imagePath),
Type = "image/png",
},
cancellationToken);
var attachmentUri = attachments.GetAttachmentUri(response.Id);
return new Attachment
{
Name = @"Resources\architecture-resize.png",
ContentType = "image/png",
ContentUrl = attachmentUri,
};
}
Terakhir, lampiran internet:
Bot/AttachmentsBot.cs
{
// ContentUrl must be HTTPS.
return new Attachment
{
Name = @"Resources\architecture-resize.png",
ContentType = "image/png",
ContentUrl = "https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png",
};
}
}
Untuk membuat pesan balasan, tentukan teks lalu siapkan lampiran. Menetapkan lampiran ke balasan sama untuk setiap jenis lampiran, namun berbagai lampiran disiapkan dan didefinisikan secara berbeda, seperti yang terlihat dalam cuplikan berikut. Kode di bawah ini menyiapkan balasan untuk lampiran sebaris:
bot/attachmentsBot.js
*/
const firstChar = turnContext.activity.text[0];
if (firstChar === '1') {
Untuk mengirimi pengguna satu konten seperti gambar atau video, Anda dapat mengirim media dengan beberapa cara berbeda. Pertama, sebagai lampiran sebaris:
Terakhir, lampiran internet yang terkandung dalam URL:
bot/attachmentsBot.js
* Returns an attachment to be sent to the user from a HTTPS URL.
*/
getInternetAttachment() {
// NOTE: The contentUrl must be HTTPS.
return {
name: 'architecture-resize.png',
contentType: 'image/png',
contentUrl: 'https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png'
Metode getAttachments()Activity objek berisi array Attachment objek yang mewakili lampiran media dan kartu kaya yang dilampirkan ke pesan. Untuk menambahkan lampiran media ke pesan, buat objek untuk reply aktivitas dan atur ContentTypeproperti , ContentUrl, dan Name .Attachment
Untuk membuat pesan balasan, tentukan teks lalu siapkan lampiran. Menetapkan lampiran ke balasan sama untuk setiap jenis lampiran, namun berbagai lampiran disiapkan dan didefinisikan secara berbeda, seperti yang terlihat dalam cuplikan berikut. Kode di bawah ini menyiapkan balasan untuk lampiran sebaris:
AttachmentsBot.java
result = getInlineAttachment()
.thenApply(attachment -> {
Activity reply = MessageFactory.text("This is an inline attachment.");
reply.setAttachment(attachment);
return reply;
});
Selanjutnya, kita melihat jenis lampiran. Pertama adalah lampiran sebaris:
AttachmentsBot.java
// Creates an inline attachment sent from the bot to the user using a base64 string.
// Using a base64 string to send an attachment will not work on all channels.
// Additionally, some channels will only allow certain file types to be sent this way.
// For example a .png file may work but a .pdf file may not on some channels.
// Please consult the channel documentation for specifics.
private CompletableFuture<Attachment> getInlineAttachment() {
return getEncodedFileData("architecture-resize.png")
.thenApply(encodedFileData -> {
Attachment attachment = new Attachment();
attachment.setName("architecture-resize.png");
attachment.setContentType("image/png");
attachment.setContentUrl("data:image/png;base64," + encodedFileData);
return attachment;
});
}
// Creates an Attachment to be sent from the bot to the user from a HTTP URL.
private static Attachment getInternetAttachment() {
// ContentUrl must be HTTPS.
Attachment attachment = new Attachment();
attachment.setName("architecture-resize.png");
attachment.setContentType("image/png");
attachment.setContentUrl("https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png");
return attachment;
}
Untuk membuat pesan balasan, tentukan teks lalu siapkan lampiran. Menetapkan lampiran ke balasan sama untuk setiap jenis lampiran, namun berbagai lampiran disiapkan dan didefinisikan secara berbeda, seperti yang terlihat dalam cuplikan berikut.
Kode di bawah ini menyiapkan balasan untuk lampiran sebaris:
bot/attachments_bot.py
reply.text = "This is an inline attachment."
reply.attachments = [self._get_inline_attachment()]
Untuk mengirimi pengguna satu konten seperti gambar atau video, Anda dapat mengirim media dengan beberapa cara berbeda. Pertama, sebagai lampiran sebaris:
bot/attachments_bot.py
def _get_inline_attachment(self) -> Attachment:
"""
Creates an inline attachment sent from the bot to the user using a base64 string.
Using a base64 string to send an attachment will not work on all channels.
Additionally, some channels will only allow certain file types to be sent this way.
For example a .png file may work but a .pdf file may not on some channels.
Please consult the channel documentation for specifics.
:return: Attachment
"""
file_path = os.path.join(os.getcwd(), "resources/architecture-resize.png")
with open(file_path, "rb") as in_file:
base64_image = base64.b64encode(in_file.read()).decode()
return Attachment(
name="architecture-resize.png",
content_type="image/png",
content_url=f"data:image/png;base64,{base64_image}",
)
Kemudian, lampiran yang diunggah:
bot/attachments_bot.py
async def _get_upload_attachment(self, turn_context: TurnContext) -> Attachment:
"""
Creates an "Attachment" to be sent from the bot to the user from an uploaded file.
:param turn_context:
:return: Attachment
"""
with open(
os.path.join(os.getcwd(), "resources/architecture-resize.png"), "rb"
) as in_file:
image_data = in_file.read()
connector = await turn_context.adapter.create_connector_client(
turn_context.activity.service_url
)
conversation_id = turn_context.activity.conversation.id
response = await connector.conversations.upload_attachment(
conversation_id,
AttachmentData(
name="architecture-resize.png",
original_base64=image_data,
type="image/png",
),
)
base_uri: str = connector.config.base_url
attachment_uri = (
base_uri
+ ("" if base_uri.endswith("/") else "/")
+ f"v3/attachments/{response.id}/views/original"
)
return Attachment(
name="architecture-resize.png",
content_type="image/png",
content_url=attachment_uri,
)
Terakhir, lampiran internet yang terkandung dalam URL:
bot/attachments_bot.py
def _get_internet_attachment(self) -> Attachment:
"""
Creates an Attachment to be sent from the bot to the user from a HTTP URL.
:return: Attachment
"""
return Attachment(
name="architecture-resize.png",
content_type="image/png",
content_url="https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png",
)
Jika lampiran adalah gambar, audio, atau video, layanan Konektor akan mengkomunikasikan data lampiran ke saluran dengan cara yang memungkinkan saluran merender lampiran tersebut dalam percakapan. Jika lampiran adalah file, URL file akan dirender sebagai hyperlink dalam percakapan.
Mengirim kartu pahlawan
Selain lampiran gambar atau video sederhana, Anda dapat melampirkan kartu hero, yang memungkinkan Anda menggabungkan gambar dan tombol dalam satu objek, dan mengirimkannya ke pengguna. Markdown didukung untuk sebagian besar bidang teks, tetapi dukungan dapat bervariasi menurut saluran.
private static async Task DisplayOptionsAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
// Create a HeroCard with options for the user to interact with the bot.
var card = new HeroCard
{
Text = "You can upload an image or select one of the following choices",
Buttons = new List<CardAction>
{
// Note that some channels require different values to be used in order to get buttons to display text.
// In this code the emulator is accounted for with the 'title' parameter, but in other channels you may
// need to provide a value for other parameters like 'text' or 'displayText'.
new CardAction(ActionTypes.ImBack, title: "1. Inline Attachment", value: "1"),
new CardAction(ActionTypes.ImBack, title: "2. Internet Attachment", value: "2"),
new CardAction(ActionTypes.ImBack, title: "3. Uploaded Attachment", value: "3"),
},
};
var reply = MessageFactory.Attachment(card.ToAttachment());
await turnContext.SendActivityAsync(reply, cancellationToken);
Untuk membuat pesan dengan kartu dan tombol hero, Anda dapat melampirkan HeroCard objek ke pesan.
* @param {Object} turnContext
*/
async displayOptions(turnContext) {
const reply = { type: ActivityTypes.Message };
// Note that some channels require different values to be used in order to get buttons to display text.
// In this code the emulator is accounted for with the 'title' parameter, but in other channels you may
// need to provide a value for other parameters like 'text' or 'displayText'.
const buttons = [
{ type: ActionTypes.ImBack, title: '1. Inline Attachment', value: '1' },
{ type: ActionTypes.ImBack, title: '2. Internet Attachment', value: '2' },
{ type: ActionTypes.ImBack, title: '3. Uploaded Attachment', value: '3' }
];
const card = CardFactory.heroCard('', undefined,
buttons, { text: 'You can upload an image or select one of the following choices.' });
reply.attachments = [card];
Untuk membuat pesan dengan kartu dan tombol hero, Anda dapat melampirkan HeroCard objek ke pesan.
private static CompletableFuture<Void> displayOptions(TurnContext turnContext) {
// Create a HeroCard with options for the user to interact with the bot.
HeroCard card = new HeroCard();
card.setText("You can upload an image or select one of the following choices");
// Note that some channels require different values to be used in order to get buttons to display text.
// In this code the emulator is accounted for with the 'title' parameter, but in other channels you may
// need to provide a value for other parameters like 'text' or 'displayText'.
card.setButtons(
new CardAction(ActionTypes.IM_BACK, "1. Inline Attachment", "1"),
new CardAction(ActionTypes.IM_BACK, "2. Internet Attachment", "2"),
new CardAction(ActionTypes.IM_BACK, "3. Uploaded Attachment", "3")
);
Activity reply = MessageFactory.attachment(card.toAttachment());
return turnContext.sendActivity(reply).thenApply(resourceResponse -> null);
}
Untuk membuat pesan dengan kartu dan tombol hero, Anda dapat melampirkan HeroCard objek ke pesan.
async def _display_options(self, turn_context: TurnContext):
"""
Create a HeroCard with options for the user to interact with the bot.
:param turn_context:
:return:
"""
# Note that some channels require different values to be used in order to get buttons to display text.
# In this code the emulator is accounted for with the 'title' parameter, but in other channels you may
# need to provide a value for other parameters like 'text' or 'displayText'.
card = HeroCard(
text="You can upload an image or select one of the following choices",
buttons=[
CardAction(
type=ActionTypes.im_back, title="1. Inline Attachment", value="1"
),
CardAction(
type=ActionTypes.im_back, title="2. Internet Attachment", value="2"
),
CardAction(
type=ActionTypes.im_back, title="3. Uploaded Attachment", value="3"
),
],
)
Memproses peristiwa dalam kartu kaya
Untuk memproses peristiwa dalam kartu kaya, gunakan objek tindakan kartu untuk menentukan apa yang harus terjadi saat pengguna memilih tombol atau mengetuk bagian kartu. Setiap tindakan kartu memiliki properti jenis dan nilai .
Agar berfungsi dengan benar, tetapkan jenis tindakan ke setiap item yang dapat diklik pada kartu hero. Tabel ini mencantumkan dan menjelaskan jenis tindakan yang tersedia dan apa yang harus ada di properti nilai terkait.
Tindakan messageBack kartu memiliki arti yang lebih umum daripada tindakan kartu lainnya. Lihat bagian Tindakan kartu dari skema Aktivitas untuk informasi selengkapnya tentang messageBack jenis tindakan kartu dan lainnya.
Tipe
Deskripsi
Nilai
panggil
Memulai panggilan telepon.
Tujuan untuk panggilan telepon dalam format ini: tel:123123123123.
downloadFile
Mengunduh file.
URL file yang akan diunduh.
imBack
Mengirim pesan ke bot, dan memposting respons yang terlihat dalam obrolan.
Teks pesan yang akan dikirim.
messageBack
Mewakili respons teks yang akan dikirim melalui sistem obrolan.
Nilai terprogram opsional untuk disertakan dalam pesan yang dihasilkan.
openUrl
Membuka URL di browser bawaan.
URL yang akan dibuka.
playAudio
Memutar audio.
URL audio yang akan diputar.
playVideo
Memutar video.
URL video yang akan diputar.
postBack
Mengirim pesan ke bot, dan mungkin tidak memposting respons yang terlihat dalam obrolan.
Teks pesan yang akan dikirim.
showImage
Menampilkan gambar.
URL gambar yang akan ditampilkan.
masuk
Memulai proses masuk OAuth.
URL alur OAuth untuk memulai.
Kartu hero menggunakan berbagai jenis peristiwa
Kode berikut menunjukkan contoh menggunakan berbagai peristiwa kartu kaya.
public static HeroCard GetHeroCard()
{
var heroCard = new HeroCard
{
Title = "BotFramework Hero Card",
Subtitle = "Microsoft Bot Framework",
Text = "Build and connect intelligent bots to interact with your users naturally wherever they are," +
" from text/sms to Skype, Slack, Office 365 mail and other popular services.",
Images = new List<CardImage> { new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg") },
Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Get Started", value: "https://docs.microsoft.com/bot-framework") },
};
return heroCard;
}
Cards.cs
public static SigninCard GetSigninCard()
{
var signinCard = new SigninCard
{
Text = "BotFramework Sign-in Card",
Buttons = new List<CardAction> { new CardAction(ActionTypes.Signin, "Sign-in", value: "https://login.microsoftonline.com/") },
};
return signinCard;
}
createOAuthCard() {
return CardFactory.oauthCard(
'OAuth connection', // Replace with the name of your Azure AD connection
'Sign In',
'BotFramework OAuth Card'
);
}
public static HeroCard getHeroCard() {
HeroCard heroCard = new HeroCard();
heroCard.setTitle("BotFramework Hero Card");
heroCard.setSubtitle("Microsoft Bot Framework");
heroCard.setText("Build and connect intelligent bots to interact with your users naturally wherever they are," +
" from text/sms to Skype, Slack, Office 365 mail and other popular services.");
heroCard.setImages(new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg"));
heroCard.setButtons(new CardAction(ActionTypes.OPEN_URL, "Get Started", "https://docs.microsoft.com/bot-framework"));
return heroCard;
}
Cards.java
public static SigninCard getSigninCard() {
SigninCard signinCard = new SigninCard();
signinCard.setText("BotFramework Sign-in Card");
signinCard.setButtons(new CardAction(ActionTypes.SIGNIN, "Sign-in", "https://login.microsoftonline.com/"));
return signinCard;
}
def create_oauth_card(self) -> Attachment:
card = OAuthCard(
text="BotFramework OAuth Card",
connection_name="OAuth connection", # Replace it with the name of your Azure AD connection.
buttons=[
CardAction(
type=ActionTypes.signin,
title="Sign in",
value="https://example.org/signin",
)
],
)
return CardFactory.oauth_card(card)
Mengirim Kartu Adaptif
Meskipun Anda dapat menggunakan pabrik pesan untuk membuat pesan yang berisi lampiran (dari jenis apa pun), Kartu Adaptif adalah salah satu jenis lampiran tertentu. Tidak semua saluran mendukung Kartu Adaptif, dan beberapa saluran mungkin hanya sebagian mendukung Kartu Adaptif. Misalnya, jika Anda mengirim Kartu Adaptif di Facebook, tombol tidak akan berfungsi saat teks dan gambar berfungsi dengan baik. Pabrik pesan adalah kelas pembantu Bot Framework SDK yang digunakan untuk mengotomatiskan langkah-langkah pembuatan untuk Anda.
Kartu Adaptif adalah format pertukaran kartu terbuka yang memungkinkan pengembang untuk bertukar konten UI dengan cara yang sama dan konsisten. Namun, tidak semua saluran mendukung Kartu Adaptif.
Perancang Kartu Adaptif memberikan pengalaman waktu desain interaktif yang kaya untuk menulis kartu adaptif.
Catatan
Anda harus menguji fitur ini dengan saluran yang akan digunakan bot Anda untuk menentukan apakah saluran tersebut mendukung kartu adaptif.
Pesan juga dapat menyertakan beberapa lampiran dalam tata letak carousel, yang menempatkan lampiran berdampingan dan memungkinkan pengguna untuk menggulir.
Pertama, buat balasan dan tentukan lampiran sebagai daftar.
// Cards are sent as Attachments in the Bot Framework.
// So we need to create a list of attachments for the reply activity.
var attachments = new List<Attachment>();
// Reply to the activity we received with an activity.
var reply = MessageFactory.Attachment(attachments);
Kemudian tambahkan lampiran dan atur jenis tata letak ke carousel.
Di sini kami menambahkannya satu per satu, tetapi jangan ragu untuk memanipulasi daftar untuk menambahkan kartu sesuka Anda.
// Display a carousel of all the rich card types.
reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
reply.Attachments.Add(Cards.CreateAdaptiveCardAttachment());
reply.Attachments.Add(Cards.GetAnimationCard().ToAttachment());
reply.Attachments.Add(Cards.GetAudioCard().ToAttachment());
reply.Attachments.Add(Cards.GetHeroCard().ToAttachment());
reply.Attachments.Add(Cards.GetOAuthCard().ToAttachment());
reply.Attachments.Add(Cards.GetReceiptCard().ToAttachment());
reply.Attachments.Add(Cards.GetSigninCard().ToAttachment());
reply.Attachments.Add(Cards.GetThumbnailCard().ToAttachment());
reply.Attachments.Add(Cards.GetVideoCard().ToAttachment());
Setelah lampiran ditambahkan, Anda dapat mengirim balasan seperti yang lain.
// Send the card(s) to the user as an attachment to the activity
await stepContext.Context.SendActivityAsync(reply, cancellationToken);
Pertama, buat balasan dan tentukan lampiran sebagai daftar.
// Cards are sent as Attachments in the Bot Framework.
// So we need to create a list of attachments for the reply activity.
List<Attachment> attachments = new ArrayList<>();
// Reply to the activity we received with an activity.
Activity reply = MessageFactory.attachment(attachments);
Kemudian tambahkan lampiran dan atur jenis tata letak ke carousel.
Di sini kami menambahkannya satu per satu, tetapi jangan ragu untuk memanipulasi daftar untuk menambahkan kartu sesuka Anda.
// Display a carousel of all the rich card types.
reply.setAttachmentLayout(AttachmentLayoutTypes.CAROUSEL);
reply.getAttachments().add(Cards.createAdaptiveCardAttachment());
reply.getAttachments().add(Cards.getAnimationCard().toAttachment());
reply.getAttachments().add(Cards.getAudioCard().toAttachment());
reply.getAttachments().add(Cards.getHeroCard().toAttachment());
reply.getAttachments().add(Cards.getOAuthCard().toAttachment());
reply.getAttachments().add(Cards.getReceiptCard().toAttachment());
reply.getAttachments().add(Cards.getSigninCard().toAttachment());
reply.getAttachments().add(Cards.getThumbnailCard().toAttachment());
reply.getAttachments().add(Cards.getVideoCard().toAttachment());
Setelah lampiran ditambahkan, Anda dapat mengirim balasan seperti yang lain.
// Send the card(s) to the user as an attachment to the activity
return stepContext.getContext().sendActivity(reply)
Pertama, buat balasan dan tentukan lampiran sebagai daftar.
reply = MessageFactory.list([])
Kemudian tambahkan lampiran dan atur jenis tata letak ke carousel.
Di sini kami menambahkannya satu per satu, tetapi jangan ragu untuk memanipulasi daftar untuk menambahkan kartu sesuka Anda.
Setelah lampiran ditambahkan, Anda dapat mengirim balasan seperti yang lain.
# Send the card(s) to the user as an attachment to the activity
await step_context.context.send_activity(reply)
Sampel kode untuk memproses input Kartu Adaptif
Sampel berikut menunjukkan salah satu cara untuk menggunakan input Kartu Adaptif dalam kelas dialog bot.
Ini memperluas sampel kartu hero dengan memvalidasi input yang diterima di bidang teks dari klien yang merespons.
Anda harus terlebih dahulu menambahkan fungsionalitas input teks dan tombol ke kartu adaptif yang ada dengan menambahkan kode berikut tepat sebelum tanda kurung akhir adaptiveCard.json, yang terletak di folder sumber daya:
ID bidang input teks diatur ke "teks". Ketika pengguna memilih OK, pesan yang dihasilkan Kartu Adaptif akan memiliki properti nilai yang memiliki properti bernama text yang berisi informasi yang dimasukkan pengguna di bidang input teks kartu.
Validator kami menggunakan Newtonsoft.json untuk terlebih dahulu mengonversi ini menjadi JObject, lalu membuat string teks yang dipangkas untuk perbandingan. Jadi tambahkan:
using System;
using System.Linq;
using Newtonsoft.Json.Linq;
untuk MainDialog.cs dan menginstal paket NuGet stabil terbaru newtonsoft.Json.
Dalam kode validator, kami menambahkan alur logika ke dalam komentar kode.
Metode ini ChoiceValidator ditempatkan ke dalam sampel Menggunakan kartu tepat setelah kurung kurawal tertutup publik untuk deklarasi MainDialog:
private async Task ChoiceValidator(
PromptValidatorContext promptContext,
CancellationToken cancellationToken)
{
// Retrieves Adaptive Card comment text as JObject.
// looks for JObject field "text" and converts that input into a trimmed text string.
var jobject = promptContext.Context.Activity.Value as JObject;
var jtoken = jobject?["text"];
var text = jtoken?.Value().Trim();
// Logic: 1. if succeeded = true, just return promptContext
// 2. if false, see if JObject contained Adaptive Card input.
// No = (bad input) return promptContext
// Yes = update Value field with JObject text string, return "true".
if (!promptContext.Recognized.Succeeded && text != null)
{
var choice = promptContext.Options.Choices.FirstOrDefault(
c => c.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase));
if (choice != null)
{
promptContext.Recognized.Value = new FoundChoice
{
Value = choice.Value,
};
return true;
}
}
return promptContext.Recognized.Succeeded;
}
Sekarang di atas dalam MainDialog perubahan deklarasi:
// Define the main dialog and its related components.
AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
untuk:
// Define the main dialog and its related components.
AddDialog(new ChoicePrompt(nameof(ChoicePrompt), ChoiceValidator));
Ini akan memanggil validator Anda untuk mencari input Kartu Adaptif setiap kali permintaan pilihan baru dibuat.
Buka mainDialog.js dan temukan metode async run(turnContext, accessor) jalankan Metode ini menangani aktivitas masuk.
Tepat setelah panggilan dialogSet.add(this); , tambahkan yang berikut ini:
// The following check looks for a non-existent text input
// plus Adaptive Card input in _activity.value.text
// If both conditions exist, the Activity Card text
// is copied into the text input field.
if(turnContext._activity.text == null
&& turnContext._activity.value.text != null) {
this.logger.log('replacing null text with Activity Card text input');
turnContext._activity.text = turnContext._activity.value.text;
}
Jika pemeriksaan ini menemukan input teks yang tidak ada dari klien, pemeriksaan ini akan melihat apakah ada input dari Kartu Adaptif.
Jika ada input Kartu Adaptif di _activity.value.text, input ini akan disalin ke bidang input teks normal.
Validator kami menggunakan pembantu Serialisasi dari com.microsoft.bot.schema untuk terlebih dahulu mengonversinya menjadi JsonNode, lalu membuat string teks yang dipangkas untuk perbandingan. Kita juga akan memerlukan beberapa impor lain untuk menyelesaikan ini, jadi tambahkan:
untuk MainDialog.java.
Dalam kode validator, kami menambahkan alur logika ke dalam komentar kode.
Ekspresi ini PromptValidator ditempatkan ke dalam sampel Menggunakan kartu tepat setelah kurung kurawal tertutup publik untuk deklarasi MainDialog:
PromptValidator<FoundChoice> validator = (promptContext) -> {
// Retrieves Adaptive Card comment text as JObject.
// looks for JObject field "text" and converts that input into a trimmed text
// string.
JsonNode jsonNode = Serialization.getAs(promptContext.getContext().getActivity().getValue(), JsonNode.class);
JsonNode textNode = jsonNode != null ? jsonNode.get("text") : null;
String text = textNode != null ? textNode.textValue() : "";
// Logic: 1. if succeeded = true, just return promptContext
// 2. if false, see if JObject contained Adaptive Card input.
// No = (bad input) return promptContext
// Yes = update Value field with JObject text string, return "true".
if (!promptContext.getRecognized().getSucceeded() && text != null) {
Optional<Choice> choice = promptContext.getOptions()
.getChoices()
.stream()
.filter(c -> StringUtils.compareIgnoreCase(c.getValue(), text) == 0)
.findFirst();
if (choice.isPresent()) {
promptContext.getRecognized().setValue(new FoundChoice() {
{
setValue(choice.get().getValue());
}
});
return CompletableFuture.completedFuture(true);
}
}
return CompletableFuture.completedFuture(promptContext.getRecognized().getSucceeded());
};
Sekarang di atas dalam MainDialog perubahan deklarasi:
// Define the main dialog and its related components.
addDialog(new ChoicePrompt("ChoicePrompt"));
untuk:
// Define the main dialog and its related components.
addDialog(new ChoicePrompt("ChoicePrompt", validator, null));
Ini akan memanggil validator Anda untuk mencari input Kartu Adaptif setiap kali permintaan pilihan baru dibuat.
Buat dan kirim aktivitas dengan tindakan yang disarankan kepada pengguna.
Metode ini choice_validator ditempatkan ke dalam sampel Menggunakan kartu tepat setelah kurung kurawal tertutup publik untuk deklarasi MainDialog:
@staticmethod
async def choice_validator(prompt_context: PromptValidatorContext) -> bool:
if prompt_context.context.activity.value:
text = prompt_context.context.activity.value["text"].lower()
if not prompt_context.recognized.succeeded and text:
matching_choices = [choice for choice in prompt_context.options.choices if choice.value.lower() == text]
if matching_choices:
choice = matching_choices[0]
prompt_context.recognized.value = FoundChoice(
value=choice.value,
index=0,
score=1.0
)
return True
return prompt_context.recognized.succeeded
Sekarang di atas dalam MainDialog perubahan deklarasi: