我正在使用 Direct Line 3.0 和 Microsoft Bot Framework,并要求网页将一些表单字段发送到机器人,就像用户发送它们一样。例如,当用户按下“提交”时,电子邮件、电话等字段将被发送到机器人,就像用户这样发送它们:电子邮件、电话等。 这是因为机器人根据值来重定向用户。该机器人采用 C# 语言编写,托管在 Azure 上。提交信息的逻辑应使用 JavaScript。
机器人的启动方式如下:
<div id="chat" style="background-color:white;
width:250px;height:600px;"><div id="bot" />
<script src="https://cdn.botframework.com/botframework-
webchat/latest/botchat.js"></script></div></div>
并通过 DirectLine 脚本:
<script>
const botConnection = new BotChat.DirectLine({
secret: 'secret',
});
BotChat.App({
user: { id: 'You' },
bot: { id: 'myId' },
resize: 'detect',
botConnection: botConnection
}, document.getElementById("bot"));
</script>
我所需要的只是发送一个字符串,就像用户发送它一样。我似乎无法通过 HTML 操作来做到这一点。
感谢任何人为我指明正确的方向!
最佳答案
使用网络聊天的“反向 channel ”功能可以“像用户一样”向机器人发送消息。
Github 网络聊天页面上的自述文件中有一个很好的使用示例:https://github.com/Microsoft/BotFramework-WebChat#the-backchannel .
您必须使用之前创建的 botConnection
来发送如下所示的事件:
botConnection.postActivity({
from: { id: 'me' },
name: 'buttonClicked',
type: 'event',
value: ''
});
然后在您的机器人代码中捕获此内容,但检查事件类型,在本例中为 Event
。
您可以看看他们如何通过单击提供的示例中的按钮来抛出此 postActivity:此处的示例:https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/backchannel/index.html
或者在这个其他sample我制作的(可在 Github 上找到,包括客户端网页和机器人代码):机器人的 Controller 如下所示:
[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
// Process each activity
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
}
// Webchat: getting an "event" activity for our js code
else if (activity.Type == ActivityTypes.Event && activity.ChannelId == "webchat")
{
var receivedEvent = activity.AsEventActivity();
if ("localeSelectionEvent".Equals(receivedEvent.Name, StringComparison.InvariantCultureIgnoreCase))
{
await EchoLocaleAsync(activity, activity.Locale);
}
}
// Sample for Skype: locale is provided in ContactRelationUpdate event
else if (activity.Type == ActivityTypes.ContactRelationUpdate && activity.ChannelId == "skype")
{
await EchoLocaleAsync(activity, activity.Entities[0].Properties["locale"].ToString());
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
private async Task EchoLocaleAsync(Activity activity, string inputLocale)
{
Activity reply = activity.CreateReply($"User locale is {inputLocale}, you should use this language for further treatment");
var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
await connector.Conversations.SendToConversationAsync(reply);
}
}
关于javascript - 是否可以像来自用户一样向 Bot Framework 发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49008420/