C#:创建单个Bot服务以支持多个Bot应用程序 [英] C# : Creating a Single Bot Service to Support Multiple Bot Applications
问题描述
This code was on this website https://www.microsoft.com/reallifecode/2017/01/10/creating-a-single-bot-service-to-support-multiple-bot-applications/#comment-148
I am new to bot framework and have written a bot in C# and want to deploy the same bot for n number of users as shown on the webpage. But the given code is in Node.js
. Is there any way to write the same code in C# asp.net
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}`);
});
推荐答案
恢复:
-
创建一个类,并从ICredentialProvider类继承.
Create a class and inherit from ICredentialProvider class.
然后,将您的Microsoft appId和密码添加到字典中.
Then, add your Microsoft appId and password into a Dictionary.
添加您的方法以检查其是否为有效应用;也获得密码 您的应用程序.
Add your method to check if it is a valid app; also get password for your application.
向您的api/messages
控制器添加自定义身份验证.
Add custom authentication to your api/messages
controller.
首先更改您的WebApiConfig
:
应该是:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
然后是您的自定义身份验证类,从YourNameSpace开始:
Then, your custom authentication class, starting from 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
添加控制器(api/messages),并添加静态构造函数以根据BotAuthentication设置的身份将容器更新为使用正确的MicorosftAppCredentials
:
After that, add your controller (api/messages) with your custom BotAuthentication
, plus your static constructor to update the container to use the right MicorosftAppCredentials
based on identity set by BotAuthentication:
[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);
}
您现在可以通过以下方式处理消息:
You can handle now messages by :
[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);
}
}
此代码已经过测试,可用于我的机器人.
希望对您有所帮助:)
This code is tested and working for my bots.
Hope it helps :)
这篇关于C#:创建单个Bot服务以支持多个Bot应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!