Hlavním cílem při vytváření robota je zapojit uživatele do smysluplné konverzace. Jedním z nejlepších způsobů, jak tohoto cíle dosáhnout, je zajistit, aby se od okamžiku, kdy se uživatel poprvé připojí, porozuměl hlavnímu účelu a možnostem robota, důvodu vytvoření robota. Tento článek obsahuje příklady kódu, které vám pomůžou přivítat uživatele robota.
Poznámka:
Sady SDK služby Bot Framework JavaScript, C# a Python budou nadále podporovány, ale sada Java SDK se vyřazuje s konečnou dlouhodobou podporou končící v listopadu 2023.
Stávající roboti sestavení pomocí sady Java SDK budou i nadále fungovat.
Tento ukázkový kód ukazuje, jak rozpoznat a přivítat nové uživatele, když jsou původně připojení k robotovi. Následující diagram znázorňuje tok logiky pro tohoto robota.
Mezi dvě hlavní události, se kterými robot narazí, jsou:
OnMembersAddedAsynczavolá se, když se k robotovi připojí nový uživatel.
OnMessageActivityAsync, volá se, když robot obdrží nový uživatelský vstup.
Kdykoli se připojí nový uživatel, bude k dispozici s WelcomeMessageInfoMessageuživatelem a PatternMessage robotem.
Při přijetí nového uživatelského vstupu se zkontroluje WelcomeUserState a zjistí, jestli DidBotWelcomeUser je nastavená hodnota true. Pokud ne, vrátí se uživateli počáteční uvítací zpráva uživatele.
Mezi dvě hlavní události, se kterými robot narazí, jsou:
onMembersAddedzavolá se, když se k robotovi připojí nový uživatel.
onMessage, volá se, když robot obdrží nový uživatelský vstup.
Kdykoli se připojí nový uživatel, bude k dispozici s welcomeMessageinfoMessageuživatelem a patternMessage robotem.
Při přijetí nového uživatelského vstupu se zkontroluje, welcomedUserProperty jestli didBotWelcomeUser je nastavená hodnota true. Pokud ne, vrátí se uživateli počáteční uvítací zpráva uživatele.
Pokud DidBotWelcomeUser je hodnota true, vyhodnotí se vstup uživatele. Na základě obsahu vstupu uživatele provede tento robot jednu z těchto věcí:
Ozvěte se zpět pozdravu přijatého uživatelem.
Zobrazení karty hrdiny poskytující další informace o robotech
Znovu odešlete WelcomeMessage vysvětlení očekávaných vstupů pro tohoto robota.
Mezi dvě hlavní události, se kterými robot narazí, jsou:
onMembersAddedzavolá se, když se k robotovi připojí nový uživatel.
onMessageActivity, volá se, když robot obdrží nový uživatelský vstup.
Kdykoli se připojí nový uživatel, bude k dispozici s WELCOME_MESSAGEINFO_MESSAGEuživatelem a PATTERN_MESSAGE robotem.
Při přijetí nového uživatelského vstupu se zkontroluje WelcomeUserState a zjistí, jestli getDidBotWelcomeUser() je nastavená hodnota true. Pokud ne, vrátí se uživateli počáteční uvítací zpráva uživatele.
Mezi dvě hlavní události, se kterými robot narazí, jsou:
on_members_added_activityzavolá se, když se k robotovi připojí nový uživatel.
on_message_activity, volá se, když robot obdrží nový uživatelský vstup.
Kdykoli je nový uživatel připojený, poskytne mu uvítací zpráva, informační zpráva a vzorová zpráva robota.
Při přijetí nového uživatelského vstupu je tato vlastnost zaškrtnutá welcome_user_state.did_welcome_user . Pokud není nastavená na hodnotu true, vrátí se uživateli počáteční uvítací zpráva uživatele. Pokud je nastavená na hodnotu true, na základě obsahu vstupu uživatele provede tento robot jednu z následujících věcí:
Ozvěte se zpět pozdravu přijatého uživatelem.
Zobrazení karty hrdiny poskytující další informace o robotech
Objekt stavu uživatele je vytvořen při spuštění a závislost vložen do konstruktoru robota.
Startup.cs
// Create the Bot Framework Authentication to be used with the Bot Adapter.
services.AddSingleton<BotFrameworkAuthentication, ConfigurationBotFrameworkAuthentication>();
// Create the Bot Adapter with error handling enabled.
Roboti\WelcomeUserBot.cs
// Initializes a new instance of the "WelcomeUserBot" class.
public WelcomeUserBot(UserState userState)
{
_userState = userState;
}
Při spuštění je stav uživatele definován a index.js spotřebován konstruktorem robota.
index.js
// Create HTTP server
const server = restify.createServer();
server.use(restify.plugins.bodyParser());
server.listen(process.env.port || process.env.PORT || 3978, function() {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
Objekt stavu uživatele je vytvořen při spuštění a závislost vložen do konstruktoru robota kontejnerem Spring.
Application.java
@Bean
public Bot getBot(UserState userState) {
return new WelcomeUserBot(userState);
}
WelcomeUserBot.java
private final UserState userState;
// Initializes a new instance of the "WelcomeUserBot" class.
@Autowired
public WelcomeUserBot(UserState withUserState) {
userState = withUserState;
}
Při spuštění je stav uživatele definován a app.py spotřebován konstruktorem robota.
app.py
# Create the Bot
BOT = WelcomeUserBot(USER_STATE)
# Listen for incoming requests on /api/messages.
Teď vytvoříme přístupové objekty vlastností, které nám poskytují popisovač WelcomeUserState uvnitř OnMessageActivityAsync metody.
Potom zavolejte metodu GetAsync , aby získal správně vymezený klíč. Potom pomocí metody uložíme data o stavu uživatele po každé iteraci SaveChangesAsync vstupu uživatele.
Roboti\WelcomeUserState.cs
// Gets or sets whether the user has been welcomed in the conversation.
public bool DidBotWelcomeUser { get; set; } = false;
Roboti\WelcomeUserBot.cs
var didBotWelcomeUser = await welcomeUserStateAccessor.GetAsync(turnContext, () => new WelcomeUserState(), cancellationToken);
this.onMessage(async (context, next) => {
// Read UserState. If the 'DidBotWelcomedUser' does not exist (first time ever for a user)
// set the default to false.
const didBotWelcomedUser = await this.welcomedUserProperty.get(context, false);
/**
* Override the ActivityHandler.run() method to save state changes after the bot logic completes.
*/
async run(context) {
await super.run(context);
// Save state changes
await this.userState.saveChanges(context);
}
Teď vytvoříme přístupové objekty vlastností, které nám poskytují popisovač WelcomeUserState uvnitř onMessageActivity metody.
Potom zavolejte metodu get , aby získal správně vymezený klíč. Potom pomocí metody uložíme data o stavu uživatele po každé iteraci saveChanges vstupu uživatele.
WelcomeUserBot.java
// Get state data from UserState.
StatePropertyAccessor<WelcomeUserState> stateAccessor =
userState.createProperty("WelcomeUserState");
CompletableFuture<WelcomeUserState> stateFuture =
stateAccessor.get(turnContext, WelcomeUserState::new);
Používá přistupovač vlastnosti v on_message_activity obslužné rutině a přepíše obslužnou rutinu on_turn k uložení stavu před koncem turnu.
# Get the state properties from the turn context.
welcome_user_state = await self.user_state_accessor.get(
turn_context, WelcomeUserState
)
async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)
# save changes to WelcomeUserState after each turn
await self._user_state.save_changes(turn_context)
V aplikaci WelcomeUserBot zkontrolujeme aktualizaci aktivit pomocí funkce OnMembersAddedAsync() Zjistit, jestli byl do konverzace přidán nový uživatel, a pak jim pošleme sadu tří počátečních uvítacích zpráv WelcomeMessageInfoMessage a PatternMessage. Níže je uvedený úplný kód pro tuto interakci.
Roboti\WelcomeUserBot.cs
public class WelcomeUserBot : ActivityHandler
{
// Messages sent to the user.
private const string WelcomeMessage = "This is a simple Welcome Bot sample. This bot will introduce you " +
"to welcoming and greeting users. You can say 'intro' to see the " +
"introduction card. If you are running this bot in the Bot Framework " +
"Emulator, press the 'Start Over' button to simulate user joining " +
"a bot or a channel";
private const string InfoMessage = "You are seeing this message because the bot received at least one " +
"'ConversationUpdate' event, indicating you (and possibly others) " +
"joined the conversation. If you are using the emulator, pressing " +
"the 'Start Over' button to trigger this event again. The specifics " +
"of the 'ConversationUpdate' event depends on the channel. You can " +
"read more information at: " +
"https://aka.ms/about-botframework-welcome-user";
private const string LocaleMessage = "You can use the activity's 'GetLocale()' method to welcome the user " +
"using the locale received from the channel. " +
"If you are using the Emulator, you can set this value in Settings.";
{
foreach (var member in membersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync($"Hi there - {member.Name}. {WelcomeMessage}", cancellationToken: cancellationToken);
await turnContext.SendActivityAsync(InfoMessage, cancellationToken: cancellationToken);
await turnContext.SendActivityAsync($"{LocaleMessage} Current locale is '{turnContext.Activity.GetLocale()}'.", cancellationToken: cancellationToken);
await turnContext.SendActivityAsync(PatternMessage, cancellationToken: cancellationToken);
}
}
}
Tento kód JavaScriptu odesílá počáteční uvítací zprávy při přidání uživatele. Provede se to tak, že zkontrolujete aktivitu konverzace a ověříte, že do konverzace byl přidán nový člen.
roboti/welcomeBot.js
// Sends welcome messages to conversation members when they join the conversation.
// Messages are only sent to conversation members who aren't the bot.
this.onMembersAdded(async (context, next) => {
// Iterate over all new members added to the conversation
for (const idx in context.activity.membersAdded) {
// Greet anyone that was not the target (recipient) of this message.
// Since the bot is the recipient for events from the channel,
// context.activity.membersAdded === context.activity.recipient.Id indicates the
// bot was added to the conversation, and the opposite indicates this is a user.
if (context.activity.membersAdded[idx].id !== context.activity.recipient.id) {
await context.sendActivity(`Welcome to the 'Welcome User' Bot. This bot will introduce you to welcoming and greeting users.`);
await context.sendActivity(`You are seeing this message because the bot received at least one 'ConversationUpdate' ` +
`event, indicating you (and possibly others) joined the conversation. If you are using the emulator, ` +
`pressing the 'Start Over' button to trigger this event again. The specifics of the 'ConversationUpdate' ` +
`event depends on the channel. You can read more information at https://aka.ms/about-botframework-welcome-user`);
await context.sendActivity(`You can use the activity's 'locale' property to welcome the user ` +
`using the locale received from the channel. ` +
`If you are using the Emulator, you can set this value in Settings. ` +
`Current locale is '${ context.activity.locale }'`);
await context.sendActivity(`It is a good pattern to use this event to send general greeting to user, explaining what your bot can do. ` +
`In this example, the bot handles 'hello', 'hi', 'help' and 'intro'. ` +
`Try it now, type 'hi'`);
}
}
// By calling next() you ensure that the next BotHandler is run.
await next();
});
V aplikaci WelcomeUserBot zkontrolujeme aktualizaci aktivit pomocí funkce onMembersAdded() Zjistit, jestli byl do konverzace přidán nový uživatel, a pak jim pošleme sadu tří počátečních uvítacích zpráv WELCOME_MESSAGEINFO_MESSAGE a PATTERN_MESSAGE. Níže je uvedený úplný kód pro tuto interakci.
WelcomeUserBot.java
public class WelcomeUserBot extends ActivityHandler {
// Messages sent to the user.
private static final String WELCOME_MESSAGE =
"This is a simple Welcome Bot sample. This bot will introduce you "
+ "to welcoming and greeting users. You can say 'intro' to see the "
+ "introduction card. If you are running this bot in the Bot Framework "
+ "Emulator, press the 'Start Over' button to simulate user joining "
+ "a bot or a channel";
private static final String INFO_MESSAGE =
"You are seeing this message because the bot received at least one "
+ "'ConversationUpdate' event, indicating you (and possibly others) "
+ "joined the conversation. If you are using the emulator, pressing "
+ "the 'Start Over' button to trigger this event again. The specifics "
+ "of the 'ConversationUpdate' event depends on the channel. You can "
+ "read more information at: " + "https://aka.ms/about-botframework-welcome-user";
private String localeMessage =
"You can use the activity's GetLocale() method to welcome the user "
+ "using the locale received from the channel. "
+ "If you are using the Emulator, you can set this value in Settings.";
private static final String PATTERN_MESSAGE =
"It is a good pattern to use this event to send general greeting"
+ "to user, explaining what your bot can do. In this example, the bot "
+ "handles 'hello', 'hi', 'help' and 'intro'. Try it now, type 'hi'";
Kontroly on_members_added_activity , jestli byl přidán nový uživatel, a pak odešle tři počáteční uvítací zprávy: uvítací zprávu, informační zprávu a vzorovou zprávu.
roboti/welcome-user-bot.py
"""
Greet when users are added to the conversation.
Note that all channels do not send the conversation update activity.
If you find that this bot works in the emulator, but does not in
another channel the reason is most likely that the channel does not
send this activity.
"""
for member in members_added:
if member.id != turn_context.activity.recipient.id:
await turn_context.send_activity(
f"Hi there { member.name }. " + self.WELCOME_MESSAGE
)
await turn_context.send_activity(self.INFO_MESSAGE)
await turn_context.send_activity(
f"{ self.LOCALE_MESSAGE } Current locale is { turn_context.activity.locale }."
)
await turn_context.send_activity(self.PATTERN_MESSAGE)
Vítejte nového uživatele a zahoďte počáteční vstup.
Je také důležité zvážit, kdy vstup uživatele může ve skutečnosti obsahovat užitečné informace, a to se může u každého kanálu lišit. Abychom zajistili, že váš uživatel má dobré prostředí ve všech možných kanálech, zkontrolujeme příznak stavu didBotWelcomeUser a pokud se jedná o false, nezpracováváme počáteční uživatelský vstup. Místo toho uživateli poskytneme úvodní uvítací zprávu. Bool vítáUserProperty je pak nastaven na "true", uložený v UserState a náš kód nyní zpracuje vstup tohoto uživatele ze všech dalších aktivit zpráv.
Roboti\WelcomeUserBot.cs
{
var welcomeUserStateAccessor = _userState.CreateProperty<WelcomeUserState>(nameof(WelcomeUserState));
var didBotWelcomeUser = await welcomeUserStateAccessor.GetAsync(turnContext, () => new WelcomeUserState(), cancellationToken);
if (didBotWelcomeUser.DidBotWelcomeUser == false)
{
didBotWelcomeUser.DidBotWelcomeUser = true;
// the channel should sends the user name in the 'From' object
var userName = turnContext.Activity.From.Name;
await turnContext.SendActivityAsync("You are seeing this message because this was your first message ever to this bot.", cancellationToken: cancellationToken);
await turnContext.SendActivityAsync($"It is a good practice to welcome the user and provide personal greeting. For example, welcome {userName}.", cancellationToken: cancellationToken);
}
else
Je také důležité zvážit, kdy vstup uživatele může ve skutečnosti obsahovat užitečné informace, a to se může u každého kanálu lišit. Abychom zajistili, že váš uživatel má dobré prostředí ve všech možných kanálech, zkontrolujeme vlastnost didBotWelcomedUser, pokud neexistuje, nastavíme ji na false a nezpracujeme počáteční vstup uživatele. Místo toho uživateli poskytneme úvodní uvítací zprávu. Bool didBotWelcomeUser se pak nastaví na true a náš kód zpracuje vstup uživatele ze všech dalších aktivit zpráv.
roboti/welcomeBot.js
this.onMessage(async (context, next) => {
// Read UserState. If the 'DidBotWelcomedUser' does not exist (first time ever for a user)
// set the default to false.
const didBotWelcomedUser = await this.welcomedUserProperty.get(context, false);
// Your bot should proactively send a welcome message to a personal chat the first time
// (and only the first time) a user initiates a personal chat with your bot.
if (didBotWelcomedUser === false) {
// The channel should send the user name in the 'From' object
const userName = context.activity.from.name;
await context.sendActivity('You are seeing this message because this was your first message ever sent to this bot.');
await context.sendActivity(`It is a good practice to welcome the user and provide personal greeting. For example, welcome ${ userName }.`);
// Set the flag indicating the bot handled the user's first message.
await this.welcomedUserProperty.set(context, true);
} else {
}
// By calling next() you ensure that the next BotHandler is run.
await next();
});
Je důležité zvážit, kdy vstup uživatele může obsahovat užitečné informace, které se můžou u jednotlivých kanálů lišit. Abychom zajistili, že váš uživatel má dobré prostředí ve všech možných kanálech, zkontrolujeme příznak stavu getDidBotWelcomeUser a pokud je to false, nezpracováváme počáteční vstup uživatele. Místo toho uživateli poskytneme úvodní uvítací zprávu. Bool setDidBotWelcomeUser se pak nastaví na true, uložený v UserState a náš kód teď zpracuje vstup tohoto uživatele ze všech dalších aktivit zpráv.
WelcomeUserBot.java
@Override
protected CompletableFuture<Void> onMessageActivity(TurnContext turnContext) {
// Get state data from UserState.
StatePropertyAccessor<WelcomeUserState> stateAccessor =
userState.createProperty("WelcomeUserState");
CompletableFuture<WelcomeUserState> stateFuture =
stateAccessor.get(turnContext, WelcomeUserState::new);
return stateFuture.thenApply(thisUserState -> {
if (!thisUserState.getDidBotWelcomeUser()) {
thisUserState.setDidBotWelcomeUser(true);
// the channel should send the user name in the 'from' object
String userName = turnContext.getActivity().getFrom().getName();
return turnContext
.sendActivities(
MessageFactory.text(FIRST_WELCOME_ONE),
MessageFactory.text(String.format(FIRST_WELCOME_TWO, userName))
);
// Save any state changes.
.thenApply(response -> userState.saveChanges(turnContext))
Je také důležité zvážit, kdy vstup uživatele může ve skutečnosti obsahovat užitečné informace, může se to pro každý kanál lišit. Pokud chcete zajistit, aby uživatel měli dobré prostředí ve všech možných kanálech, on_message_activity zkontrolujte did_welcome_user vlastnost. Při prvním nastavení se nastaví na false a nezpracuje uživatelský vstup. Místo toho uživateli poskytne úvodní uvítací zprávu. Potom se nastaví did_welcome_user na true a zpracuje vstup uživatele ze všech dalších aktivit zpráv.
roboti/welcome-user-bot.py
if not welcome_user_state.did_welcome_user:
welcome_user_state.did_welcome_user = True
await turn_context.send_activity(
"You are seeing this message because this was your first message ever to this bot."
)
name = turn_context.activity.from_property.name
await turn_context.send_activity(
f"It is a good practice to welcome the user and provide personal greeting. For example: Welcome {name}"
)
Zpracování dalšího vstupu
Jakmile bude nový uživatel vítán, vyhodnocují se informace o vstupu uživatele pro každé otočení zprávy a robot poskytne odpověď na základě kontextu tohoto uživatelského vstupu. Následující kód ukazuje rozhodovací logiku použitou k vygenerování této odpovědi.
Vstup "intro" nebo "help" volá funkci SendIntroCardAsync , aby uživateli představil informační kartu hrdiny. Tento kód je zkoumán v další části tohoto článku.
Roboti\WelcomeUserBot.cs
switch (text)
{
case "hello":
case "hi":
await turnContext.SendActivityAsync($"You said {text}.", cancellationToken: cancellationToken);
break;
case "intro":
case "help":
await SendIntroCardAsync(turnContext, cancellationToken);
break;
default:
await turnContext.SendActivityAsync(WelcomeMessage, cancellationToken: cancellationToken);
break;
}
}
Vstup "intro" nebo "help" používá CardFactory k prezentaci uživatele s adaptivní kartou intro. Tento kód je zkoumán v další části tohoto článku.
roboti/welcomeBot.js
// This example uses an exact match on user's input utterance.
// Consider using LUIS or QnA for Natural Language Processing.
const text = context.activity.text.toLowerCase();
switch (text) {
case 'hello':
case 'hi':
await context.sendActivity(`You said "${ context.activity.text }"`);
break;
case 'intro':
case 'help':
await this.sendIntroCard(context);
break;
default:
await context.sendActivity(`This is a simple Welcome Bot sample. You can say 'intro' to
see the introduction card. If you are running this bot in the Bot
Framework Emulator, press the 'Start Over' button to simulate user joining a bot or a channel`);
}
Vstup "intro" nebo "help" volá funkci sendIntroCard , aby uživateli představil informační kartu hrdiny. Tento kód je zkoumán v další části tohoto článku.
WelcomeUserBot.java
// This example hardcodes specific utterances.
// You should use LUIS or QnA for more advance language understanding.
String text = turnContext.getActivity().getText().toLowerCase();
switch (text) {
case "hello":
case "hi":
return turnContext.sendActivities(MessageFactory.text("You said " + text));
case "intro":
case "help":
return sendIntroCard(turnContext);
default:
return turnContext.sendActivity(WELCOME_MESSAGE);
}
Vstup uživatele úvodu nebo nápovědy způsobí, že robot zavolá __send_intro_card, který uživateli nabídne úvodní adaptivní kartu.
roboti/welcome-user-bot.py
if text in ("hello", "hi"):
await turn_context.send_activity(f"You said { text }")
elif text in ("intro", "help"):
await self.__send_intro_card(turn_context)
else:
await turn_context.send_activity(self.WELCOME_MESSAGE)
Pozdrav pomocí karty hero
Jak už bylo zmíněno výše, některé uživatelské vstupy vygenerují v reakci na svůj požadavek kartu Hero. Další informace o pozdravech na kartě hrdiny najdete tady : Poslat úvodní kartu. Níže je uvedený kód potřebný k vytvoření odpovědi na kartu hrdiny tohoto robota.
{
var card = new HeroCard
{
Title = "Welcome to Bot Framework!",
Text = @"Welcome to Welcome Users bot sample! This Introduction card
is a great way to introduce your Bot to the user and suggest
some things to get them started. We use this opportunity to
recommend a few next steps for learning more creating and deploying bots.",
Images = new List<CardImage>() { new CardImage("https://aka.ms/bf-welcome-card-image") },
Buttons = new List<CardAction>()
{
new CardAction(ActionTypes.OpenUrl, "Get an overview", null, "Get an overview", "Get an overview", "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"),
new CardAction(ActionTypes.OpenUrl, "Ask a question", null, "Ask a question", "Ask a question", "https://stackoverflow.com/questions/tagged/botframework"),
new CardAction(ActionTypes.OpenUrl, "Learn how to deploy", null, "Learn how to deploy", "Learn how to deploy", "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"),
}
};
var response = MessageFactory.Attachment(card.ToAttachment());
await turnContext.SendActivityAsync(response, cancellationToken);
}
}
roboti/welcomeBot.js
async sendIntroCard(context) {
const card = CardFactory.heroCard(
'Welcome to Bot Framework!',
'Welcome to Welcome Users bot sample! This Introduction card is a great way to introduce your Bot to the user and suggest some things to get them started. We use this opportunity to recommend a few next steps for learning more creating and deploying bots.',
['https://aka.ms/bf-welcome-card-image'],
[
{
type: ActionTypes.OpenUrl,
title: 'Get an overview',
value: 'https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0'
},
{
type: ActionTypes.OpenUrl,
title: 'Ask a question',
value: 'https://stackoverflow.com/questions/tagged/botframework'
},
{
type: ActionTypes.OpenUrl,
title: 'Learn how to deploy',
value: 'https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0'
}
]
);
await context.sendActivity({ attachments: [card] });
}
WelcomeUserBot.java
private CompletableFuture<ResourceResponse> sendIntroCard(TurnContext turnContext) {
HeroCard card = new HeroCard();
card.setTitle("Welcome to Bot Framework!");
card.setText(
"Welcome to Welcome Users bot sample! This Introduction card "
+ "is a great way to introduce your Bot to the user and suggest "
+ "some things to get them started. We use this opportunity to "
+ "recommend a few next steps for learning more creating and deploying bots."
);
CardImage image = new CardImage();
image.setUrl("https://aka.ms/bf-welcome-card-image");
card.setImages(Collections.singletonList(image));
CardAction overviewAction = new CardAction();
overviewAction.setType(ActionTypes.OPEN_URL);
overviewAction.setTitle("Get an overview");
overviewAction.setText("Get an overview");
overviewAction.setDisplayText("Get an overview");
overviewAction.setValue(
"https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"
);
CardAction questionAction = new CardAction();
questionAction.setType(ActionTypes.OPEN_URL);
questionAction.setTitle("Ask a question");
questionAction.setText("Ask a question");
questionAction.setDisplayText("Ask a question");
questionAction.setValue("https://stackoverflow.com/questions/tagged/botframework");
CardAction deployAction = new CardAction();
deployAction.setType(ActionTypes.OPEN_URL);
deployAction.setTitle("Learn how to deploy");
deployAction.setText("Learn how to deploy");
deployAction.setDisplayText("Learn how to deploy");
deployAction.setValue(
"https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0"
);
card.setButtons(Arrays.asList(overviewAction, questionAction, deployAction));
Activity response = MessageFactory.attachment(card.toAttachment());
return turnContext.sendActivity(response);
}
roboti/welcome-user-bot.py
async def __send_intro_card(self, turn_context: TurnContext):
card = HeroCard(
title="Welcome to Bot Framework!",
text="Welcome to Welcome Users bot sample! This Introduction card "
"is a great way to introduce your Bot to the user and suggest "
"some things to get them started. We use this opportunity to "
"recommend a few next steps for learning more creating and deploying bots.",
images=[CardImage(url="https://aka.ms/bf-welcome-card-image")],
buttons=[
CardAction(
type=ActionTypes.open_url,
title="Get an overview",
text="Get an overview",
display_text="Get an overview",
value="https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0",
),
CardAction(
type=ActionTypes.open_url,
title="Ask a question",
text="Ask a question",
display_text="Ask a question",
value="https://stackoverflow.com/questions/tagged/botframework",
),
CardAction(
type=ActionTypes.open_url,
title="Learn how to deploy",
text="Learn how to deploy",
display_text="Learn how to deploy",
value="https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0",
),
],
)
return await turn_context.send_activity(
MessageFactory.attachment(CardFactory.hero_card(card))
)