2017-06-15 86 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版本 –