En este artículo se muestra cómo compilar un bot mediante el SDK de Bot Framework y, a continuación, se muestra cómo probarlo con el Bot Framework Emulator.This article shows you how to build a bot by using the Bot Framework SDK, and then shows how to test it with the Bot Framework Emulator.
La creación de un bot con Azure Bot Service y la creación local de un bot son maneras paralelas e independientes de crear un bot.Creating a bot with Azure Bot Service and creating a bot locally are independent, parallel ways to create a bot.
Para agregar las plantillas de bot Visual Studio, descargue e instale las plantillas del SDK de Bot Framework v4 para Visual Studio archivo VSIX.To add the bot templates to Visual Studio, download and install the Bot Framework v4 SDK Templates for Visual Studio VSIX file.
Nota
El paquete VSIX incluye las versiones .net Core 2,1 y .net Core 3,1 de las plantillas de C#.The VSIX package includes both .NET Core 2.1 and .NET Core 3.1 versions of the C# templates.Al crear nuevos bots en Visual Studio 2019, debe usar las plantillas de .NET Core 3.1.When creating new bots in Visual Studio 2019, you should use the .NET Core 3.1 templates.Los ejemplos de bot actuales usan plantillas de .NET Core 3.1.The current bot samples use .NET Core 3.1 templates.Encontrará los ejemplos que usan las plantillas de .NET Core 2.1 en la rama 4.7-archive del repositorio BotBuilder-Samples.You can find the samples that use .NET Core 2.1 templates in the 4.7-archive branch of the BotBuilder-Samples repository.Para obtener información sobre la implementación de bots de .NET Core 3,1 en Azure, consulte implementación de un bot en Azure.For information about deploying .NET Core 3.1 bots to Azure, see how to deploy your bot to Azure.
Las plantillas de .NET Core le ayudarán a crear rápidamente nuevos bots de IA conversacionales mediante Bot Framework v4..NET Core Templates will help you to quickly build new conversational AI bots using Bot Framework v4.A partir de mayo de 2020, estas plantillas y el código que generan requieren .NET Core 3.1.As of May 2020, these templates and the code they generate require .NET Core 3.1.
Para instalar las Bot Framework personalizadas:To install the Bot Framework templates:
Abra una ventana de la consola.Open a console window.
Puede usar este comando para determinar qué versión de la interfaz de la línea de comandos de .NET Core ha instalado.You can use this command to determine which version of the .NET Core command-line interface you have installed.
dotnet --version
Instale las tres Bot Framework de C#: las plantillas de eco, núcleo y bot vacías.Install the three Bot Framework C# templates: the echo, core, and empty bot templates.
dotnet new -i Microsoft.Bot.Framework.CSharp.EchoBot
dotnet new -i Microsoft.Bot.Framework.CSharp.CoreBot
dotnet new -i Microsoft.Bot.Framework.CSharp.EmptyBot
Compruebe que las plantillas se han instalado correctamente.Verify the templates have been installed correctly.
dotnet new --list
Nota
Los pasos de instalación anteriores instalarán las tres Bot Framework plantillas.The above installation steps will install all three Bot Framework templates.No es necesario instalar todas las plantillas y puede instalar solo las que va a usar.You don't need to install all the templates and can install just the ones you will use.En este artículo se usa la plantilla de bot de eco.This article makes use of the echo bot template.
Instale node.js versión 12.10 o posterior.Install node.js version 12.10 or later.
Una cuenta de Azure si desea implementar en Azure.An Azure account if you want to deploy to Azure.
PlantillasTemplates
Use el generador de Yeoman para configurar rápidamente un bot de IA conversacional con funcionalidades básicas de IA en Bot Framework v4.Use the Yeoman generator to quickly set up a conversational AI bot using core AI capabilities in the Bot Framework v4.Para obtener más información, vea yeoman.io.For more information, see yeoman.io.
El generador admite tres opciones de plantilla diferentes, como se muestra a continuación.The generator supports three different template options as shown below.
PlantillaTemplate
DescriptionDescription
Bot de ecoEcho Bot
Una buena plantilla si desea algo más que "Hola mundo!", pero no mucho más.A good template if you want a little more than "Hello World!", but not much more.Esta plantilla controla los aspectos básicos de enviar mensajes a un bot y hacer que el bot procese los mensajes repitiendo los mensajes al usuario.This template handles the very basics of sending messages to a bot, and having the bot process the messages by repeating them back to the user.Esta plantilla genera un bot que simplemente "repite" al usuario todo lo que el usuario dice al bot.This template produces a bot that simply "echoes" back to the user anything the user says to the bot.
Bot vacíoEmpty Bot
Una buena plantilla si está familiarizado con Bot Framework v4 y simplemente quiere un proyecto básico de esqueleto.A good template if you are familiar with Bot Framework v4, and simply want a basic skeleton project.También es una buena opción si desea tomar código de ejemplo de la documentación y pegarlo en un bot mínimo para aprender.Also a good option if you want to take sample code from the documentation and paste it into a minimal bot in order to learn.
Bot principalCore Bot
Una buena plantilla si desea crear bots avanzados, ya que usa diálogos de varios turnos y LUIS, un servicio cognitivo basado en inteligencia artificial, para implementar la comprensión del lenguaje.A good template if you want to create advanced bots, as it uses multi-turn dialogs and LUIS, an AI based cognitive service, to implement language understanding.Esta plantilla crea un bot que puede extraer lugares y fechas para reservar un vuelo.This template creates a bot that can extract places and dates to book a flight.
Instalación de YeomanInstall Yeoman
Asegúrese de que ha instalado node.js versión 12.10 o posterior.Assure that you have installed node.js version 12.10 or later.
Instale Yeoman.Install Yeoman.Asegúrese de instalar globalmente.Make sure to install globally.
npm install -g yo
Instale generator-botbuilder-java.Install generator-botbuilder-java.Asegúrese de instalar globalmente.Make sure to install globally.
npm install -g generator-botbuilder-java
Compruebe que Yeoman y generator-botbuilder-java se han instalado correctamente.Verify that Yeoman and generator-botbuilder-java have been installed correctly.
Conocimientos sobre restify y programación asincrónica en JavaScript.Knowledge of restify and asynchronous programming in JavaScript
Visual Studio Code o su IDE favorito, si desea editar el código del bot.Visual Studio Code or your favorite IDE, if you want to edit the bot code.
PlantillasTemplates
Para instalar Yeoman y el generador de Yeoman para Bot Framework v4:To install Yeoman and the Yeoman generator for Bot Framework v4:
Abra un terminal o un símbolo del sistema con privilegios elevados.Open a terminal or elevated command prompt.
Cambie al directorio para sus bots de JavaScript.Switch to the directory for your JavaScript bots.Créelo primero si aún no tiene uno.Create it first if you don't already have one.
mkdir myJsBots
cd myJsBots
Asegúrese de que tiene las versiones más recientes de npm y Yeoman.Make sure you have the latest versions of npm and Yeoman.
npm install -g npm
npm install -g yo
Instale el generador de Yeoman.Install the Yeoman generator.Yeoman es una herramienta para crear aplicaciones.Yeoman is a tool for creating applications.Para obtener más información, vea yeoman.io.For more information, see yeoman.io.
npm install -g generator-botbuilder
Nota
La instalación de las herramientas de compilación de Windows que se indican a continuación solo se necesitan si se usa Windows como sistema operativo de desarrollo.The install of Windows build tools listed below is only required if you use Windows as your development operating system.En algunas instalaciones, el paso de instalación de restify está generando un error relacionado con node-gyp .For some installations, the install step for restify is giving an error related to node-gyp.Si este es el caso, intente ejecutar este comando con permisos elevados.If this is the case you can try running this command with elevated permissions.Esta llamada también puede no cerrarse si Python ya está instalado en el sistema:This call may also hang without exiting if Python is already installed on your system:
Ejecute este comando solo si está en Windows.Only run this command if you are on Windows.
Conocimientos de programación asincrónica en PythonKnowledge of asynchronous programming in Python
Sugerencia
Algunos desarrolladores pueden resultar útiles para crear bots de Python en un entorno virtual.Some developers may find it useful to create Python bots in a virtual environment.Los pasos siguientes funcionarán independientemente de si desarrolla en un entorno virtual o en la máquina local.The steps below will work regardless if you're developing in a virtual environment or on your local machine.
PlantillasTemplates
Instale los paquetes necesarios mediante la ejecución de los pip install siguientes comandos:Install the necessary packages by running the following pip install commands:
En Visual Studio, cree un proyecto de bot mediante la plantilla Echo Bot (Bot Framework v4 - .NET Core 3.1) .In Visual Studio, create a new bot project using the Echo Bot (Bot Framework v4 - .NET Core 3.1) template.Elija Bots de IA en los tipos de proyecto para mostrar solo plantillas de bot.Choose AI Bots from the project types to show only bot templates.
Gracias a la plantilla, el proyecto contiene todo el código necesario para crear el bot en esta guía de inicio rápido.Thanks to the template, your project contains all the code that's necessary to create the bot in this quickstart.No es necesario ningún código adicional para probar el bot.You don't need any additional code to test your bot.
Nota
Si crea un bot principal, necesitará un modelo de lenguaje LUIS.If you create a Core bot, you'll need a LUIS language model.Puede crear un modelo de lenguaje en luis.ai.You can create a language model at luis.ai.Después de crear el modelo, actualice el archivo de configuración.After creating the model, update the configuration file.
En Visual Studio Code, abra una nueva ventana de terminal.In Visual Studio Code, open a new terminal window.
Vaya al directorio en el que desea crear el proyecto de bot.Navigate to the directory in which you want to create your bot project.
Cree un nuevo proyecto de bot de eco con el siguiente comando.Create a new echo bot project using the following command.Reemplace <your-bot-name> por el nombre que se usará para el proyecto de bot.Replace <your-bot-name> with the name to use for your bot project.
dotnet new echobot -n <your-bot-name>
Abra una nueva ventana de terminal.Open a new terminal window.
Vaya al directorio en el que desea crear el proyecto de bot.Navigate to the directory in which you want to create your bot project.
Cree un nuevo proyecto de bot de eco con el siguiente comando.Create a new echo bot project using the following command.Reemplace <your-bot-name> por el nombre que se usará para el proyecto de bot.Replace <your-bot-name> with the name to use for your bot project.
Ejecute el siguiente comando para crear un bot de eco a partir de plantillas.Run the following command to create an echo bot from templates.El comando usa opciones predeterminadas para sus parámetros.The command uses default options for its parameters.
yo botbuilder-java -T "echo"
Yeoman le solicitará alguna información con la que se va a crear el bot.Yeoman prompts you for some information with which to create your bot.En este tutorial, use los valores predeterminados.For this tutorial, use the default values.
? What's the name of your bot? (echo)
? What's the fully qualified package name of your bot? (com.mycompany.echo)
? Which template would you like to start with? (Use arrow keys) Select "Echo Bot"
? Looking good. Shall I go ahead and create your new bot? (Y/n) Enter "y"
El generador admite una serie de opciones de línea de comandos que se pueden usar para cambiar las opciones predeterminadas del generador o para preinserr un símbolo del sistema.The generator supports a number of command line options that can be used to change the generator's default options or to pre-seed a prompt.
Opción de línea de comandosCommand line Option
DescriptionDescription
--help, -h--help, -h
Lista de texto de ayuda para todas las opciones de línea de comandos admitidasList help text for all supported command-line options
--botName, -N--botName, -N
El nombre dado al proyecto de botThe name given to the bot project
--packageName, -P--packageName, -P
El nombre del paquete de Java que se usará para el botThe Java package name to use for the bot
El generador no solicitará confirmación antes de crear un bot.The generator will not prompt for confirmation before creating a new bot.Las opciones de requisitos que no se pasen en la línea de comandos usarán un valor predeterminado razonable.Any requirement options not passed on the command line will use a reasonable default value.Esta opción está pensada para habilitar la generación automatizada de bots con fines de prueba.This option is intended to enable automated bot generation for testing purposes.
Gracias a la plantilla, el proyecto contiene todo el código necesario para crear el bot en esta guía de inicio rápido.Thanks to the template, your project contains all the code that's necessary to create the bot in this quickstart.No es necesario ningún código adicional para probar el bot.You don't need any additional code to test your bot.
Nota
Si crea un bot Core, necesitará un modelo de lenguaje LUISIf you create a Core bot, you'll need a LUIS language model.Puede crear un modelo de lenguaje en luis.ai.You can create a language model at luis.ai.Después de crear el modelo, actualice el archivo de configuración.After creating the model, update the configuration file.
Use el generador para crear un bot de eco.Use the generator to create an echo bot.
yo botbuilder
Yeoman le solicitará alguna información con la que se va a crear el bot.Yeoman prompts you for some information with which to create your bot.En este tutorial, use los valores predeterminados.For this tutorial, use the default values.
? What's the name of your bot? my-chat-bot
? What will your bot do? Demonstrate the core capabilities of the Microsoft Bot Framework
? What programming language do you want to use? JavaScript
? Which template would you like to start with? Echo Bot - https://aka.ms/bot-template-echo
? Looking good. Shall I go ahead and create your new bot? Yes
Gracias a la plantilla, el proyecto contiene todo el código necesario para crear el bot en esta guía de inicio rápido.Thanks to the template, your project contains all the code that's necessary to create the bot in this quickstart.No es necesario ningún código adicional para probar el bot.You don't need any additional code to test your bot.
Nota
Si crea un bot Core, necesitará un modelo de lenguaje LUISIf you create a Core bot, you'll need a LUIS language model.Puede crear un modelo de lenguaje en luis.ai.You can create a language model at luis.ai.Después de crear el modelo, actualice el archivo de configuración.After creating the model, update the configuration file.
Para crear el bot, vaya al directorio en el que desea crear el bot.To create your bot, navigate to the directory you want to create your bot.Luego, ejecute el siguiente comando:Then run the following command:
Este comando copia todos los archivos necesarios de GitHub para crear un bot de eco basado en la plantilla de eco dePython .This command copies all needed files from GitHub to create an Echo Bot based on the Python echo template.Se le pedirá el nombre del bot y una descripción.You will be prompted for the name of the bot and a description.Escriba los siguientes valores:Enter the following values:
bot_name:echo-botbot_name: echo-bot
bot_description: bot que resuena la respuesta del usuario.bot_description: A bot that echoes back user response.
Ejecute el proyecto sin depurar.Run the project without debugging.
Esto compilará la aplicación, la implementará en localhost e iniciará el explorador web para mostrar la página default.htm de la aplicación.This will build the application, deploy it to localhost, and launch the web browser to display the application's default.htm page.En este momento, el bot se ejecuta de forma local en el puerto 3978.At this point, your bot is running locally on port 3978.
Para ejecutar el bot desde VS Code:To run your bot from VS Code:
Abra la carpeta del proyecto de bot.Open your bot project folder.
Vaya a Ejecutar y, a continuación, seleccione Ejecutar sin depurar.Go to Run, and then select Run Without Debugging.
Seleccione el .Net Core de trabajo.Select the .Net Core environment.
Si este comando ha actualizado la configuración de inicio, guarde los cambios y vuelva a ejecutar el comando.If this command updated your launch settings, save the changes and rerun the command.
Esto compilará la aplicación, la implementará en localhost e iniciará el explorador web para mostrar la página default.htm de la aplicación.This will build the application, deploy it to localhost, and launch the web browser to display the application's default.htm page.En este momento, el bot se ejecuta de forma local en el puerto 3978.At this point, your bot is running locally on port 3978.
Para ejecutar el bot localmente en un símbolo del sistema o terminal:To run your bot locally in a command prompt or terminal:
Cambie los directorios a la carpeta del proyecto para el bot.Change directories to the project folder for your bot.
Use dotnet run para iniciar el bot.Use dotnet run to start the bot.
dotnet run
Esto compilará la aplicación e implementará en localhost.This will build the application and deploy it to localhost.La página web predeterminada de la aplicación no se mostrará, pero en este momento, el bot se ejecuta localmente en el puerto 3978.The application's default web page will not display, but at this point, your bot is running locally on port 3978.
Desde un terminal, vaya al directorio donde guardó el bot y, a continuación, ejecute los comandos que se enumeran a continuación.From a terminal, navigate to the directory where you saved your bot, then execute the commands listed below.
Compile el proyecto de Maven y lo empaqueta en un archivo .jar (archivo).Build the Maven project and packages it into a .jar file (archive).
mvn package
Ejecute el bot localmente.Run the bot locally.Reemplace archive-name por el nombre real del comando anterior.Replace the archive-name with the actual name from the previous command.
java -jar .\target\<archive-name>.jar
Ya está listo para iniciar la Emulator.You are now ready to start the Emulator.
En un terminal o símbolo del sistema, mueva los directorios al que creó para el bot e inícielo con npm start.In a terminal or command prompt change directories to the one created for your bot, and start it with npm start.
cd my-chat-bot
npm start
En este momento, el bot se ejecuta de forma local en el puerto 3978.At this point, your bot is running locally on port 3978.
Desde un terminal, vaya a la carpeta echo-bot donde guardó el bot.From a terminal navigate to the echo-bot folder where you saved your bot.Ejecute el siguiente comando para instalar los paquetes necesarios para ejecutar el bot.Run the following command to install any required packages to run your bot.
pip install -r requirements.txt
Una vez instalados los paquetes, ejecute lo siguiente para iniciar el bot:Once the packages are installed run the following to to start your bot:
python app.py
Sabrá que el bot está listo para probarlo cuando vea la última línea que se muestra en la siguiente captura de pantalla:You will know your bot is ready to test when you see the last line shown in the screenshot below:
Copie los últimos cuatro dígitos de la dirección en la última línea (normalmente 3978), ya que los utilizará en el paso siguiente.Copy the last for digits in the address on the last line (usually 3978) since you will be using them in the next step.Ya está listo para iniciar la Emulator.You are now ready to start the Emulator.
Inicio del emulador y conexión del botStart the Emulator and connect your bot
Inicie Bot Framework Emulator.Start the Bot Framework Emulator.
Seleccione Abrir bot en la Emulator de bienvenida de la aplicación.Select Open Bot on the Emulator's Welcome tab.
Escriba la dirección URL del bot, que es la dirección URL del puerto local, y se agrega a la ruta /api/messages de acceso, normalmente http://localhost:3978/api/messages .Enter your bot's URL, which is the URL of the local port, with /api/messages added to the path, typically http://localhost:3978/api/messages.
A continuación, seleccione Conectar.Then select Connect.
Envíe un mensaje al bot y el bot responderá de nuevo.Send a message to your bot, and the bot will respond back.
Consulte Depuración de un bot para obtener información sobre cómo depurar Visual Studio o Visual Studio Code y el Bot Framework Emulator.See Debug a bot for how to debug using Visual Studio or Visual Studio Code and the Bot Framework Emulator.