跳到主要內容

使用Azure cli 建立對話式聊天機器人(Bot Service)


前言

如果覺得使用Azure Portal建立Bot很麻煩的話, 不妨試試看用Azure Cli, 以指令的方式來建立

以下教學如何使用Azure cli 快速建立一個Bot

前置作業:

需要先在開發機上安裝Azure cli的套件
https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-windows?view=azure-cli-latest

註冊新的應用程式


每隻Bot應用都需要先在微軟的App Portal註冊, 之後會取得APP ID 以及Public key
(https://apps.dev.microsoft.com/portal/register-app)


Public Key

這組密鑰需要自己手動按下 Generate New Password 去產生, 得到之後記得要好好保存, 因為它只會在UI上顯示一次



如上圖所示, 以上步驟完成後會可以得到App ID\Public key, 當後端程式(Bot邏輯)與Azure Bot  Connector Service溝通時會需要App ID\Public key來認證身分

在雲上建立Bot Service

登陸azure


az login

建立資源群組(若使用既有群組,可以省略)


az group create --name BotResourceGroup --location "West US"

建立bot 相關資源


az bot create --resource-group "BotResourceGroup" --name "andy-test-bot" --kind "function" --description "description-of-my-bot" --appid <YOUR_APP_ID> --password <YOUR_PUBLIC_KEY>
appid, password 記得換成剛剛取得那組帳密

kind - 目前有三種資源方案function, registration, web


Web App Bot
註冊資訊到Bot Channels Registration, 並將Bot建立在Azure Web App Service上


Functions Bot
註冊資訊到Bot Channels Registration, 並將Bot建立在Azure Function Service上, 類似 Amazon Lambda Service 屬無伺服器架構

對於一些開發比較小型的Bot我會選擇部屬在這邊, 因為程式的架構簡單, 且修改很方便, 直接在雲上操作, 改完立即生效

需要注意的是, 使用指令建立的function bot預設會使用App Service Plan(S1)作為Hosting Plan(這是要錢的), 當然也可以在建立後去修改成

Bot Channels Registration
單純只註冊Bot 資訊

通常使用這種方案是

1. 當你還未決定Bot要部屬在哪裡, 可以透過此服務先註冊一個Bot, 等確定之後再去設定web hook的endpoint
2. 不想將Bot 程式部屬在Azure上時


測試


在Azure上, 可以在Resource Groups找到剛剛建立的Bot資源






修改


若想修改Bot程式(以Function Bot為例)可以打開Azure Function


進入Azure Function之後, 打開 messages, 基本上對話的邏輯都封裝在EchoDialog.csx, 可以修改裡面的MessageReceivedAsync去滿足我們的對話需求

public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var message = await argument;
if (message.Text == "reset")
{
PromptDialog.Confirm(
context,
AfterResetAsync,
"Are you sure you want to reset the count?",
"Didn't get that!",
promptStyle: PromptStyle.Auto);
}
else
{
await context.PostAsync($"I am a super cooooool bot, hahaha");
context.Wait(MessageReceivedAsync);
}

}







https://docs.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-connector-concepts?view=azure-bot-service-4.0

留言