使用网络聊天的“反向通道”功能可以“像用户一样”向机器人发送消息。
Github 网络聊天页面上的自述文件中有一个很好的使用示例:https://github.com/Microsoft/BotFramework-WebChat#the-backchannel 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 https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/backchannel/index.html
或者在这个其他sample https://github.com/nrobert/Bot-Language-Demo/tree/master/Bot.Language.Demo我制作的(可在 Github 上找到,包括客户端网页和机器人代码):机器人的控制器如下所示:
[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);
}
}