2017年4月24日 星期一

[Chatbot] Messaging Api withASP.NET Core

 ChatBot      Microsoft Bot framework      ASP.NET Core



Introduction


We will take a look at how to implement the Messaging endpoint API with ASP.NET Core: Web Api.

Related articles



Environment

MS Bot Framework v3.0
Visual Studio 2017




Implement


Install packages




Set Microsoft Bot id/pwd

Hope you still keep the Microsoft App Id and Microsoft App Password of the bot.
If not, please go to https://dev.botframework.com/ and copy them, we will paste them to appsettings.json.

appsettings.json

{
  "MicrosoftAppId": "XXXXXXXX",
  "MicrosoftAppPassword": "YYYYYYY"
}


Register service

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
            services.AddSingleton(_ => Configuration);

            //Should register service after Microsoft.Bot.Connector.AspNetCore v3.6.0-alpha
            //See also : https://github.com/Microsoft/BotBuilder/issues/2570
            services.UseBotConnector();

            // Add framework services.
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(TrustServiceUrlAttribute));
            });
}

public void Configure(
IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
            app.UseStaticFiles();
           
            app.UseBotAuthentication(new StaticCredentialProvider(
Configuration.GetSection(MicrosoftAppCredentials.MicrosoftAppIdKey)?.Value,
         Configuration.GetSection(
MicrosoftAppCredentials.MicrosoftAppPasswordKey)?.Value));

            app.UseMvc();
}


Implement message endpoint

[Route("api/[controller]")]
public class MsgController : Controller
{
        private readonly IConfigurationRoot _configuration;
        private readonly ILogger<MsgController> _logger;

        public MsgController(IConfigurationRoot configuration, ILogger<MsgController> logger)
        {
            this._configuration = configuration;
            this._logger = logger;
        }

        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        /// <param name="activity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Hook")]
        public async Task<HttpResponseMessage> Hook([FromBody]Activity activity)
        {
            try
            {
                var appCredentials = new MicrosoftAppCredentials(this._configuration);
                var connector = new ConnectorClient(new Uri(activity.ServiceUrl), appCredentials);

                var reply = activity.CreateReply();

                if (activity.Type == ActivityTypes.Message)
                {
                    // calculate something for us to return
                    int length = (activity.Text ?? string.Empty).Length;
                    // return our reply to the user
                   reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
                }
                else
                {
                    //…
                }

                await connector.Conversations.ReplyToActivityAsync(reply);
               
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                return response;

            }
            catch (Exception ex)
            {
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(ex.Message);
                return response;
            }

        }
}



Result

The result is as same as the one in previous article.





Reference






沒有留言:

張貼留言