2017-06-15 60 views
4

此代码是本网站https://www.microsoft.com/reallifecode/2017/01/10/creating-a-single-bot-service-to-support-multiple-bot-applications/#comment-148
我是新来的BOT框架和C#写了一个机器人,并希望为用户部署的n个一样的机器人上显示在网页上。但是给定的代码是Node.js。有什么办法来写相同的代码在C#asp.netC#:创建单一机器人服务,以支持多种机器人应用

var express = require('express');    
var builder = require('botbuilder');   
var port = process.env.PORT || 3978;   
var app = express(); 

// a list of client ids, with their corresponding 
// appids and passwords from the bot developer portal.  
// get this from the configuration, a remote API, etc. 
var customersBots = [ 
    { cid: 'cid1', appid: '', passwd: '' }, 
    { cid: 'cid2', appid: '', passwd: '' },  
    { cid: 'cid3', appid: '', passwd: '' },  
]; 

// expose a designated Messaging Endpoint for each of the customers 

customersBots.forEach(cust => { 

    // create a connector and bot instances for  
    // this customer using its appId and password 
    var connector = new builder.ChatConnector({ 
     appId: cust.appid, 
     appPassword: cust.passwd 
    }); 
    var bot = new builder.UniversalBot(connector); 

    // bing bot dialogs for each customer bot instance 
    bindDialogsToBot(bot, cust.cid); 

    // bind connector for each customer on it's dedicated Messaging Endpoint. 
    // bot framework entry should use the customer id as part of the  
    // endpoint url to map to the right bot instance 
    app.post(`/api/${cust.cid}/messages`, connector.listen());  
}); 

// this is where you implement all of your dialogs  
// and add them on the bot instance 
function bindDialogsToBot (bot, cid) {  
    bot.dialog('/', [  
     session => {  
      session.send(`Hello... I'm a bot for customer id: '${cid}'`);  
     }  
]);  
}  
// start listening for incoming requests  
app.listen(port,() => {  
    console.log(`listening on port ${port}`);  
});  
+0

发生了什么事?我的回答对你有帮助吗? –

+0

@BobSwager是的!非常感谢! :) –

+0

很高兴听到:) –

回答

8

简历:

  • 创建一个类,并从ICredentialProvider类继承。

  • 然后,将您的Microsoft appId和密码添加到字典中。

  • 添加您的方法来检查它是否是一个有效的应用程序;也可以获得您的应用程序的密码 。

  • 将定制认证添加到您的api/messages控制器。


首先改变你的WebApiConfig

应该是:

config.Routes.MapHttpRoute(
    name: "DefaultApi", 
    routeTemplate: "api/{controller}/{action}/{id}", 
    defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional } 
); 

然后,您的自定义验证类,从YourNameSpace开始:

namespace YourNameSpace { 
    public class MultiCredentialProvider : ICredentialProvider 
    { 
     public Dictionary<string, string> Credentials = new Dictionary<string, string> 
     { 
      { MicrosoftAppID1, MicrosoftAppPassword1}, 
      { MicrosoftAppID2, MicrosoftAppPassword2} 
     }; 

     public Task<bool> IsValidAppIdAsync(string appId) 
     { 
      return Task.FromResult(this.Credentials.ContainsKey(appId)); 
     } 

     public Task<string> GetAppPasswordAsync(string appId) 
     { 
      return Task.FromResult(this.Credentials.ContainsKey(appId) ? this.Credentials[appId] : null); 
     } 

     public Task<bool> IsAuthenticationDisabledAsync() 
     { 
      return Task.FromResult(!this.Credentials.Any()); 
     } 
    } 

之后,添加

[BotAuthentication(CredentialProviderType = typeof(MultiCredentialProvider))] 
public async Task<HttpResponseMessage> Post([FromBody]Activity activity) 
{ 
    if (activity.Type == ActivityTypes.Message) 
    { 
     ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); 
     Activity reply = activity.CreateReply("it Works!");      
     await connector.Conversations.ReplyToActivityAsync(reply); 
    } 
} 

[BotAuthentication(CredentialProviderType = typeof(MultiCredentialProvider))] 
public class MessagesController : ApiController 
{ 
    static MessagesController() 
    { 
     var builder = new ContainerBuilder(); 

     builder.Register(c => ((ClaimsIdentity)HttpContext.Current.User.Identity).GetCredentialsFromClaims()) 
      .AsSelf() 
      .InstancePerLifetimeScope(); 
     builder.Update(Conversation.Container); 
    } 

现在你应该可以处理的消息:你的控制器(API /消息)与自定义BotAuthentication,再加上你的静态构造基于身份的BotAuthentication设置更新使用权MicorosftAppCredentials容器

此代码已经过测试,适用于我的机器人。
希望它有帮助:)

+0

我使用的代码与您的代码相同,但是我的'MultiCredentialProvider'断点从来没有被打过,我总是得到错误'错误:机器人的MSA appId或密码不正确.' –

+0

你有什么版本的botframework? –

+0

我使用的是3.8.5版本 –