是否可以从控制台应用程序加入机器人对话(使用 Microsoft 机器人框架)?我的客户正在尝试测试机器人,但到目前为止必须有人加入对话才能做到这一点。
Bot Framework 团队不提供这种性质的应用程序。但是,只要遵守 Azure 服务条款,您就可以自由构建应用程序来执行此操作。 Direct Line API 是一个很好的起点。
是的,Microsoft Bot Framework 允许您通过 Direct Line API 与机器人交互,从而无需用户界面。使用此 API,您可以从机器人发送和接收消息。
下面的这些代码片段展示了如何发起对话、从用户向机器人发送消息,以及随后接收机器人的响应。
using Microsoft.Bot.Connector.DirectLine;
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string directLineSecret = "YOUR_DIRECT_LINE_SECRET";
string botId = "YOUR_BOT_ID";
var directLineClient = new DirectLineClient(directLineSecret);
var conversation = await directLineClient.Conversations.StartConversationAsync();
Console.WriteLine("Bot: Hello! Type 'exit' to end the conversation.");
while (true)
{
Console.Write("You: ");
string userMessage = Console.ReadLine();
if (userMessage.ToLower() == "exit")
{
break;
}
await SendMessageToBot(directLineClient, conversation.ConversationId, userMessage);
var botResponse = await ReceiveMessageFromBot(directLineClient, conversation.ConversationId);
Console.WriteLine($"Bot: {botResponse?.Text}");
}
}
static async Task SendMessageToBot(DirectLineClient client, string conversationId, string messageText)
{
var userMessage = new Activity
{
Type = ActivityTypes.Message,
Text = messageText,
From = new ChannelAccount("User"),
};
await client.Conversations.PostActivityAsync(conversationId, userMessage);
}
static async Task<Activity> ReceiveMessageFromBot(DirectLineClient client, string conversationId)
{
var response = await client.Conversations.GetActivitiesAsync(conversationId);
var activities = response.Activities;
var botResponse = activities.FirstOrDefault(a => a.From.Id == botId && a.Type == ActivityTypes.Message);
return botResponse;
}
}
您需要按照以下步骤才能处理此问题:
Direct Line Secret 和 Bot ID: 您应该将 directLineSecret 和 botId 变量替换为您的机器人的 Direct Line Secret 和 Bot ID。
所需的库:为了使代码正常运行,您需要将 Microsoft.Bot.Connector.DirectLine 库添加到您的项目中。您可以通过 NuGet Package Manager 或 .NET CLI 添加此库。
Direct Line API: 代码使用 Direct Line API 与机器人进行通信。因此,请确保您的 Direct Line API 可以运行且可访问。
执行上述步骤并进行必要的更改后,您可以使用此代码示例通过 C# 控制台应用程序与您的机器人进行交互。