├── .env ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README-localized ├── README-es-es.md ├── README-fr-fr.md ├── README-ja-jp.md ├── README-pt-br.md ├── README-ru-ru.md └── README-zh-cn.md ├── README.md ├── SearchBotLUIS.json ├── package.json ├── readme-images ├── BotPreview.png └── PublishLUISApp.png ├── src ├── etc │ └── ssl │ │ ├── server.crt │ │ ├── server.csr │ │ ├── server.key │ │ └── server.orig.key ├── public │ └── code.html └── server │ ├── dialogs │ ├── idialog.js │ ├── idialog.js.map │ ├── idialog.ts │ ├── searchDialog.js │ ├── searchDialog.js.map │ └── searchDialog.ts │ ├── helpers │ ├── AuthHelper.js │ ├── AuthHelper.js.map │ ├── authHelper.ts │ ├── httpHelper.js │ ├── httpHelper.js.map │ ├── httpHelper.ts │ ├── sentimentHelper.js │ ├── sentimentHelper.js.map │ └── sentimentHelper.ts │ ├── server.js │ ├── server.js.map │ └── server.ts └── tsconfig.json /.env: -------------------------------------------------------------------------------- 1 | PORT=3980 2 | MICROSOFT_APP_ID= 3 | MICROSOFT_APP_PASSWORD= 4 | KBID= 5 | LUIS_MODEL_URL=ENTER_YOUR_LUIS_MODEL_URL 6 | CLIENT_ID=ENTER_YOUR_CLIENT_ID 7 | CLIENT_SECRET=ENTER_YOUR_CLIENT_SECRET 8 | COG_SUB_KEY=ENTER_YOUR_COG_SERVICE_SUBSCRIPTION_KEY -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (http://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | 58 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribute to this code sample 2 | 3 | Thank you for your interest in our sample 4 | 5 | * [Ways to contribute](#ways-to-contribute) 6 | * [To contribute using Git](#To-contribute-using-Git) 7 | * [Contribute code](#Contribute-code) 8 | * [FAQ](#faq) 9 | * [More resources](#more-resources) 10 | 11 | ## Ways to contribute 12 | 13 | Here are some ways you can contribute to this sample: 14 | 15 | * Add better comments to the sample code. 16 | * Fix issues opened in GitHub against this sample. 17 | * Add a new feature to the sample. 18 | 19 | We want your contributions. Help the developer community by improving this sample. 20 | Contributions can include Bug fixes, new features, and better code documentation. 21 | Submit code comment contributions where you want a better explanation of what's going on. 22 | See a good example of [code commenting](https://github.com/OfficeDev/O365-Android-Microsoft-Graph-Connect/blob/master/app/src/main/java/com/microsoft/office365/connectmicrosoftgraph/AuthenticationManager.java). 23 | 24 | Another great way to improve the sample in this repository is to take on some of the open issues filed against the repository. You may have a solution to an bug in the sample code that hasn't been addressed. Fix the issue and then create a pull request following our [Contribute code](#Contribute-code) guidance. 25 | 26 | If you want to add a new feature to the sample, be sure you have the agreement of the repository owner before writing the code. Start by opening an issue in the repository. Use the new issue to propose the feature. The repository owner will respond and will usually ask you for more information. When the owner agrees to take the new feature, code it and submit a pull request. 27 | 28 | ## To contribute using Git 29 | For most contributions, you'll be asked to sign a Contribution License Agreement (CLA). For those contributions that need it, The Office 365 organization on GitHub will send a link to the CLA that we want you to sign via email. 30 | By signing the CLA, you acknowledge the rights of the GitHub community to use any code that you submit. The intellectual property represented by the code contribution is licensed for use by Microsoft open source projects. 31 | 32 | If Office 365 emails an CLA to you, you need to sign it before you can contribute large submissions to a project. You only need to complete and submit it once. 33 | Read the CLA carefully. You may need to have your employer sign it. 34 | 35 | Signing the CLA does not grant you rights to commit to the main repository, but it does mean that the Office Developer and Office Developer Content Publishing teams will be able to review and approve your contributions. You will be credited for your submissions. 36 | 37 | Pull requests are typically reviewed within 10 business days. 38 | 39 | ## Contribute code 40 | 41 | To make the contribution process as seamless as possible, follow these steps. 42 | 43 | ### To contribute code 44 | 45 | 1. Create a new branch. 46 | 2. Add new code or modify existing code. 47 | 3. Submit a pull request to the main repository. 48 | 4. Await notification of acceptance and merge. 49 | 5. Delete the branch. 50 | 51 | 52 | ### To create a new branch 53 | 54 | 1. Open Git Bash. 55 | 2. At the Git Bash command prompt, type `git pull upstream master:`. This creates a new branch locally that is copied from the latest OfficeDev master branch. 56 | 3. At the Git Bash command prompt, type `git push origin `. This alerts GitHub to the new branch. You should now see the new branch in your fork of the repository on GitHub. 57 | 4. At the Git Bash command prompt, type `git checkout ` to switch to your new branch. 58 | 59 | ### Add new code or modify existing code 60 | 61 | Navigate to the repository on your computer. On a Windows PC, the repository files are in `C:\Users\\`. 62 | 63 | Use the IDE of your choice to modify and build the sample. Once you have completed your change, commented your code, and run your unit tests, check the code 64 | into the remote branch on GitHub. Be sure to check in any unit tests you've written. 65 | 66 | #### Code contribution checklist 67 | Be sure to satisfy all of the requirements in the following list before submitting a pull request: 68 | - Follow the code style found in the cloned repository code. Our Android code follows the style conventions found in the [Code Style for Contributors](https://source.android.com/source/code-style.html) guide. 69 | - Code must be unit tested. Include the unit tests in the pull request. 70 | - Test the sample UI thoroughly to be sure nothing has been broken by your change. 71 | - Keep the size of your code change reasonable. if the repository owner cannot review your code change in 4 hours or less, your pull request may not be reviewed and approved quickly. 72 | - Avoid unnecessary changes to cloned or forked code. The reviewer will use a tool to find the differences between your code and the original code. Whitespace changes are called out along with your code. Be sure your changes will help improve the content. 73 | 74 | ### Push your code to the remote GitHub branch 75 | The files in `C:\Users\\` are a working copy of the new branch that you created in your local repository. Changing anything in this folder doesn't affect the local repository until you commit a change. To commit a change to the local repository, type the following commands in GitBash: 76 | 77 | git add . 78 | git commit -v -a -m "" 79 | 80 | The `add` command adds your changes to a staging area in preparation for committing them to the repository. The period after the `add` command specifies that you want to stage all of the files that you added or modified, checking subfolders recursively. (If you don't want to commit all of the changes, you can add specific files. You can also undo a commit. For help, type `git add -help` or `git status`.) 81 | 82 | The `commit` command applies the staged changes to the repository. The switch `-m` means you are providing the commit comment in the command line. The -v and -a switches can be omitted. The -v switch is for verbose output from the command, and -a does what you already did with the add command. 83 | 84 | You can commit multiple times while you are doing your work, or you can commit once when you're done. 85 | 86 | ### Submit a pull request to the master repository 87 | 88 | When you're finished with your work and are ready to have it merged into the master repository, follow these steps. 89 | 90 | #### To submit a pull request to the master repository 91 | 92 | 1. In the Git Bash command prompt, type `git push origin `. In your local repository, `origin` refers to your GitHub repository that you cloned the local repository from. This command pushes the current state of your new branch, including all commits made in the previous steps, to your GitHub fork. 93 | 2. On the GitHub site, navigate in your fork to the new branch. 94 | 3. Choose the **Pull Request** button at the top of the page. 95 | 4. Verify the Base branch is `OfficeDev/@master` and the Head branch is `/@`. 96 | 5. Choose the **Update Commit Range** button. 97 | 6. Add a title to your pull request, and describe all the changes you're making. 98 | 7. Submit the pull request. 99 | 100 | One of the site administrators will process your pull request. Your pull request will surface on the `OfficeDev/` site under Issues. When the pull request is accepted, the issue will be resolved. 101 | 102 | ### Repository owner code review 103 | The owner of the repository will review your pull request to be sure that all requirements are met. If the reviewer 104 | finds any issues, she will communicate with you and ask you to address them and then submit a new pull request. If your pull 105 | request is accepted, then the repository owner will tell you that your pull request is to be merged. 106 | 107 | ### Create a new branch after merge 108 | 109 | After a branch is successfully merged (that is, your pull request is accepted), don't continue working in that local branch. This can lead to merge conflicts if you submit another pull request. To do another update, create a new local branch from the successfully merged upstream branch, and then delete your initial local branch. 110 | 111 | For example, if your local branch X was successfully merged into the OfficeDev/O365-Android-Microsoft-Graph-Connect master branch and you want to make additional updates to the code that was merged. Create a new local branch, X2, from the OfficeDev/O365-Android-Microsoft-Graph-Connect branch. To do this, open GitBash and execute the following commands: 112 | 113 | cd microsoft-graph-docs 114 | git pull upstream master:X2 115 | git push origin X2 116 | 117 | You now have local copies (in a new local branch) of the work that you submitted in branch X. The X2 branch also contains all the work other developers have merged, so if your work depends on others' work (for example, a base class), it is available in the new branch. You can verify that your previous work (and others' work) is in the branch by checking out the new branch... 118 | 119 | git checkout X2 120 | 121 | ...and verifying the code. (The `checkout` command updates the files in `C:\Users\\O365-Android-Microsoft-Graph-Connect` to the current state of the X2 branch.) Once you check out the new branch, you can make updates to the code and commit them as usual. However, to avoid working in the merged branch (X) by mistake, it's best to delete it (see the following **Delete a branch** section). 122 | 123 | ### Delete a branch 124 | 125 | Once your changes are successfully merged into the main repository, delete the branch you used because you no longer need it. Any additional work should be done in a new branch. 126 | 127 | #### To delete a branch 128 | 129 | 1. In the Git Bash command prompt, type `git checkout master`. This ensures that you aren't in the branch to be deleted (which isn't allowed). 130 | 2. Next, at the command prompt, type `git branch -d `. This deletes the branch on your computer only if it has been successfully merged to the upstream repository. (You can override this behavior with the `–D` flag, but first be sure you want to do this.) 131 | 3. Finally, type `git push origin :` at the command prompt (a space before the colon and no space after it). This will delete the branch on your github fork. 132 | 133 | Congratulations, you have successfully contributed to the sample app! 134 | 135 | 136 | ## FAQ 137 | 138 | ### How do I get a GitHub account? 139 | 140 | Fill out the form at [Join GitHub](https://github.com/join) to open a free GitHub account. 141 | 142 | ### Where do I get a Contributor's License Agreement? 143 | 144 | You will automatically be sent a notice that you need to sign the Contributor's License Agreement (CLA) if your pull request requires one. 145 | 146 | As a community member, **you must sign the CLA before you can contribute large submissions to this project**. You only need complete and submit the CLA document once. Carefully review the document. You may be required to have your employer sign the document. 147 | 148 | ### What happens with my contributions? 149 | 150 | When you submit your changes, via a pull request, our team will be notified and will review your pull request. You will receive notifications about your pull request from GitHub; you may also be notified by someone from our team if we need more information. If your pull request is approved, we'll update the documentation on GitHub and on MSDN. We reserve the right to edit your submission for legal, style, clarity, or other issues. 151 | 152 | ### Who approves pull requests? 153 | 154 | The owner of the sample repository approves pull requests. 155 | 156 | ### How soon will I get a response about my change request? 157 | 158 | Pull requests are typically reviewed within 10 business days. 159 | 160 | 161 | ## More resources 162 | 163 | * For more information about Markdown, go to the Git creator's site [Daring Fireball]. 164 | * For more information about using Git and GitHub, first check out the [GitHub Help section] [GitHub Help] and, if necessary, contact the site administrators. 165 | 166 | [GitHub Home]: http://github.com 167 | [GitHub Help]: http://help.github.com/ 168 | [Set Up Git]: http://help.github.com/win-set-up-git/ 169 | [Markdown Home]: http://daringfireball.net/projects/markdown/ 170 | [Markdown Pad]: http://markdownpad.com/ 171 | [OfficeDev/microsoft-graph-docs issues]: https://github.com/OfficeDev/microsoft-graph-docs/issues 172 | [Daring Fireball]: http://daringfireball.net/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README-localized/README-es-es.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - nodejs 7 | - typescript 8 | description: "Usar Microsoft Graph, Microsoft Cognitive Services y el Microsoft Bot Framework para hacer análisis de sentimientos en una aplicación web de NodeJS" 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft Bot Framework 14 | createdDate: 9/13/2017 10:47:10 AM 15 | --- 16 | # Bot de análisis de Microsoft Graph Sentiment 17 | 18 | ## Tabla de contenido 19 | 20 | * [Introducción](#introduction) 21 | * [Requisitos previos](#prerequisites) 22 | * [Obtener una clave para la API de análisis de texto](#get-a-key-for-the-text-analytics-api) 23 | * [Publicar el modelo LUIS](#publish-the-luis-model) 24 | * [Registrar la aplicación web](#register-the-web-application) 25 | * [Compile el ejemplo](#build-the-sample) 26 | * [Ejecutar el ejemplo](#run-the-sample) 27 | * [Preguntas y comentarios](#questions-and-comments) 28 | * [Colaboradores](#contributing) 29 | * [Recursos adicionales](#additional-resources) 30 | 31 | ## Introducción 32 | 33 | Este ejemplo muestra cómo construir unMicrosoft Bot Framework bot que se conecta a Microsoft Graph, busca a través de los mensajes de correo electrónico, y realiza un análisis de los sentimientos en esos mensajes utilizando el[Servicio cognitivo de Microsoft Text Analytics](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quick-start). Se aprovecha el[Servicio Inteligente de Comprensión del Lenguaje](https://www.luis.ai)para ayudar a tu robot a entender las preguntas que le envías. 34 | 35 | ## Requisitos previos 36 | 37 | Para usar la muestra de Microsoft Graph Connect para Node.js, necesitas lo siguiente: 38 | 39 | * [Node.js](https://nodejs.org/) 40 | * [TypeScript](http://www.typescriptlang.org/) 41 | * El[Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) 42 | * Ya sea una [cuenta de Microsoft](https://www.outlook.com/) o una [cuenta de trabajo o educativa](http://dev.office.com/devprogram) 43 | * Una [cuenta de Microsoft Azure](https://azure.microsoft.com/en-us/free/) 44 | * Una [cuenta Language Understanding Intelligent Service](https://www.luis.ai/) 45 | 46 | Además de estos prerrequisitos, tendrá que[obtener una clave de suscripción para la API de análisis de texto](#get-a-key-for-the-text-analytics-api)), [publicar un modelo de LUIS](),y [registrar una aplicación de cliente web](#register-the-web-application). En las tres secciones siguientes se describe cómo obtener estos recursos adicionales. 47 | 48 | ## Obtener una clave para la API de análisis de texto 49 | 50 | 1. Inicie sesión en[Azure Portal](https://portal.azure.com). 51 | 52 | 2. Elija**Más servicios**en la parte inferior de la columna izquierda de la página. 53 | 54 | 3. En el**filtro**, en la parte superior de la columna **más servicios**, escriba **servicios cognitivos**. 55 | 56 | 4. Elija la opción **servicios cognitivos** cuando aparezca. 57 | 58 | 5. Elija el botón **Agregar**en la parte superior de la página. 59 | 60 | 6. Elija la opción**Text Analytics API (vista previa)**en el panel derecho. 61 | 62 | 7. Elija el botón**Crear**en la parte inferior del panel derecho. 63 | 64 | 8. Escriba un nombre para su suscripción y seleccione un plan. Puede seleccionar el nivel gratuito para 5 000 transacciones al mes. 65 | 66 | 9. Lea y confirme que ha entendido el aviso cerca de la parte inferior del panel, y luego seleccione el botón**Crear**en la parte inferior. 67 | 68 | 10. Una vez que haya creado su suscripción, navegue hasta ella y seleccione **Tecla** en la sección** Administración de recursos** del panel central. 69 | 70 | 11. Copia el valor de la primera tecla ("Tecla 1"). Usará este valor en el [construir la sección](#build-the-sample) de ejemplo. 71 | 72 | 73 | ## Publicar el modelo LUIS 74 | 75 | 1. Navegue a la página principal del [Language Understanding Intelligent Service](https://www.luis.ai) (LUIS). 76 | 77 | 2. Cree una cuenta LUIS si no tienes ya una. Navegará automáticamente hasta el panel de control de tu cuenta. 78 | 79 | 3. Elija **Mis aplicaciones**en la esquina superior izquierda de la página del tablero. 80 | 81 | 4. Elija **Importar aplicación** 82 | 83 | 5. En la ventana emergente, busque el[SearchBotLUIS. JSON](./SearchBotLUIS.json) en el directorio raíz de este repositorio. 84 | 85 | 6. Elija el botón **Importar**. Navegará automáticamente a la página del panel de control de tu nueva aplicación. 86 | 87 | 7. Elija **publicar aplicación** en el menú de la izquierda. 88 | 89 | 8. Seleccione la opción predeterminada **BootstrapKey** como el valor de **Clave del punto final**y luego seleccione el botón **publicar**. 90 | ![Captura de pantalla de Microsoft Graph Sentiment Bot](./readme-images/PublishLUISApp.png) 91 | 92 | 9. Copie el valor de la dirección** URL del extremo **. Usará este valor en el [construir la sección](#build-the-sample) de ejemplo. 93 | 94 | 10. Seleccione**entrenar y probar** en el menú de la izquierda para ir a una página donde se pueden hacer consultas de prueba contra su modelo publicado. Tipo**búsqueda de Office 365 para el gráfico**en el panel de expresión de prueba para verificar que su nueva aplicación está encontrando una intención para esta consulta. 95 | 96 | ## Registrar la aplicación web 97 | 98 | 1. Inicie sesión en el [Portal de registro de aplicaciones el Azure](https://go.microsoft.com/fwlink/?linkid=2083908) usando su cuenta personal, de trabajo o de la escuela. 99 | 100 | 2. Seleccione **Nuevo registro**. 101 | 102 | 3. Introduzca un nombre para la aplicación. Para **Tipos de cuenta admitidos**,seleccione**Cuentas en cualquier directorio de la organización y cuentas personales de Microsoft (por ejemplo, Skype, Xbox, Outlook.com)**. 103 | 104 | 4. Escriba *https://localhost:3980/botauth/aadv2/callback* como URI de redireccionamiento (Web). 105 | 106 | 5. Elija **Registrar**. 107 | 108 | Se muestra la página de resumen de la aplicación, con una lista de las propiedades de tu aplicación. 109 | 110 | 6. Copie la identificación de la solicitud (cliente) de la página de resumen. Este es el identificador único de su aplicación. 111 | 112 | 7. Diríjase a**certificados y secretos**página en **administrar**. Elija **nuevo cliente secreto**, dele una descripción y una fecha de caducidad, y luego seleccione **agregar**. 113 | 114 | 8. Copie y guarde el valor del nuevo secreto del cliente. Esta es la única vez que podrá ver el cliente secreto. 115 | 116 | Usará el ID de la aplicación y el cliente secreto para configurar la aplicación de muestra en la siguiente sección. 117 | 118 | ## Compile el ejemplo 119 | 120 | 1. Descargue o clone este repo. 121 | 122 | 2. Usando tu IDE favorito, abre el archivo**.env** en el directorio raíz del repo. 123 | 124 | 3. Reemplace el valor **ENTER\_YOUR\_COG\_SERVICE\_SUBSCRIPTION\_KEY** valor del marcador de posición con la tecla de la API de análisis de texto que has copiado en el[obtener una tecla para la sección de la API de análisis de texto](#get-a-key-for-the-text-analytics-api). 125 | 126 | 4. Reemplace el **ENTER\_YOUR\_LUIS\_MODEL\_URL** valor del marcador de posición por la dirección URL del extremo que copió en el [publicar la sección del modelo LUIS](#publish-the-luis-model). 127 | 128 | 5. Reemplace la **ENTER\_YOUR\_CLIENT\_ID** y **ENTER\_YOUR\_CLIENT\_SECRET** valores de marcador de posición con el identificador de la aplicación y el secreto de la aplicación que copió en la [sección registrar la aplicación web](#register-the-web-application). 129 | 130 | 6. En un símbolo del sistema, ejecute el siguiente comando en el directorio raíz. Esto instala las dependencias del proyecto. 131 | 132 | ```Instalar npm``` 133 | 134 | 7. Ejecute el siguiente comando para iniciar el servidor de desarrollo. 135 | 136 | ```inicio npm``` 137 | 138 | 8. Lanzar el[Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) 139 | 140 | 9. Introduzca el punto final de mensajería para este proyecto de bot: https://localhost:3980/api/messages. Deja los valores de Microsoft App ID y Microsoft App Password en blanco. Estos son para bots publicados. 141 | 142 | 10. Elija el botón **conectar**. 143 | 144 | ## Ejecutar el ejemplo 145 | 146 | 1. Escriba una consulta en el Bot Framework Emulator en este formulario: **Búsqueda de Office 365 para el gráfico**. 147 | 148 | 2. Verá un botón **conectar** en el emulador. Elija este botón para iniciar una página web que muestre una cadena en el navegador. Se le pedirá que escriba la cadena en el chat del emulador. Ten en cuenta que tu navegador puede advertirte que tu PC no confía en el certificado de seguridad del sitio. Elija la opción de continuar a la página web. 149 | 150 | 3. Después de escribir la cadena en el chat, recibirás un mensaje indicando la puntuación de sentimiento para tu consulta. 151 | ![Captura de pantalla de Microsoft Graph Sentiment Bot](./readme-images/BotPreview.png) 152 | 153 | 4. Escriba las preguntas adicionales para ver el análisis sentimental del servicio cognitivo en funcionamiento. 154 | 155 | ## Preguntas y comentarios 156 | 157 | Nos encantaría recibir sus comentarios sobre la muestra de Microsoft Graph Connect para Node.js. Puede enviar sus preguntas y sugerencias en la sección[asuntos](https://github.com/microsoftgraph/nodejs-sentiment-bot-sample/issues)de este repositorio. 158 | 159 | Las preguntas sobre el desarrollo de Microsoft Graph en general deben enviarse a [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Asegúrate de que tus preguntas o comentarios estén etiquetados con \[microsoftgraph]. 160 | 161 | ## Colaboradores ## 162 | 163 | Si quiere hacer su aportación a este ejemplo, vea [CONTRIBUTING.MD](/CONTRIBUTING.md). 164 | 165 | Este proyecto ha adoptado el [Código de conducta de código abierto de Microsoft](https://opensource.microsoft.com/codeofconduct/). Para obtener más información, vea [Preguntas frecuentes sobre el código de conducta](https://opensource.microsoft.com/codeofconduct/faq/) o póngase en contacto con [opencode@microsoft.com](mailto:opencode@microsoft.com) si tiene otras preguntas o comentarios. 166 | 167 | ## Recursos adicionales 168 | 169 | - [Otros ejemplos de código de Microsoft Graph](https://github.com/microsoftgraph?utf8=%E2%9C%93&q=sample) 170 | - [Microsoft Graph](https://graph.microsoft.io) 171 | 172 | ## Derechos de autor 173 | Copyright (c) 2017 Microsoft. Todos los derechos reservados. 174 | -------------------------------------------------------------------------------- /README-localized/README-fr-fr.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - nodejs 7 | - typescript 8 | description: "Utiliser Microsoft Graph, Microsoft Cognitive Services et Microsoft Bot Framework pour analyser les sentiments dans une application web NodeJS." 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft Bot Framework 14 | createdDate: 9/13/2017 10:47:10 AM 15 | --- 16 | # Robot d'analyse des sentiments Microsoft Graph 17 | 18 | ## Table des matières 19 | 20 | * [Introduction](#introduction) 21 | * [Conditions préalables](#prerequisites) 22 | * [Obtenir une clé pour l’API d’Analyse texte](#get-a-key-for-the-text-analytics-api) 23 | * [Publier le modèle LUIS](#publish-the-luis-model) 24 | * [Inscription de l’application web](#register-the-web-application) 25 | * [Créer l’exemple](#build-the-sample) 26 | * [Exécuter l’exemple](#run-the-sample) 27 | * [Questions et commentaires](#questions-and-comments) 28 | * [Contribution](#contributing) 29 | * [Ressources supplémentaires](#additional-resources) 30 | 31 | ## Introduction 32 | 33 | Cet exemple présente comment créer une [Microsoft Bot Framework](https://dev.botframework.com/), un robot qui se connecte à [Microsoft Graph](https://developer.microsoft.com/en-us/graph/), effectue une recherche dans les courriers électroniques et effectue une analyse des sentiments sur ces messages à l’aide du [service cognitif Microsoft Text Analytics](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quick-start). Il tire parti du [Language Understanding Intelligent Service](https://www.luis.ai) pour permettre à votre robot de comprendre les requêtes que vous lui envoyez. 34 | 35 | ## Conditions préalables 36 | 37 | Pour utiliser l’exemple de connexion Microsoft Graph pour Node.js, vous avez besoin des éléments suivants : 38 | 39 | * [Node.js](https://nodejs.org/) 40 | * [TypeScript](http://www.typescriptlang.org/) 41 | * Le [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) 42 | * Un [compte Microsoft](https://www.outlook.com/) ou un [compte professionnel ou scolaire](http://dev.office.com/devprogram) 43 | * Un [compte Microsoft Azure](https://azure.microsoft.com/en-us/free/) 44 | * Un [compte Language Understanding Intelligent Service](https://www.luis.ai/) 45 | 46 | Outre ces conditions préalables, vous devez [obtenir une clé d’abonnement pour l’API Text Analytics](#get-a-key-for-the-text-analytics-api), [publier un modèle LUIS]()et [enregistrer une application cliente web](#register-the-web-application). Les trois sections ci-après décrivent comment obtenir ces ressources supplémentaires. 47 | 48 | ## Obtenir une clé pour l’API d’Analyse texte 49 | 50 | 1. Connectez-vous au [Portail Azure](https://portal.azure.com). 51 | 52 | 2. Sélectionnez **Autres services** en bas de la colonne de gauche de la page. 53 | 54 | 3. Dans la boîte de dialogue **Filtre** en haut de la colonne **Autres services**, tapez **Services cognitifs**. 55 | 56 | 4. Choisissez l’option **Services cognitifs** lorsqu'elle apparaît. 57 | 58 | 5. Choisissez le bouton **Ajouter** en haut de la page. 59 | 60 | 6. Choisissez l’option **Text Analytics API (préversion)** dans le volet droit. 61 | 62 | 7. Choisissez le bouton **Créer** en bas du volet droit. 63 | 64 | 8. Tapez un nom pour votre inscription, puis sélectionnez une offre. Vous pouvez sélectionner le niveau Gratuit comprenant 5 000 transactions par mois. 65 | 66 | 9. Lisez et confirmez que vous avez compris l’information préalable dans la partie inférieure du volet, puis sélectionnez le bouton **Créer** tout en haut. 67 | 68 | 10. Une fois votre abonnement créé, accédez à votre abonnement, puis sélectionnez **Clés** sous la section **Gestion des ressources** du volet central. 69 | 70 | 11. Copiez la valeur de la première clé (« Clé 1 »). Vous utiliserez cette valeur dans la section [Créer l'exemple](#build-the-sample). 71 | 72 | 73 | ## Publier le modèle LUIS 74 | 75 | 1. Accédez à la page d’accueil de ](https://www.luis.ai)Language Understanding Intelligent Service[ (LUIS). 76 | 77 | 2. Si vous n’en avez pas déjà un, créez un compte LUIS. Vous accédez automatiquement au tableau de bord de votre compte. 78 | 79 | 3. Choisissez **Mes applications** dans le coin supérieur gauche de la page du tableau de bord. 80 | 81 | 4. Sélectionnez **Importer une application** 82 | 83 | 5. Dans le menu contextuel, accédez au fichier [SearchBotLUIS.JSON](./SearchBotLUIS.json) dans le répertoire racine de ce référentiel. 84 | 85 | 6. Choisissez le bouton **Importer**. Vous accédez automatiquement au tableau de bord de votre nouvelle application. 86 | 87 | 7. Sélectionnez **Publier une application** dans le menu de gauche. 88 | 89 | 8. Sélectionnez l’option **BootstrapKey** par défaut comme valeur pour la **Clé de point de terminaison**, puis sélectionnez le bouton **Publier**. 90 | ![Capture d'écran de Microsoft Graph Sentiment Bot](./readme-images/PublishLUISApp.png) 91 | 92 | 9. Copier la valeur de l’**URL du point de terminaison**. Vous utiliserez cette valeur dans la section [Créer l'exemple](#build-the-sample). 93 | 94 | 10. Sélectionnez **Former et tester** dans le menu de gauche pour accéder à une page dans laquelle vous pouvez exécuter des requêtes de test sur votre modèle publié. Tapez **Rechercher Office 365 pour Graph** dans le volet d’énoncé de tests pour vérifier que votre nouvelle application recherche une intention pour cette requête. 95 | 96 | ## Inscription de l’application web 97 | 98 | 1. Connectez-vous au [portail d’inscription de l'application Azure](https://go.microsoft.com/fwlink/?linkid=2083908) en utilisant votre compte personnel, professionnel ou scolaire. 99 | 100 | 2. Sélectionnez **Nouvelle inscription**. 101 | 102 | 3. Tapez un nom pour l'application. Pour les **Types de comptes pris en charge**, sélectionnez **Comptes dans un annuaire organisationnel et comptes personnels Microsoft (par ex. Skype, Xbox et Outlook.com)**. 103 | 104 | 4. Entrez *https://localhost :3980/botauth/aadv2/callback* comme URI de redirection (web). 105 | 106 | 5. Choisissez **S'inscrire**. 107 | 108 | La page de vue d'ensemble de l'application s’affiche, répertoriant les propriétés de votre application. 109 | 110 | 6. Copiez l’ID de l’application (client) à partir de la page de vue d’ensemble. Il s’agit de l’identificateur unique de votre application. 111 | 112 | 7. Accédez à la page **Certificats et secrets** sous **Gérer**. Sélectionnez **Nouvelle clé secrète client**, faites-en une description et donnez-lui une date d’expiration, puis sélectionnez **Ajouter**. 113 | 114 | 8. Copiez et enregistrez la valeur de la nouvelle clé secrète client. C'est la seule fois où vous pourrez visualiser la clé secrète client. 115 | 116 | Vous utiliserez l’ID de l’application et la clé secrète client pour configurer l’exemple d’application dans la section suivante. 117 | 118 | ## Créer l’exemple 119 | 120 | 1. Téléchargez ou clonez ce référentiel. 121 | 122 | 2. À l’aide de votre environnement IDE favori, ouvrez le fichier **.env** dans le répertoire racine du référentiel. 123 | 124 | 3. Remplacez la valeur de l’espace réservé **ENTER\_YOUR\_COG\_SERVICE\_SUBSCRIPTION\_KEY** par la clé API Text Analytics que vous avez copiée dans la section [Obtenir une clé pour l'API Text Analytics](#get-a-key-for-the-text-analytics-api). 125 | 126 | 4. Remplacez la valeur de l’espace réservé **ENTER\_YOUR\_LUIS\_MODEL\_URL** par l’URL du point de terminaison que vous avez copiée dans la section [Publier le modèle LUIS](#publish-the-luis-model). 127 | 128 | 5. Remplacez les valeurs de l'espace réservé **ENTER\_YOUR\_CLIENT\_ID** et **ENTER\_YOUR\_CLIENT\_SECRET** par l’ID d’application et le secret de l’application que vous avez copiés dans la section [Inscrivez l'application web](#register-the-web-application). 129 | 130 | 6. Dans une invite de commandes, exécutez la commande suivante dans le répertoire racine. Cette procédure installe les dépendances du projet. 131 | 132 | ```npm install``` 133 | 134 | 7. Entrez la commande suivante pour démarrer le serveur de développement. 135 | 136 | ```npm start``` 137 | 138 | 8. Lancez le ](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator)Bot Framework Emulator[. 139 | 140 | 9. Entrez le point de terminaison de la messagerie pour ce projet de robot : https://localhost:3980/api/messages. Laissez les valeurs ID de l’application Microsoft et mot de passe de l’application Microsoft vierges. Il s’agit de robots publiés. 141 | 142 | 10. Sélectionnez le bouton **Se connecter**. 143 | 144 | ## Exécutez l’exemple 145 | 146 | 1. Tapez une requête dans le Bot Framework Emulator dans ce formulaire : **Rechercher Office 365 pour Graph**. 147 | 148 | 2. Le bouton **Se connecter** s’affiche dans l’émulateur. Sélectionnez ce bouton pour ouvrir une page web affichant une chaîne dans le navigateur. Vous êtes invité à taper cette chaîne dans la conversation de votre émulateur. Veuillez noter que votre navigateur peut vous avertir que votre PC ne fait pas confiance au certificat de sécurité du site. Choisissez l’option pour accéder vers la page web. 149 | 150 | 3. Après avoir entré la chaîne dans votre conversation, vous recevez un message indiquant le score d’un sentiment pour votre requête. 151 | ![Capture d'écran de Microsoft Graph Sentiment Bot](./readme-images/BotPreview.png) 152 | 153 | 4. Tapez d’autres requêtes pour afficher l’analyse sentimental du service cognitif au travail. 154 | 155 | ## Questions et commentaires 156 | 157 | Nous serions ravis de connaître votre opinion sur l’exemple de connexion Microsoft Graph Connect pour Node.js. Vous pouvez nous faire part de vos questions et suggestions dans la rubrique [Problèmes](https://github.com/microsoftgraph/nodejs-sentiment-bot-sample/issues) de ce référentiel. 158 | 159 | Les questions générales sur le développement de Microsoft Graph doivent être publiées sur [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Veillez à poser vos questions ou à rédiger vos commentaires en utilisant les balises \[microsoftgraph]. 160 | 161 | ## Contribution ## 162 | 163 | Si vous souhaitez contribuer à cet exemple, voir [CONTRIBUTING.MD](/CONTRIBUTING.md). 164 | 165 | Ce projet a adopté le [code de conduite Open Source de Microsoft](https://opensource.microsoft.com/codeofconduct/). Pour en savoir plus, reportez-vous à la [FAQ relative au code de conduite](https://opensource.microsoft.com/codeofconduct/faq/) ou contactez [opencode@microsoft.com](mailto:opencode@microsoft.com) pour toute question ou tout commentaire. 166 | 167 | ## Ressources supplémentaires 168 | 169 | - [Autres exemples Microsoft Graph](https://github.com/microsoftgraph?utf8=%E2%9C%93&q=sample) 170 | - [Microsoft Graph](https://graph.microsoft.io) 171 | 172 | ## Copyright 173 | Copyright (c) 2017 Microsoft. Tous droits réservés. 174 | -------------------------------------------------------------------------------- /README-localized/README-ja-jp.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - nodejs 7 | - typescript 8 | description: "Use Microsoft Graph, Microsoft Cognitive Services, and the Microsoft Bot Framework to do sentiment analysis in a NodeJS web application." 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft Bot Framework 14 | createdDate: 9/13/2017 10:47:10 AM 15 | --- 16 | # Microsoft Graph Sentiment Analysis Bot 17 | 18 | ## 目次 19 | 20 | * [はじめに](#introduction) 21 | * [前提条件](#prerequisites) 22 | * [Text Analytics API のキーを取得する](#get-a-key-for-the-text-analytics-api) 23 | * [LUIS モデルを発行する](#publish-the-luis-model) 24 | * [Web アプリケーションを登録する](#register-the-web-application) 25 | * [サンプルをビルドする](#build-the-sample) 26 | * [サンプルを実行する](#run-the-sample) 27 | * [質問とコメント](#questions-and-comments) 28 | * [投稿](#contributing) 29 | * [その他のリソース](#additional-resources) 30 | 31 | ## はじめに 32 | 33 | このサンプルでは、[Microsoft Bot Framework](https://dev.botframework.com/) ボットを作成する方法を示します。このボットは [Microsoft Graph](https://developer.microsoft.com/en-us/graph/) に接続し、メール メッセージを検索し、[Microsoft Text Analytics Cognitive Service](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quick-start) を使用してこれらのメッセージに対して感情分析を実行します。このサンプルでは、[Language Understanding Intelligent Service](https://www.luis.ai) を活用して、ユーザーがボットに送信するクエリをボットが理解できるようにします。 34 | 35 | ## 前提条件 36 | 37 | Node.js 用 Microsoft Graph Connect サンプルを使用するには、以下が必要です。 38 | 39 | * [Node.js](https://nodejs.org/) 40 | * [TypeScript](http://www.typescriptlang.org/) 41 | * [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) 42 | * [Microsoft アカウント](https://www.outlook.com/)か[職場または学校アカウント](http://dev.office.com/devprogram) 43 | * [Microsoft Azure アカウント](https://azure.microsoft.com/en-us/free/) 44 | * [Language Understanding Intelligent Service アカウント](https://www.luis.ai/) 45 | 46 | これらの前提条件に加えて、[Text Analytics API のサブスクリプション キーを取得](#get-a-key-for-the-text-analytics-api)し、[LUIS モデルを発行]()し、[Web クライアント アプリケーションを登録](#register-the-web-application)する必要があります。これらの追加リソースを取得する方法について、以下の 3 つのセクションで説明します。 47 | 48 | ## Text Analytics API のキーを取得する 49 | 50 | 1. [Azure ポータル](https://portal.azure.com)にサインインします。 51 | 52 | 2. ページの左側の列の下部にある [**その他のサービス**] を選択します。 53 | 54 | 3. [**その他のサービス**] 列の上部にある [**フィルター**] ボックスに、"**Cognitive Services**" と入力します。 55 | 56 | 4. [**Cognitive Services**] オプションが表示されたら、それを選択します。 57 | 58 | 5. ページの上部にある [**追加**] ボタンを選択します。 59 | 60 | 6. 右側のウィンドウで、[**Text Analytics API (preview)**] を選択します。 61 | 62 | 7. 右側のウィンドウの下部にある [**作成**] ボタンを選択します。 63 | 64 | 8. サブスクリプション名を入力し、プランを選択します。1 か月あたり 5,000 トランザクションまでの無料レベルを選択します。 65 | 66 | 9. ウィンドウの下部にある通知を読んで理解したことを確認し、一番下にある [**作成**] ボタンを選択します。 67 | 68 | 10. サブスクリプションを作成したら、サブスクリプションに移動し、中央のウィンドウの [**リソース管理**] セクションで [**キー**] を選択します。 69 | 70 | 11. 最初のキー ("Key 1") の値をコピーします。この値は、「[サンプルをビルドする](#build-the-sample)」 セクションで使用します。 71 | 72 | 73 | ## LUIS モデルを発行する 74 | 75 | 1. [Language Understanding Intelligent Service](https://www.luis.ai) (LUIS) のホーム ページに移動します。 76 | 77 | 2. LUIS アカウントがまだない場合は作成します。自動的にアカウントのダッシュボードに移動します。 78 | 79 | 3. ダッシュボード ページの左上隅にある [**My apps (マイ アプリ)**] を選択します。 80 | 81 | 4. [**Import App (アプリのインポート)**] を選択します。 82 | 83 | 5. ポップアップで、このリポジトリのルート ディレクトリにある [[SearchBotLUIS.json](./SearchBotLUIS.json)] ファイルを参照します。 84 | 85 | 6. [**Import (インポート)**] ボタンを選択します。自動的に新しいアプリのダッシュボード ページに移動します。 86 | 87 | 7. [**Publish App (アプリの発行)**] を選択します。 88 | 89 | 8. [**Endpoint key (エンドポイント キー)**] の値として既定の [**BootstrapKey**] オプションを選択し、[**Publish (発行)**] ボタンを選択します。 90 | ![Microsoft Graph Sentiment Bot のスクリーンショット](./readme-images/PublishLUISApp.png) 91 | 92 | 9. [**Endpoint url (エンドポイント URL)**] の値をコピーします。この値は、「[サンプルをビルドする](#build-the-sample)」 セクションで使用します。 93 | 94 | 10. 左のメニューで [**Train and Test (トレーニングとテスト)**] を選択し、発行されたモデルに対してテスト クエリを実行できるページに移動します。テストの発言ウィンドウに "**Search Office 365 for Graph**" と入力し、新しいアプリケーションがこのクエリの目的を検索することを確認します。 95 | 96 | ## Web アプリケーションを登録する 97 | 98 | 1. 個人用アカウントか職場または学校アカウントのいずれかを使用して、[Azure アプリケーション登録ポータル](https://go.microsoft.com/fwlink/?linkid=2083908)にサインインします。 99 | 100 | 2. [**新規登録**] を選択します。 101 | 102 | 3. アプリ名を入力します。[**サポートされているアカウントの種類**] で、[**任意の組織のディレクトリ内のアカウントと、個人用の Microsoft アカウント (Skype、 Xbox、Outlook.com など)**] を選択します。 103 | 104 | 4. リダイレクト URI (Web) として、"*https://localhost:3980/botauth/aadv2/callback*" と入力します。 105 | 106 | 5. [**登録**] を選択します。 107 | 108 | アプリの概要ページが表示され、アプリのプロパティが一覧表示されます。 109 | 110 | 6. 概要ページからアプリケーション (クライアント) ID をコピーします。これは、アプリの一意の識別子です。 111 | 112 | 7. [**管理**] の下にある [**証明書とシークレット**] ページに移動します。[**新しいクライアント シークレット**] を選択し、説明と有効期限を入力し、[**追加**] を選択します。 113 | 114 | 8. 新しいクライアント シークレットの値をコピーして保存します。クライアント シークレットが表示されるのは、このときだけです。 115 | 116 | 次のセクションで、アプリケーション ID とクライアント シークレットを使用してサンプル アプリを構成します。 117 | 118 | ## サンプルをビルドする 119 | 120 | 1. このレポジトリをダウンロードするか、複製を作成します。 121 | 122 | 2. 任意の IDE を使用して、リポジトリのルート ディレクトリにある [**.env**] ファイルを開きます。 123 | 124 | 3. プレースホルダー **ENTER\_YOUR\_COG\_SERVICE\_SUBSCRIPTION\_KEY** の値を、「[Text Analytics API のキーを取得する](#get-a-key-for-the-text-analytics-api)」セクションでコピーした Text Analytics API のキーで置き換えます。 125 | 126 | 4. プレースホルダー **ENTER\_YOUR\_LUIS\_MODEL\_URL** の値を、「[LUIS モデルを発行する](#publish-the-luis-model)」セクションでコピーしたエンドポイント URL で置き換えます。 127 | 128 | 5. プレースホルダー **ENTER\_YOUR\_CLIENT\_ID** と **ENTER\_YOUR\_CLIENT\_SECRET** の値を、「[Web アプリケーションを登録する](#register-the-web-application)」セクションでコピーしたアプリケーション ID とアプリケーション シークレットで置き換えます。 129 | 130 | 6. コマンド プロンプトで、ルート ディレクトリで次のコマンドを実行します。これにより、プロジェクトの依存関係がインストールされます。 131 | 132 | ```npm install``` 133 | 134 | 7. 次のコマンドを実行して開発用サーバーを起動します。 135 | 136 | ```npm start``` 137 | 138 | 8. [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) を起動します。 139 | 140 | 9. このボット プロジェクトのメッセージング エンドポイント (https://localhost:3980/api/messages) を入力します。[Microsoft App ID] と [Microsoft App Password] の値は空白のままにします。これらは発行されたボット用です。 141 | 142 | 10. [**Connect (接続)**] ボタンを選択します。 143 | 144 | ## サンプルを実行する 145 | 146 | 1. 次の形式で、Bot Framework Emulator にクエリを入力します:**Search Office 365 for Graph**。 147 | 148 | 2. エミュレーターに [**Connect (接続)**] ボタンが表示されます。このボタンを選択して、文字列を表示する Web ページをブラウザーで開きます。その文字列をエミュレーターのチャットに入力するように求められます。PC がサイトのセキュリティ証明書を信頼していないという警告がブラウザーに表示される場合があります。Web ページに進むオプションを選択します。 149 | 150 | 3. 文字列をチャットに入力すると、クエリの感情スコアを示すメッセージが届きます。 151 | ![Microsoft Graph Sentiment Bot のスクリーンショット](./readme-images/BotPreview.png) 152 | 153 | 4. 追加のクエリを入力して、Cognitive Servicese の感情分析の動作を確認してみます。 154 | 155 | ## 質問とコメント 156 | 157 | Node.js 用 Microsoft Graph Connect のサンプルに関するフィードバックをお寄せください。質問や提案は、このリポジトリの「[問題](https://github.com/microsoftgraph/nodejs-sentiment-bot-sample/issues)」セクションで送信できます。 158 | 159 | Microsoft Graph 開発全般の質問については、「[Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph)」に投稿してください。質問やコメントには、必ず "microsoftgraph" とタグを付けてください。 160 | 161 | ## 投稿 ## 162 | 163 | このサンプルに投稿する場合は、[CONTRIBUTING.MD](/CONTRIBUTING.md) を参照してください。 164 | 165 | このプロジェクトでは、[Microsoft Open Source Code of Conduct (Microsoft オープン ソース倫理規定)](https://opensource.microsoft.com/codeofconduct/) が採用されています。詳細については、「[Code of Conduct の FAQ](https://opensource.microsoft.com/codeofconduct/faq/)」を参照してください。また、その他の質問やコメントがあれば、[opencode@microsoft.com](mailto:opencode@microsoft.com) までお問い合わせください。 166 | 167 | ## その他のリソース 168 | 169 | - [Microsoft Graph の他のサンプル](https://github.com/microsoftgraph?utf8=%E2%9C%93&q=sample) 170 | - [Microsoft Graph](https://graph.microsoft.io) 171 | 172 | ## 著作権 173 | Copyright (c) 2017 Microsoft.All rights reserved. 174 | -------------------------------------------------------------------------------- /README-localized/README-pt-br.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - nodejs 7 | - typescript 8 | description: "Use o Microsoft Graph, os Serviços Cognitivos da Microsoft e Microsoft Bot Framework para realizar uma análise de sentimento em um aplicativo Web NodeJS." 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft Bot Framework 14 | createdDate: 9/13/2017 10:47:10 AM 15 | --- 16 | # Bot de análise de sentimento do Microsoft Graph 17 | 18 | ## Sumário 19 | 20 | * [Introdução](#introduction) 21 | * [Pré-requisitos](#prerequisites) 22 | * [Obter uma chave para a API de Análise de Texto](#get-a-key-for-the-text-analytics-api) 23 | * [Publicar o modelo LUIS](#publish-the-luis-model) 24 | * [Registrar o aplicativo Web](#register-the-web-application) 25 | * [Criar o exemplo](#build-the-sample) 26 | * [Executar o exemplo](#run-the-sample) 27 | * [Perguntas e comentários](#questions-and-comments) 28 | * [Colaboração](#contributing) 29 | * [Recursos adicionais](#additional-resources) 30 | 31 | ## Introdução 32 | 33 | Esse exemplo mostrar como criar um bot do [Microsoft Bot Framework](https://dev.botframework.com/) que se conecta ao [Microsoft Graph](https://developer.microsoft.com/en-us/graph/), pesquisa mensagens de email e realiza análise de sentimento nessas mensagens usando o [serviço cognitivo da Análise de Texto da Microsoft](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quick-start). Ele utiliza o [Serviço Inteligente de Reconhecimento de Voz](https://www.luis.ai) para ajudar seu bot a entender as consultas que você enviar. 34 | 35 | ## Pré-requisitos 36 | 37 | Para usar o exemplo de conexão do Microsoft Graph para node.js, você precisará do seguinte: 38 | 39 | * [Node.js](https://nodejs.org/) 40 | * [TypeScript](http://www.typescriptlang.org/) 41 | * O [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) 42 | * Uma [conta da Microsoft](https://www.outlook.com/) ou uma [conta corporativa ou de estudante](http://dev.office.com/devprogram) 43 | * Uma [conta do Microsoft Azure](https://azure.microsoft.com/en-us/free/) 44 | * Uma [conta do Serviço Inteligente de Reconhecimento de Voz](https://www.luis.ai/) 45 | 46 | Além desses pré-requisitos, você precisará [obter uma chave de assinatura para a API de Análise de Texto](#get-a-key-for-the-text-analytics-api)), [publicar um modelo LUIS]() e [registrar um aplicativo de cliente Web](#register-the-web-application). As três seções a seguir descrevem como obter esses recursos adicionais. 47 | 48 | ## Obter uma chave para a API de Análise de Texto 49 | 50 | 1. Entre no [Portal do Azure](https://portal.azure.com). 51 | 52 | 2. Escolha **Mais serviços** na parte inferior da coluna esquerda da página. 53 | 54 | 3. Na caixa **Filtrar** na parte superior da coluna **Mais serviços**, digite **Serviços Cognitivos**. 55 | 56 | 4. Escolha a opção **Serviços Cognitivos** quando ela for exibida. 57 | 58 | 5. Escolha o botão **Adicionar** na parte superior da página. 59 | 60 | 6. Escolha a opção **API de Análise de Texto (visualização)** no painel direito. 61 | 62 | 7. Escolha o botão **Criar** na parte inferior do painel direito. 63 | 64 | 8. Digite um nome para a assinatura e selecione um plano. Você pode selecione a camada gratuita para 5.000 transações por mês. 65 | 66 | 9. Leia e confirme que você entendeu o aviso na parte inferior do painel e, em seguida, selecione o botão **Criar** na parte inferior. 67 | 68 | 10. Depois de criar sua assinatura, navegue até ela e selecione **Chaves** na seção **Gerenciamento de Recursos** do painel central. 69 | 70 | 11. Copie o valor da primeira chave (“Chave 1”) Você usará esse valor na seção [Criar o exemplo](#build-the-sample). 71 | 72 | 73 | ## Publicar o modelo LUIS 74 | 75 | 1. Navegue até a página inicial do [Serviço Inteligente de Reconhecimento de Voz](https://www.luis.ai) (LUIS). 76 | 77 | 2. Se você ainda não tiver uma conta LUIS, crie uma agora. Você navegará automaticamente até o painel da sua conta. 78 | 79 | 3. Escolha **Meus aplicativos** no canto superior esquerdo da página do painel. 80 | 81 | 4. Escolha **Importar Aplicativo** 82 | 83 | 5. Na janela pop-up, navegue até o arquivo [SearchBotLUIS.json](./SearchBotLUIS.json) no diretório raiz deste repositório. 84 | 85 | 6. Escolha o botão **Importar**. Você navegará automaticamente até a página de painel do novo aplicativo. 86 | 87 | 7. Escolha **Publish Aplicativo** no menu à esquerda. 88 | 89 | 8. Selecione a opção padrão **BootstrapKey** como o valor da **chave de ponto de extremidade** e, em seguida, selecione o botão **Publish**. 90 | ![Captura de tela do bot de sentimento do Microsoft Graph](./readme-images/PublishLUISApp.png) 91 | 92 | 9. Copie o valor da **URL de ponto de extremidade**. Você usará esse valor na seção [Criar o exemplo](#build-the-sample). 93 | 94 | 10. Selecione **Treinar e Testar** no menu à esquerda para ir a uma página onde você pode executar as consultas no modelo publicado. Digite **Pesquisar o Office 365 para Graph** no painel de teste enunciado para verificar se o novo aplicativo está encontrando uma intenção para essa consulta. 95 | 96 | ## Registrar o aplicativo Web 97 | 98 | 1. Entre no [portal de registro de aplicativos do Azure](https://go.microsoft.com/fwlink/?linkid=2083908) usando sua conta pessoal ou uma conta corporativa ou de estudante. 99 | 100 | 2. Escolha **Novo registro**. 101 | 102 | 3. Digite um nome para o aplicativo. Para **tipos de conta com suporte**, selecione **contas em qualquer diretório organizacional e contas pessoais da Microsoft (por exemplo, Skype, Xbox, Outlook.com)**. 103 | 104 | 4. Insira *https://localhost:3980/botauth/aadv2/callback* como URI de redirecionamento (Web). 105 | 106 | 5. Escolha **Registrar**. 107 | 108 | A página de visão geral do aplicativo será exibida, listando as propriedades do seu aplicativo. 109 | 110 | 6. Copie a ID do aplicativo (cliente) da página visão geral. Esse é o identificador exclusivo do aplicativo. 111 | 112 | 7. Vá para a página **Certificados e segredos** em **Gerenciar**. Escolha **Novo segredo do cliente**, dê uma descrição e data de validade a ele e, em seguida, selecione **Adicionar**. 113 | 114 | 8. Copie e salve o valor do novo segredo do cliente. Esta é a única vez que você poderá ver o segredo do cliente. 115 | 116 | Você usará a ID do aplicativo e o segredo do cliente para configurar o aplicativo de exemplo na próxima seção. 117 | 118 | ## Criar o exemplo 119 | 120 | 1. Baixe ou clone este repositório. 121 | 122 | 2. Usando seu IDE favorito, abra o arquivo **.env** no diretório raiz do repositório. 123 | 124 | 3. Substitua o valor de espaço reservado **ENTER\_YOUR\_COG\_SERVICE\_SUBSCRIPTION\_KEY** com a API de Análise de Texto que você copiou na seção [Obter uma chave para a API de Análise de Texto](#get-a-key-for-the-text-analytics-api). 125 | 126 | 4. Substitua o valor de espaço reservado **ENTER\_YOUR\_LUIS\_MODEL\_URL** com a URL de ponto de extremidade que você copiou na seção [Publicar o modelo LUIS](#publish-the-luis-model). 127 | 128 | 5. Substitua os valores de espaço reservado **ENTER\_YOUR\_CLIENT\_ID** e **ENTER\_YOUR\_CLIENT\_SECRET** com a ID do aplicativo e o segredo do aplicativo que você copiou na seção [Registrar o aplicativo de cliente Web](#register-the-web-application). 129 | 130 | 6. Em um prompt de comando, execute o seguinte comando no diretório raiz. Isso instala as dependências do projeto. 131 | 132 | ```instalação npm``` 133 | 134 | 7. Execute o seguinte comando para iniciar o servidor de desenvolvimento. 135 | 136 | ```início do npm``` 137 | 138 | 8. Inicie o [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator). 139 | 140 | 9. Insira o ponto de extremidade de envio de mensagens para este projeto de bot: https://localhost:3980/api/messages. Deixe em branco os valores da ID do Aplicativo da Microsoft e da Senha do Aplicativo da Microsoft. Esses são para bots publicados. 141 | 142 | 10. Escolha o botão **Conectar**. 143 | 144 | ## Executar o exemplo 145 | 146 | 1. Digite uma consulta no Bot Framework Emulator neste formulário: **Pesquisar o Office 365 para Graph**. 147 | 148 | 2. Você verá um botão **Conectar** no emulador. Escolha este botão para iniciar uma página da Web que exibe uma cadeia de caracteres no navegador. Você será solicitado a digitar essa cadeia de caracteres no chat do emulador. Observe que o seu navegador poderá avisar que seu computador não confia no certificado de segurança do site. Escolha a opção de continuar à página da Web. 149 | 150 | 3. Depois de digitar a cadeia de caracteres no chat, você receberá uma mensagem indicando a pontuação de sentimento da consulta. 151 | ![Captura de tela do bot de sentimento do Microsoft Graph](./readme-images/BotPreview.png) 152 | 153 | 4. Digite consultas adicionais para ver a análise de sentimento do serviço cognitivo em ação. 154 | 155 | ## Perguntas e comentários 156 | 157 | Adoraríamos receber seus comentários sobre o exemplo de conexão do Microsoft Graph para Node.js. Você pode enviar perguntas e sugestões na seção [Problemas](https://github.com/microsoftgraph/nodejs-sentiment-bot-sample/issues) deste repositório. 158 | 159 | As perguntas sobre o desenvolvimento do Microsoft Graph em geral devem ser postadas no [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Não deixe de marcar as perguntas ou comentários com \[microsoftgraph]. 160 | 161 | ## Colaboração ## 162 | 163 | Se quiser contribuir para esse exemplo, confira [CONTRIBUTING.MD](/CONTRIBUTING.md). 164 | 165 | Este projeto adotou o [Código de Conduta de Código Aberto da Microsoft](https://opensource.microsoft.com/codeofconduct/). Para saber mais, confira as [Perguntas frequentes sobre o Código de Conduta](https://opensource.microsoft.com/codeofconduct/faq/) ou entre em contato pelo [opencode@microsoft.com](mailto:opencode@microsoft.com) se tiver outras dúvidas ou comentários. 166 | 167 | ## Recursos adicionais 168 | 169 | - [Outros exemplos do Microsoft Graph](https://github.com/microsoftgraph?utf8=%E2%9C%93&q=sample) 170 | - [Microsoft Graph](https://graph.microsoft.io) 171 | 172 | ## Direitos autorais 173 | Copyright (c) 2017 Microsoft. Todos os direitos reservados. 174 | -------------------------------------------------------------------------------- /README-localized/README-ru-ru.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - nodejs 7 | - typescript 8 | description: "Используйте Microsoft Graph, Microsoft Cognitive Services и Microsoft Bot Framework для анализа настроений в веб-приложении NodeJS" 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft Bot Framework 14 | createdDate: 9/13/2017 10:47:10 AM 15 | --- 16 | # Microsoft Graph Анализ настроений Bot 17 | 18 | ## Содержание 19 | 20 | * [Введение](#introduction) 21 | * [Предварительные требования](#prerequisites) 22 | * [Получить ключ для API текстовых аналитиков](#get-a-key-for-the-text-analytics-api) 23 | * [Опубликовать модель LUIS](#publish-the-luis-model) 24 | * [Регистрация веб-приложения](#register-the-web-application) 25 | * [выполнить сборку кода из примера;](#build-the-sample) 26 | * [Запустите пример](#run-the-sample) 27 | * [Вопросы и комментарии](#questions-and-comments) 28 | * [Участие](#contributing) 29 | * [Дополнительные ресурсы](#additional-resources) 30 | 31 | ## Введение 32 | 33 | В этом примере показано, как создать [Microsoft Bot Framework](https://dev.botframework.com/), который подключается к [Microsoft Graph](https://developer.microsoft.com/en-us/graph/), просматривает сообщения в сообщениях электронной почты и выполняет анализ мнений в этих сообщениях с помощью [Познавательный сервис Microsoft Text Analytics](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quick-start). Он использует интеллектуальную службу [Интеллектуальная служба Понимания языка ](https://www.luis.ai), чтобы помочь вашему боту понять запросы, которые вы ему отправляете. 34 | 35 | ## Предварительные требования 36 | 37 | Чтобы использовать образец Microsoft Graph Connect для Node.js, вам необходимо следующее: 38 | 39 | * [Node.js](https://nodejs.org/) 40 | * [TypeScript](http://www.typescriptlang.org/) 41 | * [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) 42 | * [Учетная запись Microsoft](https://www.outlook.com/) или [рабочая или учебная учетная запись](http://dev.office.com/devprogram) 43 | * Учетная запись [Microsoft Azure](https://azure.microsoft.com/en-us/free/) 44 | * [учетная запись Интеллектуальной службы Понимания языка](https://www.luis.ai/) 45 | 46 | В дополнение к этим предварительным условиям вам необходимо [получить ключ подписки для API Text Analytics](#get-a-key-for-the-text-analytics-api)), [опубликовать модель LUIS]() и [зарегистрировать приложение веб-клиента](#register-the-web-application). В следующих трех разделах описано, как получить эти дополнительные ресурсы. 47 | 48 | ## Получить ключ для API текстовых аналитиков 49 | 50 | 1. Войдите на [портал Azure](https://portal.azure.com). 51 | 52 | 2. В нижней части левого столбца страницы выберите **другие службы**. 53 | 54 | 3. В поле **Фильтр** в верхней части столбца **Дополнительные службы** введите **Cognitive Services**. 55 | 56 | 4. Выберите опцию **Cognitive Services**, когда она появится. 57 | 58 | 5. Нажмите кнопку **Добавить** в верхней части страницы. 59 | 60 | 6. Выберите опцию **Text Analytics API (предварительный просмотр)** на правой панели. 61 | 62 | 7. Нажмите кнопку **Создать** в нижней части правой панели. 63 | 64 | 8. Введите имя для вашей подписки и выберите план. Вы можете выбрать бесплатный уровень для 5000 транзакций в месяц. 65 | 66 | 9. Прочитайте и подтвердите, что вы поняли уведомление в нижней части панели, а затем нажмите кнопку **Создать** в самом низу. 67 | 68 | 10. После создания подписки перейдите к своей подписке и выберите **Ключи** в разделе **Управление ресурсами** на центральной панели. 69 | 70 | 11. Скопируйте значение первого ключа («Ключ 1»). Вы будете использовать это значение в разделе [Построить образец](#build-the-sample) 71 | 72 | 73 | ## Опубликовать модель LUIS 74 | 75 | 1. Перейдите на домашнюю страницу [Интеллектуальная служба понимания языка](https://www.luis.ai) (LUIS). 76 | 77 | 2. Создайте учетную запись LUIS, если у вас ее еще нет. Вы автоматически перейдете на панель управления учетной записью. 78 | 79 | 3. Выберите **Мои приложения** в верхнем левом углу страницы панели инструментов. 80 | 81 | 4. Выберите **приложение для импорта**. 82 | 83 | 5. В всплывающем окне найдите файл [SearchBotLUIS.json](./SearchBotLUIS.json) в корневом каталоге этого репозитория. 84 | 85 | 6. Нажмите кнопку "**импорт**". Вы автоматически перейдете на страницу информационной панели своего нового приложения. 86 | 87 | 7. В меню слева выберите **опубликовать приложение**. 88 | 89 | 8. Выберите значение **BootstrapKey** по умолчанию в качестве значения для **клавишу конечной точки**, а затем нажмите кнопку **публиковать**. 90 | ![Скриншот Microsoft Graph Sentiment Bot](./readme-images/PublishLUISApp.png) 91 | 92 | 9. Скопируйте **URL-адрес конечной точки**. Вы будете использовать это значение в разделе [Построить образец](#build-the-sample) 93 | 94 | 10. Чтобы перейти на страницу, на которой можно выполнить тестовый запрос в соответствии с опубликованной моделью, выберите в меню слева пункт **обучить и тестировать**. Введите **Поиск Office 365 для Graph** на панели тестовых высказываний, чтобы убедиться, что ваше новое приложение находит цель для этого запроса. 95 | 96 | ## Зарегистрировать веб-приложение 97 | 98 | 1. Войдите на [портал регистрации приложений Azure](https://go.microsoft.com/fwlink/?linkid=2083908) с помощью личной, рабочей или учебной учетной записи. 99 | 100 | 2. Выберите **Новая регистрация**. 101 | 102 | 3. Введите имя для приложения. Для **Поддерживаемых типов учетных записей** выберите **Учетные записи в любом организационном каталоге и личные учетные записи Microsoft (например, Skype, Xbox, Outlook.com)**. 103 | 104 | 4. Введите *https://localhost:3980/botauth/aadv2/callback* в качестве URI перенаправления (веб-сайта). 105 | 106 | 5. Нажмите кнопку **Зарегистрировать**. 107 | 108 | Откроется страница обзора приложения со списком свойств вашего приложения. 109 | 110 | 6. Скопируйте идентификатор приложения (клиента) со страницы обзора. Это уникальный идентификатор приложения. 111 | 112 | 7. Выберите **Сертификаты и секреты** в разделе **Управление**. Выберите **новый секрет клиента**, введите его описание и дату окончания срока действия, а затем нажмите кнопку **добавить**. 113 | 114 | 8. Скопируйте и сохраните новый секретный ключ клиента. Это единственный раз, когда вы сможете увидеть секрет клиента. 115 | 116 | Вы будете использовать идентификатор приложения и секрет клиента для настройки примера приложения в следующем разделе. 117 | 118 | ## выполнить сборку кода из примера; 119 | 120 | 1. Загрузите или клонируйте этот репозиторий. 121 | 122 | 2. В вашей любимой среде IDE откройте файл **. env** в корневом каталоге репозитория. 123 | 124 | 3. Замените значение заполнителя **ENTER\_YOUR\_COG\_SERVICE\_SUBSCRIPTION\_KEY** на ключ API Text Analytics, скопированный в [получить ключ для раздела API Text Analytics](#get-a-key-for-the-text-analytics-api). 125 | 126 | 4. Замените значение заполнителя **ENTER\_YOUR\_LUIS\_MODEL\_URL** на URL-адрес конечной точки, который вы скопировали в разделе [Публикация модели LUIS](#publish-the-luis-model). 127 | 128 | 5. Замените значения заполнителей **ENTER\_YOUR\_CLIENT\_ID** и **ENTER\_YOUR\_CLIENT\_SECRET** на идентификатор приложения и секретный ключ приложения, которые вы скопировали в разделе [Регистрация веб-приложения](#register-the-web-application). 129 | 130 | 6. В командной строке выполните следующую команду в корневом каталоге. При этом устанавливаются зависимости проекта. 131 | 132 | ```npm install``` 133 | 134 | 7. Выполните следующую команду, чтобы запустить сервер разработки. 135 | 136 | ```npm start``` 137 | 138 | 8. Запустите [эмулятор Bot Framework](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator). 139 | 140 | 9. Укажите конечную точку обмена сообщениями для этого проекта. https://localhost:3980/api/messages. Оставьте значения Microsoft App ID и Microsoft App Password пустыми. Это для опубликованных ботов. 141 | 142 | 10. Нажмите кнопку **подключиться**. 143 | 144 | ## Запустите пример 145 | 146 | 1. Введите запрос в эмулятор Bot Framework в этой форме: **Поиск Office 365 для графа**. 147 | 148 | 2. Вы увидите кнопку **подключения** в эмуляторе. Нажмите эту кнопку, чтобы запустить веб-страницу, отображающую строку в браузере. Вам будет предлагаться ввести эту строку в чат. Обратите внимание, что ваш браузер может предупредить вас, что ваш компьютер не доверяет сертификату безопасности сайта. Выберите опцию, чтобы перейти на веб-страницу. 149 | 150 | 3. После того, как вы введете строку в свой чат, вы получите сообщение с указанием оценки настроения для вашего запроса. 151 | ![Скриншот Microsoft Graph Sentiment Bot](./readme-images/BotPreview.png) 152 | 153 | 4. Введите дополнительные запросы, чтобы увидеть анализ настроений когнитивных услуг на работе. 154 | 155 | ## Вопросы и комментарии 156 | 157 | Мы хотели бы получить ваши отзывы о образце Microsoft Graph Connect для Node.js. Вы можете отправлять нам свои вопросы и предложения с помощью вкладки [Проблемы](https://github.com/microsoftgraph/nodejs-sentiment-bot-sample/issues) этого репозитория. 158 | 159 | Общие вопросы о разработке решений для Microsoft Graph следует задавать на сайте [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Обязательно помечайте свои вопросы и комментарии тегом \[microsoftgraph]. 160 | 161 | ## Участие ## 162 | 163 | Если вы хотите добавить код в этот пример, просмотрите статью [CONTRIBUTING.MD](/CONTRIBUTING.md). 164 | 165 | Этот проект соответствует [Правилам поведения разработчиков открытого кода Майкрософт](https://opensource.microsoft.com/codeofconduct/). Дополнительные сведения см. в разделе [вопросов и ответов о правилах поведения](https://opensource.microsoft.com/codeofconduct/faq/). Если у вас возникли вопросы или замечания, напишите нам по адресу [opencode@microsoft.com](mailto:opencode@microsoft.com). 166 | 167 | ## Дополнительные ресурсы 168 | 169 | - [Другие примеры кода для Microsoft Graph](https://github.com/microsoftgraph?utf8=%E2%9C%93&q=sample) 170 | - [Microsoft Graph](https://graph.microsoft.io) 171 | 172 | ## Авторские права 173 | (c) Корпорация Майкрософт (Microsoft Corporation), 2017. Все права защищены. 174 | -------------------------------------------------------------------------------- /README-localized/README-zh-cn.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - nodejs 7 | - typescript 8 | description: "使用 Microsoft Graph、Microsoft 认知服务和 Microsoft Bot Framework 在 NodeJS Web 应用程序中进行情绪分析。" 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft Bot Framework 14 | createdDate: 9/13/2017 10:47:10 AM 15 | --- 16 | # Microsoft Graph Sentiment Analysis Bot 17 | 18 | ## 目录 19 | 20 | * [简介](#introduction) 21 | * [先决条件](#prerequisites) 22 | * [获取文本分析 API 密钥](#get-a-key-for-the-text-analytics-api) 23 | * [发布 LUIS 模型](#publish-the-luis-model) 24 | * [注册 Web 应用](#register-the-web-application) 25 | * [生成示例](#build-the-sample) 26 | * [运行示例](#run-the-sample) 27 | * [问题和意见](#questions-and-comments) 28 | * [参与](#contributing) 29 | * [其他资源](#additional-resources) 30 | 31 | ## 简介 32 | 33 | 此示例显示如何创建 [Microsoft Bot Framework](https://dev.botframework.com/) 机器人,它连接至 [Microsoft Graph](https://developer.microsoft.com/en-us/graph/),搜索电子邮件,并使用 “[Microsoft 文本分析认知服务](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quick-start)”对这些邮件进行情感分析。它利用“[语言理解智能服务](https://www.luis.ai)”,帮助你的机器人理解发送给它的查询。 34 | 35 | ## 先决条件 36 | 37 | 若要使用针对 Node.js 的 Microsoft Graph 连接示例,需满足以下条件: 38 | 39 | * [Node.js](https://nodejs.org/) 40 | * [TypeScript](http://www.typescriptlang.org/) 41 | * [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) 42 | * 一个 [Microsoft 帐户](https://www.outlook.com/)或者一个[工作或学校帐户](http://dev.office.com/devprogram) 43 | * 一个 [Microsoft Azure 账户](https://azure.microsoft.com/en-us/free/) 44 | * 一个[语言理解智能服务账户](https://www.luis.ai/) 45 | 46 | 除这些先决条件外,还需要“[获取文本分析 API 订阅密钥](#get-a-key-for-the-text-analytics-api))”、“[发布 LUIS 模型]()”和“[注册 Web 客户端应用程序](#register-the-web-application)”。下列三个部分叙述如何获取这些附加资源。 47 | 48 | ## 获取文本分析 API 密钥 49 | 50 | 1. 登录到 [Azure 门户](https://portal.azure.com)。 51 | 52 | 2. 在页面左列的底部选择“**更多服务**”。 53 | 54 | 3. 在“**更多服务**”列顶部的“**筛选器**”框中,输入“**认知服务**”。 55 | 56 | 4. 出现时,选择“**认知服务**”选项。 57 | 58 | 5. 在窗格顶部选择“**添加**”按钮。 59 | 60 | 6. 选择右窗格中的“**文本分析 API (预览版)**”选项。 61 | 62 | 7. 选择右窗格底部的“**创建**”按钮。 63 | 64 | 8. 输入订阅的名称并选择一项计划。对于每月 5,000 交易,可选择免费层。 65 | 66 | 9. 阅读并确认已理解窗格底部附近的通知,然后选择最底部的“**创建**”按钮。 67 | 68 | 10. 创建订阅后,导航至订阅并选择左窗格“**资源管理**”部分下的“**密钥**”。 69 | 70 | 11. 复制第一个密钥的数值("Key 1")。该数值将在“[生成示例](#build-the-sample)”部分使用。 71 | 72 | 73 | ## 发布 LUIS 模型 74 | 75 | 1. 导航到“[语言理解智能服务](https://www.luis.ai)”(LUIS)主页。 76 | 77 | 2. 如果还没有 LUIS 账户,请创建一个。系统自动导航至账户仪表板。 78 | 79 | 3. 选择仪表板页面左上角的“**我的应用程序**”。 80 | 81 | 4. 选择“**导入应用**” 82 | 83 | 5. 在弹出窗口中,浏览此存储库根目录中的 [SearchBotLUIS.json](./SearchBotLUIS.json) 文件。 84 | 85 | 6. 选择“**导入**”按钮。系统自动导航至新应用程序的仪表板页面。 86 | 87 | 7. 选择左侧菜单中的“**发布应用程序**”。 88 | 89 | 8. 选择默认“**BootstrapKey**”选项作为“**终结点密钥**”值,然后选择“**发布**”按钮。 90 | ![Microsoft Graph Sentiment Bot 截屏](./readme-images/PublishLUISApp.png) 91 | 92 | 9. 复制“**终结点 URL**”值。该数值将在“[生成示例](#build-the-sample)”部分使用。 93 | 94 | 10. 选择左侧菜单中的“**培训和测试**”,以转至针对已发布模型运行查询的页面。在测试言语窗格中输入“**Search Office 365 for Graph** ”,以验证新应用程序正在查找此查询的意图。 95 | 96 | ## 注册 Web 应用 97 | 98 | 1. 使用个人帐户或者工作或学校帐户登录到 [Azure 应用注册门户](https://go.microsoft.com/fwlink/?linkid=2083908)。 99 | 100 | 2. 选择“**新注册**”。 101 | 102 | 3. 输入应用程序的名称。对于“**支持的帐户类型**”,选择“**任何组织目录中的帐户和 Microsoft 个人帐户”(例如,Skype、Xbox、Outlook.com)**。 103 | 104 | 4. 输入 *https://localhost:3980/botauth/aadv2/callback* 作为重定向 URI (Web)。 105 | 106 | 5. 选择“**注册**”。 107 | 108 | 应用程序概述页面显示,列出应用程序的属性。 109 | 110 | 6. 从 概述页面复制应用程序(客户端) ID。这是应用的唯一标识符。 111 | 112 | 7. 转至“**管理**”下的“**证书和密码**”页面。选择“**新建客户端密码**”,并输入描述和到期日期,随后选择“**添加**”。 113 | 114 | 8. 复制并保存新的客户端密码值。这是你能查看客户端密码的唯一时间。 115 | 116 | 使用应用程序 ID 和客户端密码在下一部分中配置示例应用。 117 | 118 | ## 生成示例 119 | 120 | 1. 下载或克隆该存储库。 121 | 122 | 2. 使用喜欢的 IDE,在存储库的根目录中打开 **.env** 文件。 123 | 124 | 3. 使用复制至“[获取文本分析 API 密钥](#get-a-key-for-the-text-analytics-api)”部分中的文本分析 API 密钥,替换 **ENTER\_YOUR\_COG\_SERVICE\_SUBSCRIPTION\_KEY** 占位符值。 125 | 126 | 4. 使用复制至 “[发布 LUIS 模型](#publish-the-luis-model)”中的终结点 URL,替换 **ENTER\_YOUR\_LUIS\_MODEL\_URL** 占位符值。 127 | 128 | 5. 使用复制至“[注册 Web 应用程序](#register-the-web-application)”中的应用程序密码,替换 **ENTER\_YOUR\_CLIENT\_ID** 和 **ENTER\_YOUR\_CLIENT\_SECRET** 占位符值。 129 | 130 | 6. 在命令提示窗口的根目录中运行以下命令。这将安装项目依赖项。 131 | 132 | ```npm install``` 133 | 134 | 7. 运行以下命令以启动开发服务器。 135 | 136 | ``` npm start ``` 137 | 138 | 8. 启动 [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator)。 139 | 140 | 9. 输入此机器人项目的消息终结点: https://localhost:3980/api/messages。将 Microsoft App ID 和 Microsoft App Password 值保留为空白。它们用于机器人。 141 | 142 | 10. 选择“**连接**”按钮。 143 | 144 | ## 运行示例 145 | 146 | 1. 采用这种形式在 Bot Framework Emulator 中输入查询:**Search Office 365 for Graph**。 147 | 148 | 2. 你将在模拟器中看到“**连接**”按钮。选择此按钮,以启动在浏览器中显示字符串的 Web 页面。系统将提示在仿真器聊天中输入字符串。注意,浏览器可能会警告你的计算机不信任网站的安全证书。选择选项,以继续至 Web 页面。 149 | 150 | 3. 在聊天中输入字符串后,将获得指示查询情绪分数的消息。 151 | ![Microsoft Graph Sentiment Bot 截屏](./readme-images/BotPreview.png) 152 | 153 | 4. 输入附加查询,以在工作时查看认知服务的情绪分析。 154 | 155 | ## 问题和意见 156 | 157 | 对于针对 Node.js 的 Microsoft Graph 连接示例,我们非常乐意收到你的相关反馈。你可以在该存储库中的“[问题](https://github.com/microsoftgraph/nodejs-sentiment-bot-sample/issues)”部分将问题和建议发送给我们。 158 | 159 | 与 Microsoft Graph 开发相关的一般问题应发布到 [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph)。请确保你的问题或意见标记有 \[microsoftgraph]。 160 | 161 | ## 参与 ## 162 | 163 | 如果想要参与本示例,请参阅 [CONTRIBUTING.MD](/CONTRIBUTING.md)。 164 | 165 | 此项目已采用 [Microsoft 开放源代码行为准则](https://opensource.microsoft.com/codeofconduct/)。有关详细信息,请参阅[行为准则常见问题解答](https://opensource.microsoft.com/codeofconduct/faq/)。如有其他任何问题或意见,也可联系 [opencode@microsoft.com](mailto:opencode@microsoft.com)。 166 | 167 | ## 其他资源 168 | 169 | - [其他 Microsoft Graph 示例](https://github.com/microsoftgraph?utf8=%E2%9C%93&q=sample) 170 | - [Microsoft Graph](https://graph.microsoft.io) 171 | 172 | ## 版权信息 173 | 版权所有 (c) 2017 Microsoft。保留所有权利。 174 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Microsoft Graph Sentiment Analysis Bot 2 | 3 | ## IMPORTANT 4 | 5 | **This project is being archived. As part of the archival process, we're closing all open issues and pull requests.** 6 | 7 | **You can continue to use this sample "as-is", but it won't be maintained moving forward. We apologize for any inconvenience.** 8 | 9 | ## Table of contents 10 | 11 | * [Introduction](#introduction) 12 | * [Prerequisites](#prerequisites) 13 | * [Get a key for the Text Analytics API](#get-a-key-for-the-text-analytics-api) 14 | * [Publish the LUIS model](#publish-the-luis-model) 15 | * [Register the web application](#register-the-web-application) 16 | * [Build the sample](#build-the-sample) 17 | * [Run the sample](#run-the-sample) 18 | * [Questions and comments](#questions-and-comments) 19 | * [Contributing](#contributing) 20 | * [Additional resources](#additional-resources) 21 | 22 | ## Introduction 23 | 24 | This sample shows how to build a [Microsoft Bot Framework](https://dev.botframework.com/) bot that connects to [Microsoft Graph](https://developer.microsoft.com/en-us/graph/), searches through email messages, and performs sentiment analysis on those messages by using the [Microsoft Text Analytics cognitive service](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quick-start). It leverages the [Language Understanding Intelligent Service](https://www.luis.ai) to help your bot understand the queries you send to it. 25 | 26 | ## Prerequisites 27 | 28 | To use the Microsoft Graph Connect Sample for Node.js, you need the following: 29 | 30 | * [Node.js](https://nodejs.org/) 31 | * [TypeScript](http://www.typescriptlang.org/) 32 | * The [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator) 33 | * Either a [Microsoft account](https://www.outlook.com/) or a [work or school account](http://dev.office.com/devprogram) 34 | * A [Microsoft Azure Account](https://azure.microsoft.com/en-us/free/) 35 | * A [Language Understanding Intelligent Service Account](https://www.luis.ai/) 36 | 37 | In addition to these prerequisites, you'll need to [get a subscription key for the Text Analytics API](#get-a-key-for-the-text-analytics-api)), [publish a LUIS model](), and [register a web client application](#register-the-web-application). The following three sections describe how to get these additional resources. 38 | 39 | ## Get a key for the Text Analytics API 40 | 41 | 1. Sign in to the [Azure Portal](https://portal.azure.com). 42 | 43 | 2. Choose **More services** at the bottom of the left column of the page. 44 | 45 | 3. In the **Filter** box at the top of the **More Services** column, type **Cognitive Services**. 46 | 47 | 4. Choose the **Cognitive Services** option when it appears. 48 | 49 | 5. Choose the **Add** button at the top of the page. 50 | 51 | 6. Choose the **Text Analytics API (preview)** option in the right pane. 52 | 53 | 7. Choose the **Create** button at the bottom of the right pane. 54 | 55 | 8. Type a name for your subscription and select a plan. You may select the free tier for 5,000 transactions per month. 56 | 57 | 9. Read and confirm that you've understood the notice near the bottom of the pane, and then select the **Create** button at the very bottom. 58 | 59 | 10. After you've created your subscription, navigate to your subscription and select **Keys** under the **Resource Management** section of the center pane. 60 | 61 | 11. Copy the value of the first key ("Key 1"). You'll use this value in the [Build the sample](#build-the-sample) section. 62 | 63 | 64 | ## Publish the LUIS model 65 | 66 | 1. Navigate to the [Language Understanding Intelligent Service](https://www.luis.ai) (LUIS) home page. 67 | 68 | 2. Create a LUIS account if you don't already have one. You'll automatically navigate to your account dashboard. 69 | 70 | 3. Choose **My apps** in the upper left corner of the dashboard page. 71 | 72 | 4. Choose **Import App** 73 | 74 | 5. In the popup, browse to the [SearchBotLUIS.json](./SearchBotLUIS.json) file in the root directory of this repo. 75 | 76 | 6. Choose the **Import** button. You'll automatically navigate to the dashboard page of your new app. 77 | 78 | 7. Choose **Publish App** in the left menu. 79 | 80 | 8. Select the default **BootstrapKey** option as the value for **Endpoint key**, and then select the **Publish** button. 81 | ![Microsoft Graph Sentiment Bot screenshot](./readme-images/PublishLUISApp.png) 82 | 83 | 9. Copy the **Endpoint url** value. You'll use this value in the [Build the sample](#build-the-sample) section. 84 | 85 | 10. Select **Train and Test** in the left menu to go to a page where you can run test queries against your published model. Type **Search Office 365 for Graph** in the test utterance pane to verify that your new application is finding an intent for this query. 86 | 87 | ## Register the web application 88 | 89 | 1. Sign into the [Azure application registration portal](https://go.microsoft.com/fwlink/?linkid=2083908) using either your personal or work or school account. 90 | 91 | 2. Choose **New registration**. 92 | 93 | 3. Enter a name for the app. For **Supported account types**, select **Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com)**. 94 | 95 | 4. Enter *https://localhost:3980/botauth/aadv2/callback* as the Redirect URI (Web). 96 | 97 | 5. Choose **Register**. 98 | 99 | The app overview page displays, listing the properties of your app. 100 | 101 | 6. Copy the Application (client) ID from the overview page. This is the unique identifier for your app. 102 | 103 | 7. Go to the **Certificates & secrets** page under **Manage**. Choose **New client secret**, give it a description and expiration date, and then select **Add**. 104 | 105 | 8. Copy and save the new client secret's value. This is the only time you will be able to see the client secret. 106 | 107 | You'll use the application ID and client secret to configure the sample app in the next section. 108 | 109 | ## Build the sample 110 | 111 | 1. Download or clone this repo. 112 | 113 | 2. Using your favorite IDE, open the **.env** file in the root directory of the repo. 114 | 115 | 3. Replace the **ENTER_YOUR_COG_SERVICE_SUBSCRIPTION_KEY** placeholder value with the Text Analytics API key that you copied in the [Get a key for the Text Analytics API](#get-a-key-for-the-text-analytics-api) section. 116 | 117 | 4. Replace the **ENTER_YOUR_LUIS_MODEL_URL** placeholder value with the endpoint url that you copied in the [Publish the LUIS model](#publish-the-luis-model) section. 118 | 119 | 5. Replace the **ENTER_YOUR_CLIENT_ID** and **ENTER_YOUR_CLIENT_SECRET** placeholder values with the application Id and application secret that you copied in the [Register the web application](#register-the-web-application) section. 120 | 121 | 6. In a command prompt, run the following command in the root directory. This installs the project dependencies. 122 | 123 | ```npm install``` 124 | 125 | 7. Run the following command to start the development server. 126 | 127 | ```npm start``` 128 | 129 | 8. Launch the [Bot Framework Emulator](https://docs.microsoft.com/en-us/bot-framework/debug-bots-emulator). 130 | 131 | 9. Enter the messaging endpoint for this bot project: https://localhost:3980/api/messages. Leave the Microsoft App ID and Microsoft App Password values blank. These are for published bots. 132 | 133 | 10. Choose the **Connect** button. 134 | 135 | ## Run the sample 136 | 137 | 1. Type a query into the Bot Framework Emulator in this form: **Search Office 365 for Graph**. 138 | 139 | 2. You'll see a **Connect** button in the emulator. Choose this button to launch a web page that displays a string in the browser. You'll be prompted to type that string into your emulator chat. Note that your browser might warn you that your PC doesn't trust the site's security certificate. Choose the option to continue to the web page. 140 | 141 | 3. After you type the string into your chat, you'll get a message indicating the sentiment score for your query. 142 | ![Microsoft Graph Sentiment Bot screenshot](./readme-images/BotPreview.png) 143 | 144 | 4. Type additional queries to see the cognitive service's sentimental analysis at work. 145 | 146 | ## Questions and comments 147 | 148 | We'd love to get your feedback about the Microsoft Graph Connect Sample for Node.js. You can send your questions and suggestions in the [Issues](https://github.com/microsoftgraph/nodejs-sentiment-bot-sample/issues) section of this repository. 149 | 150 | Questions about Microsoft Graph development in general should be posted to [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Make sure that your questions or comments are tagged with [microsoftgraph]. 151 | 152 | ## Contributing ## 153 | 154 | If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md). 155 | 156 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 157 | 158 | ## Additional resources 159 | 160 | - [Other Microsoft Graph samples](https://github.com/microsoftgraph?utf8=%E2%9C%93&q=sample) 161 | - [Microsoft Graph](https://graph.microsoft.io) 162 | 163 | ## Copyright 164 | Copyright (c) 2017 Microsoft. All rights reserved. 165 | -------------------------------------------------------------------------------- /SearchBotLUIS.json: -------------------------------------------------------------------------------- 1 | { 2 | "luis_schema_version": "2.1.0", 3 | "versionId": "0.1", 4 | "name": "SearchBot", 5 | "desc": "", 6 | "culture": "en-us", 7 | "intents": [ 8 | { 9 | "name": "None" 10 | }, 11 | { 12 | "name": "Search" 13 | } 14 | ], 15 | "entities": [ 16 | { 17 | "name": "Source" 18 | }, 19 | { 20 | "name": "Term" 21 | } 22 | ], 23 | "composites": [], 24 | "closedLists": [], 25 | "bing_entities": [], 26 | "actions": [], 27 | "model_features": [], 28 | "regex_features": [], 29 | "utterances": [ 30 | { 31 | "text": "search linkedin for yina arenas", 32 | "intent": "Search", 33 | "entities": [ 34 | { 35 | "entity": "Term", 36 | "startPos": 20, 37 | "endPos": 30 38 | }, 39 | { 40 | "entity": "Source", 41 | "startPos": 7, 42 | "endPos": 14 43 | } 44 | ] 45 | }, 46 | { 47 | "text": "search dynamics for roland hofmann", 48 | "intent": "Search", 49 | "entities": [ 50 | { 51 | "entity": "Term", 52 | "startPos": 20, 53 | "endPos": 33 54 | }, 55 | { 56 | "entity": "Source", 57 | "startPos": 7, 58 | "endPos": 14 59 | } 60 | ] 61 | }, 62 | { 63 | "text": "search office 365 for contoso", 64 | "intent": "Search", 65 | "entities": [ 66 | { 67 | "entity": "Term", 68 | "startPos": 22, 69 | "endPos": 28 70 | }, 71 | { 72 | "entity": "Source", 73 | "startPos": 7, 74 | "endPos": 16 75 | } 76 | ] 77 | }, 78 | { 79 | "text": "search office 365 for richard dizerega", 80 | "intent": "Search", 81 | "entities": [ 82 | { 83 | "entity": "Term", 84 | "startPos": 22, 85 | "endPos": 37 86 | }, 87 | { 88 | "entity": "Source", 89 | "startPos": 7, 90 | "endPos": 16 91 | } 92 | ] 93 | }, 94 | { 95 | "text": "find contoso in dynamics", 96 | "intent": "Search", 97 | "entities": [ 98 | { 99 | "entity": "Term", 100 | "startPos": 5, 101 | "endPos": 11 102 | }, 103 | { 104 | "entity": "Source", 105 | "startPos": 16, 106 | "endPos": 23 107 | } 108 | ] 109 | }, 110 | { 111 | "text": "find mat velloso in office 365", 112 | "intent": "Search", 113 | "entities": [ 114 | { 115 | "entity": "Term", 116 | "startPos": 5, 117 | "endPos": 15 118 | }, 119 | { 120 | "entity": "Source", 121 | "startPos": 20, 122 | "endPos": 29 123 | } 124 | ] 125 | }, 126 | { 127 | "text": "look for anne wallace in linkedin", 128 | "intent": "Search", 129 | "entities": [ 130 | { 131 | "entity": "Term", 132 | "startPos": 9, 133 | "endPos": 20 134 | }, 135 | { 136 | "entity": "Source", 137 | "startPos": 25, 138 | "endPos": 32 139 | } 140 | ] 141 | }, 142 | { 143 | "text": "look for lily nguyen in office 365", 144 | "intent": "Search", 145 | "entities": [ 146 | { 147 | "entity": "Term", 148 | "startPos": 9, 149 | "endPos": 19 150 | }, 151 | { 152 | "entity": "Source", 153 | "startPos": 24, 154 | "endPos": 33 155 | } 156 | ] 157 | }, 158 | { 159 | "text": "locate david shen in office 365", 160 | "intent": "Search", 161 | "entities": [ 162 | { 163 | "entity": "Term", 164 | "startPos": 7, 165 | "endPos": 16 166 | }, 167 | { 168 | "entity": "Source", 169 | "startPos": 21, 170 | "endPos": 30 171 | } 172 | ] 173 | }, 174 | { 175 | "text": "locate fabrikam in dynamics", 176 | "intent": "Search", 177 | "entities": [ 178 | { 179 | "entity": "Term", 180 | "startPos": 7, 181 | "endPos": 14 182 | }, 183 | { 184 | "entity": "Source", 185 | "startPos": 19, 186 | "endPos": 26 187 | } 188 | ] 189 | }, 190 | { 191 | "text": "search for contoso in crm", 192 | "intent": "Search", 193 | "entities": [ 194 | { 195 | "entity": "Term", 196 | "startPos": 11, 197 | "endPos": 17 198 | }, 199 | { 200 | "entity": "Source", 201 | "startPos": 22, 202 | "endPos": 24 203 | } 204 | ] 205 | }, 206 | { 207 | "text": "find jt fletcher in facebook", 208 | "intent": "Search", 209 | "entities": [ 210 | { 211 | "entity": "Term", 212 | "startPos": 5, 213 | "endPos": 15 214 | }, 215 | { 216 | "entity": "Source", 217 | "startPos": 20, 218 | "endPos": 27 219 | } 220 | ] 221 | }, 222 | { 223 | "text": "find james garner in office 365", 224 | "intent": "Search", 225 | "entities": [ 226 | { 227 | "entity": "Term", 228 | "startPos": 5, 229 | "endPos": 16 230 | }, 231 | { 232 | "entity": "Source", 233 | "startPos": 21, 234 | "endPos": 30 235 | } 236 | ] 237 | }, 238 | { 239 | "text": "search for cammie lee in linkedin", 240 | "intent": "Search", 241 | "entities": [ 242 | { 243 | "entity": "Term", 244 | "startPos": 11, 245 | "endPos": 20 246 | }, 247 | { 248 | "entity": "Source", 249 | "startPos": 25, 250 | "endPos": 32 251 | } 252 | ] 253 | } 254 | ] 255 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "microsoft-graph-bot-quickstart-luis-node", 3 | "version": "1.0.0", 4 | "description": "Quickstart template for building a bot that connects to the Microsoft Graph and uses LUIS with NodeJS", 5 | "main": "server.js", 6 | "scripts": { 7 | "init": "npm install", 8 | "build": "tsc -p ./", 9 | "start": "npm run build && node ./src/server/server.js" 10 | }, 11 | "author": "richdizz", 12 | "license": "MIT", 13 | "dependencies": { 14 | "botbuilder": "3.8.4", 15 | "botauth": "0.2.12", 16 | "dotenv": "^2.0.0", 17 | "restify": "^4.3.0", 18 | "express": "4.15.3", 19 | "express-session": "1.15.3", 20 | "passport-azure-ad": "3.0.6", 21 | "@microsoft/microsoft-graph-client": "https://github.com/microsoftgraph/msgraph-sdk-javascript.git", 22 | "@microsoft/microsoft-graph-types": "https://github.com/microsoftgraph/msgraph-typescript-typings.git" 23 | }, 24 | "devDependencies": { 25 | "@types/node": "^6.0.52", 26 | "@types/restify": "^2.0.35", 27 | "@types/express": "4.0.35" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /readme-images/BotPreview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/nodejs-sentiment-bot-sample/646c2963424a5902adbffeac43cf13984811b618/readme-images/BotPreview.png -------------------------------------------------------------------------------- /readme-images/PublishLUISApp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/nodejs-sentiment-bot-sample/646c2963424a5902adbffeac43cf13984811b618/readme-images/PublishLUISApp.png -------------------------------------------------------------------------------- /src/etc/ssl/server.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDejCCAmICCQDQK9hhyoxRVTANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJV 3 | UzEOMAwGA1UECBMFVGV4YXMxDzANBgNVBAcTBkF1c3RpbjERMA8GA1UEChMIcmlj 4 | aGRpenoxFjAUBgNVBAMTDWxvY2FsaG9zdC5zc2wxJDAiBgkqhkiG9w0BCQEWFXJp 5 | Y2hkaXp6QHJpY2hkaXp6LmNvbTAeFw0xNzA2MDgxODAxMTRaFw0xODA2MDgxODAx 6 | MTRaMH8xCzAJBgNVBAYTAlVTMQ4wDAYDVQQIEwVUZXhhczEPMA0GA1UEBxMGQXVz 7 | dGluMREwDwYDVQQKEwhyaWNoZGl6ejEWMBQGA1UEAxMNbG9jYWxob3N0LnNzbDEk 8 | MCIGCSqGSIb3DQEJARYVcmljaGRpenpAcmljaGRpenouY29tMIIBIjANBgkqhkiG 9 | 9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmMTspBPAJmEw/u+18QAvXg/LNnKJ/nAsPW/8 10 | 5E0ZNClA36dIX0KSf7ob5F10usVZmx6OrNCFLWfQFLz2CRg7jS4rw/ZtEgCe891W 11 | 9Md++FUY0HslJaKk/mJrTg+HG5OfK26ZvlfkV80XIiWmQdYkd3sT91BPyglo2ghm 12 | jqSGtBUbesQQ8XPmtjMRAO+2+rGedcioquFTNmGT4ViaNjM007V3OFzdHuhMcCpW 13 | WQox0bNePv/6IM084mNEBhE76Zl51nrdhofpx+gnLaDPjd2ZntQJKcOGEpW+gKmR 14 | tk7a8/bTtXUAkxoxxT+MGq7m3hP/V1XWnev/tDQS0ZUgtNyAbQIDAQABMA0GCSqG 15 | SIb3DQEBBQUAA4IBAQBwZ9t+J39bItntqKuQ2MQYM+dKTWtOYBktYM1xtRsnk6Ic 16 | yItixIES40BHcIb9web2YmPkkY65cTNZpmXwMBJ3nbYj9oSWkxqwEpG6+Sf/AyyA 17 | nmgWzJ7O7RvQ64Hk+tAqfn5KUQ/Ru/bPCKnHGmlxluZQeFF2ZKE+SmVwwytJQCH3 18 | SVChunnmIs5x/ktdr4nxXrz0snnbES1LDd4DznIDYxuZWqC+VNDz8iQxuHrgszDv 19 | 71xda5wmh/r37EW3IH0JdLlpiooP3hcLlEgrpQ/qj+fgq6/uc8Vr7c80RjyC1dNd 20 | lIbi0kWuP0fSMgKzyf6atWWVtU4ueCrgQwTrcbGB 21 | -----END CERTIFICATE----- 22 | -------------------------------------------------------------------------------- /src/etc/ssl/server.csr: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE REQUEST----- 2 | MIICxDCCAawCAQAwfzELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMQ8wDQYD 3 | VQQHEwZBdXN0aW4xETAPBgNVBAoTCHJpY2hkaXp6MRYwFAYDVQQDEw1sb2NhbGhv 4 | c3Quc3NsMSQwIgYJKoZIhvcNAQkBFhVyaWNoZGl6ekByaWNoZGl6ei5jb20wggEi 5 | MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYxOykE8AmYTD+77XxAC9eD8s2 6 | con+cCw9b/zkTRk0KUDfp0hfQpJ/uhvkXXS6xVmbHo6s0IUtZ9AUvPYJGDuNLivD 7 | 9m0SAJ7z3Vb0x374VRjQeyUloqT+YmtOD4cbk58rbpm+V+RXzRciJaZB1iR3exP3 8 | UE/KCWjaCGaOpIa0FRt6xBDxc+a2MxEA77b6sZ51yKiq4VM2YZPhWJo2MzTTtXc4 9 | XN0e6ExwKlZZCjHRs14+//ogzTziY0QGETvpmXnWet2Gh+nH6CctoM+N3Zme1Akp 10 | w4YSlb6AqZG2Ttrz9tO1dQCTGjHFP4warubeE/9XVdad6/+0NBLRlSC03IBtAgMB 11 | AAGgADANBgkqhkiG9w0BAQUFAAOCAQEAj8M2QXnfmL6LzIuihs7kvhqJ48Vnis2X 12 | HH9fc9Mi3tSQoFt39vI7Dp/rrr2FMFgII7nGEPBBmCvmFGT85TZg4iTR93xAdhTV 13 | Zct/GJldJaAfpsfVxM/fO2PKfMeJhQUprF3ixGxM4JvWtJSMMQiK8NDB4UXDUu7Z 14 | UFCgKCeSdoWPdCR/4BPkZecTP5X4bYWs+8RnT2nZsjoBOKNVP0JfBdbTGKUvjDOh 15 | mqkw2XBPc9A6DSsrc8VVtXyROLbN4dRJkKmPQibsAl+6AuZDQ6l6Vz5JUmB9OBra 16 | SMUBhnfwzPKvEpCv/HHIg4yCE0mwfC+zgeb+Hn1cB5waLfyWgY43kw== 17 | -----END CERTIFICATE REQUEST----- 18 | -------------------------------------------------------------------------------- /src/etc/ssl/server.key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEAmMTspBPAJmEw/u+18QAvXg/LNnKJ/nAsPW/85E0ZNClA36dI 3 | X0KSf7ob5F10usVZmx6OrNCFLWfQFLz2CRg7jS4rw/ZtEgCe891W9Md++FUY0Hsl 4 | JaKk/mJrTg+HG5OfK26ZvlfkV80XIiWmQdYkd3sT91BPyglo2ghmjqSGtBUbesQQ 5 | 8XPmtjMRAO+2+rGedcioquFTNmGT4ViaNjM007V3OFzdHuhMcCpWWQox0bNePv/6 6 | IM084mNEBhE76Zl51nrdhofpx+gnLaDPjd2ZntQJKcOGEpW+gKmRtk7a8/bTtXUA 7 | kxoxxT+MGq7m3hP/V1XWnev/tDQS0ZUgtNyAbQIDAQABAoIBAGXF6xBzx/LJlOaB 8 | s2fWg7faNbsUGzJScGaNkKBXbI7/XKSiwOgVZZuJ1MMSL42to8BfXxVp5Q8Wtdza 9 | 9d2hMyseszFdndP8behwcFmp/cBakKlzIJAuBlUiI/JhDdUlR0ib6fiQfSKxEtRA 10 | 2L3Ld4fRir+b1Uv3cM6wAgLNQJ/+2DUWWs7cELyB/WjSujdpdrEbd2glVNXau9Ju 11 | hAI2gskzfkZBCu2LGnehnwSWEBAw/D2YRqKqDk2jTh+U8Oura3Th1FB3SxOJ7sZ3 12 | GnZZgjb6g0lCw/Y/3j3MztRRnIi4CYji07VZxjJSD856mtngy2WCzQ7xmC8RZfs1 13 | uiGpLVECgYEAyxsk5QIshBmlJIenGedhcl8/qX5ZOZvoeNzGV8Shy1UdGWxqk8XD 14 | hdxOScAQ/uR5qITgr+MllTpM4lC9r2TRxVoCf7s4dX/UNhxgNQM+NCdPwrvOf4y/ 15 | umqUzscMnBS4jplA9ETbih+C77ClXbcOhbWpyh3f/Vn6iR/If/sW6Q8CgYEAwI3h 16 | pAkJtCJX3+LNXl7WOQUAm+VGMEnFQC+Ad5YGLvqDNshQqIheNuHv8jLrPXG78nsr 17 | NAlBM8u6X4ia6pbEbTU1ogIf5Gv64RfI9abQgXHQKKry6E7iZZMYprB+TmKJASib 18 | vAuOcqoTAL9BOypIl8ehksOOKQwvJECovEOjZsMCgYAQrev7uo/5UTnUpCc+41eH 19 | UvchbjTZnEodEtRfBNDcp+K54cNm20jRR2ROfi1nIVA0XKUvDJJbjOwfcc4CB1+K 20 | u3eVEcTzMUo2H2JvOBL1qXzNWyr8IozkPDh4OrR4ZOM7Iq7I4Ja+4xOXp4QNDClv 21 | JZoJ9SYd4jPG6wtGJ1KcVQKBgQCns2pPqSdwYXDTJv7iMAq3QmoTXI3SxI0sp7Jl 22 | dJ4SEFBzR+cnwQz9E64c7MgAjau5Nhici2rkJ408Ywc5RPHygyMg5GTOVlT78fEu 23 | MYjrFCrNIIXKWdnHyWLw2kpHDn5wKePo1M/Ngd5nCitP0jXDKzTHU9XeXiQ4mK/c 24 | t7P6bQKBgHNvwfGFrL7kPRSXA1Zn7T908G7zBzVxucTfCVGSWTjC1lKU+UaJBHd1 25 | 0enhYcEBWQwdkEQEi87QaRQENcHn3Q1jLg8femQhLnDSCCiZFL67dtZy7ccOHUsp 26 | gfz1yiOTbtaQn8yTukb8CnY16EcTUdgLvKNJLcU4NYxyAHEcqjgy 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /src/etc/ssl/server.orig.key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | Proc-Type: 4,ENCRYPTED 3 | DEK-Info: DES-EDE3-CBC,AE965F11B3C1597D 4 | 5 | K4cLgXa/ZZJ/8Gq/Cyhy/KfzqM29nwnw3v7nPo4HIxtWQhDATLNo/RW7DTYvJggS 6 | IKk/90zaVjil22hfSmpd84cEK6p7XomH1hj1X45ko42Jf4aCJfT+0EWFyaozwE9v 7 | jr3wmVco3SVPWBxVoh+FpgMRk2tFpex/XrzZ8EzCSZa4m5mepQjVEo74M6TWaZ6t 8 | YrdH4tp5JQ1dhzALAMhXaCaWTKMRfx18hu06eGFtymlfSsy1QLFGthUN6oMszQ3x 9 | 7wu86cromZuEDGQhWA3oN8pfriTtonCxHMcnK4yWhzXwT7IlxA//oDUJF2bhTpTK 10 | tV3ef8kiIhKZr3FNWQPCvZClIGRTPQ3bQuVBMD2PkdaYlIkCwq4+/vfsbmAQie+m 11 | wKqTul3GBlz5IisMege7hC0HMBkFlf9WkbY5QWzowFy0GLahSvo+Kj4kNk/Ufclu 12 | wM5y22STOnjZcTJysZIsakzl6xWYADx8d4wVQDNeQZrn66/BzZV7U6tPNVAZdivn 13 | i37CQKTB0vvWJtkkQLqlLSTDJUbcbhB4jAe2cHbGUW5xAqL2IiTu0OeObh2ooD+L 14 | xqfnulQ5mbFVvScHaGDogGnPP1b6W/LtieW54PJtZBIIPMQmD71lDcLl8BHSE+Bc 15 | gL2rC4razkGDmm1iVhD57zcI8T06YhNrvkT/yld5wEiaIaKXg2ldMC1IAY76j6R0 16 | 7vO/14RmDY1ma8eb5RgythK0NDbXMnQkTNeMk8Hxpb0UUajr1MOhRJ4WB4wS5nLC 17 | aQKMSbFieCXgFS2nIJJgQ5PeduEV7l3kuWMQM68ErAQwHfH6qe8dydp7+6wrbFnA 18 | 44HxHSxI/dXsgZC5ZbESn4xugAZEMSadYT703EEFsS8AiI4NrbCrLTP55Nf+uVuZ 19 | XykBi6LW8v8x9YRxUspC8CzSxzgLH3ButpT79R4Fc8WXZag1jdo+QOfRlOMDzrqD 20 | 69l71PUaJm/fq5b8ekFwB/S/QiYDOMIuVeFAnOH/REAcitGdUPz5/ZQX/jL6lt8L 21 | 2YMaRhGzqi6MdOk0UNeLwDf6Jrr5W/g/s/NEUiszbeQI0s/ByHbqEA2ZMj7uViRe 22 | QQE9Ma4DX6rchqDrAVPvyl0rMcYD3k2T0dQQn4iKDcpqXWbLRqLLmGH8pO+ymzZC 23 | ln64D+URO9uqYURHqJvFX6kU70S1eDbuS1xkEEilkRfGXfKrAweUFICpmAy6VdcA 24 | Gx0dhIsEE3W2mb6dt3aU2XnWWB9IGlD74skLtg4lbGOo+AzfANQIrwg8RDjJl/Bt 25 | NB9ijXuXbJc9kyFOuAjOps6VMo/w+cak4VoXKSUdfjaWWVKEqgt1fLdWWwiYVWUB 26 | o7Ck3AI1cmHqSj/QYsOHO7wXrVQs6oZhjmS4YfR8Kg0j/PA7iia9Qj+RTeh654Xd 27 | ea0cRQWLEP1+IN4Cdra4w/mxi1JAwQghiSboqND1sw+81Af7stEACpBUvoI8+k3R 28 | JiCyctO3wakIjQKuCpacCzg+f8pwHhzt5fO4Trfb4k4xSDNskPUH8IgkvWtrcAL8 29 | npFxcSfhs6td+2zz7febfApcqA3+wLd4VIbxI1HaSLiChacJZXG0uA== 30 | -----END RSA PRIVATE KEY----- 31 | -------------------------------------------------------------------------------- /src/public/code.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Contoso - Login Success 10 | 11 | 12 | 13 | 14 | 15 | 16 | 37 | 38 | 39 | 46 |
47 |
48 | You're almost done. Please type 49 |
50 | in our chat to complete your authentication. 51 |
52 |
53 | 54 | 57 | 58 | -------------------------------------------------------------------------------- /src/server/dialogs/idialog.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | //# sourceMappingURL=idialog.js.map -------------------------------------------------------------------------------- /src/server/dialogs/idialog.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"idialog.js","sourceRoot":"","sources":["idialog.ts"],"names":[],"mappings":""} -------------------------------------------------------------------------------- /src/server/dialogs/idialog.ts: -------------------------------------------------------------------------------- 1 | import * as builder from 'botbuilder'; 2 | 3 | export interface IDialog { 4 | id: string; 5 | name: string; 6 | waterfall: builder.IDialogWaterfallStep[]; 7 | } -------------------------------------------------------------------------------- /src/server/dialogs/searchDialog.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const builder = require("botbuilder"); 4 | const sentimentHelper_1 = require("../helpers/sentimentHelper"); 5 | const MicrosoftGraphClient = require("@microsoft/microsoft-graph-client"); 6 | class searchDialog { 7 | constructor(authHelper) { 8 | this.authHelper = authHelper; 9 | this.id = 'Search'; 10 | this.name = 'Search'; 11 | this.waterfall = [].concat((session, args, next) => { 12 | this.term = builder.EntityRecognizer.findEntity(args.intent.entities, 'Term'); 13 | this.source = builder.EntityRecognizer.findEntity(args.intent.entities, 'Source'); 14 | next(); 15 | }, authHelper.getAccessToken(), (session, results, next) => { 16 | if (results.response != null) { 17 | var client = MicrosoftGraphClient.Client.init({ 18 | authProvider: (done) => { 19 | done(null, results.response); 20 | } 21 | }); 22 | let searchQuery = `$search="${encodeURIComponent(this.term.entity)}"`; 23 | var messages; 24 | client 25 | .api('me/messages') 26 | .top(5) 27 | .query(searchQuery) 28 | .select('bodyPreview') 29 | .get() 30 | .then((res) => { 31 | messages = res.value; 32 | let text = []; 33 | for (var i = 0; i < messages.length; i++) { 34 | text.push(messages[i].bodyPreview); 35 | } 36 | sentimentHelper_1.SentimentHelper.getSentimentScore(text).then((score) => { 37 | session.endConversation(`Sentiment Score: ${score}`); 38 | }, (err) => { 39 | session.endConversation(`Error occurred: ${err}`); 40 | }); 41 | }).catch((err) => { 42 | console.log(err); 43 | session.endConversation(`Error occurred: ${err}`); 44 | }); 45 | } 46 | else { 47 | session.endConversation('Sorry, I did not understand'); 48 | } 49 | }); 50 | } 51 | } 52 | exports.searchDialog = searchDialog; 53 | exports.default = searchDialog; 54 | //# sourceMappingURL=searchDialog.js.map -------------------------------------------------------------------------------- /src/server/dialogs/searchDialog.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"searchDialog.js","sourceRoot":"","sources":["searchDialog.ts"],"names":[],"mappings":";;AACA,sCAAsC;AAItC,gEAA6D;AAE7D,0EAAyE;AAEzE;IACI,YAAoB,UAAsB;QAAtB,eAAU,GAAV,UAAU,CAAY;QACtC,IAAI,CAAC,EAAE,GAAG,QAAQ,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC;QACrB,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC,MAAM,CACtB,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI;YAEhB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;YAC9E,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;YAClF,IAAI,EAAE,CAAC;QACX,CAAC,EACD,UAAU,CAAC,cAAc,EAAE,EAC3B,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI;YACnB,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC;gBAG3B,IAAI,MAAM,GAAG,oBAAoB,CAAC,MAAM,CAAC,IAAI,CAAC;oBAC1C,YAAY,EAAE,CAAC,IAAI;wBACf,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;oBACjC,CAAC;iBACJ,CAAC,CAAC;gBAEH,IAAI,WAAW,GAAG,YAAY,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC;gBACtE,IAAI,QAAiC,CAAC;gBAKtC,MAAM;qBACL,GAAG,CAAC,aAAa,CAAC;qBAClB,GAAG,CAAC,CAAC,CAAC;qBACN,KAAK,CAAC,WAAW,CAAC;qBAClB,MAAM,CAAC,aAAa,CAAC;qBACrB,GAAG,EAAE;qBACL,IAAI,CAAC,CAAC,GAAG;oBACN,QAAQ,GAAI,GAAG,CAAC,KAAK,CAAC;oBACtB,IAAI,IAAI,GAAG,EAAE,CAAC;oBACd,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;wBACvC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;oBACvC,CAAC;oBAED,iCAAe,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK;wBAC/C,OAAO,CAAC,eAAe,CAAC,oBAAoB,KAAK,EAAE,CAAC,CAAC;oBACzD,CAAC,EAAE,CAAC,GAAG;wBACH,OAAO,CAAC,eAAe,CAAC,mBAAmB,GAAG,EAAE,CAAC,CAAC;oBACtD,CAAC,CAAC,CAAC;gBACH,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG;oBACT,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;oBACjB,OAAO,CAAC,eAAe,CAAC,mBAAmB,GAAG,EAAE,CAAC,CAAC;gBACtD,CAAC,CAAC,CAAC;YACX,CAAC;YACD,IAAI,CAAC,CAAC;gBACF,OAAO,CAAC,eAAe,CAAC,6BAA6B,CAAC,CAAC;YAC3D,CAAC;QACL,CAAC,CACJ,CAAC;IACN,CAAC;CAGJ;AA3DD,oCA2DC;AAED,kBAAe,YAAY,CAAC"} -------------------------------------------------------------------------------- /src/server/dialogs/searchDialog.ts: -------------------------------------------------------------------------------- 1 | import { IDialog } from './idialog'; 2 | import * as builder from 'botbuilder'; 3 | import * as restify from 'restify'; 4 | import { AuthHelper } from '../helpers/authHelper'; 5 | //import { HttpHelper } from '../helpers/httpHelper'; 6 | import { SentimentHelper } from '../helpers/sentimentHelper'; 7 | import * as MicrosoftGraph from "@microsoft/microsoft-graph-types" 8 | import * as MicrosoftGraphClient from "@microsoft/microsoft-graph-client" 9 | 10 | export class searchDialog implements IDialog { 11 | constructor(private authHelper: AuthHelper) { 12 | this.id = 'Search'; 13 | this.name = 'Search'; 14 | this.waterfall = [].concat( 15 | (session, args, next) => { 16 | // Read the LUIS detail and then move to auth 17 | this.term = builder.EntityRecognizer.findEntity(args.intent.entities, 'Term'); 18 | this.source = builder.EntityRecognizer.findEntity(args.intent.entities, 'Source'); 19 | next(); 20 | }, 21 | authHelper.getAccessToken(), 22 | (session, results, next) => { 23 | if (results.response != null) { 24 | // Create a client to call Microsoft Graph. 25 | var client = MicrosoftGraphClient.Client.init({ 26 | authProvider: (done) => { 27 | done(null, results.response); 28 | } 29 | }); 30 | 31 | let searchQuery = `$search="${encodeURIComponent(this.term.entity)}"`; 32 | var messages:MicrosoftGraph.Message[]; 33 | 34 | // Use the Microsoft Graph Client (SDK) to search for the term inside me/messages 35 | // and to select the body preview property of each returned message. 36 | // Cap the result set at 5. 37 | client 38 | .api('me/messages') 39 | .top(5) 40 | .query(searchQuery) 41 | .select('bodyPreview') 42 | .get() 43 | .then((res) => { 44 | messages = res.value; 45 | let text = []; 46 | for (var i = 0; i < messages.length; i++) { 47 | text.push(messages[i].bodyPreview); 48 | } 49 | // use the sentiment helper to get sentiment score for the messages 50 | SentimentHelper.getSentimentScore(text).then((score) => { 51 | session.endConversation(`Sentiment Score: ${score}`); 52 | }, (err) => { 53 | session.endConversation(`Error occurred: ${err}`); 54 | }); 55 | }).catch((err) => { 56 | console.log(err); 57 | session.endConversation(`Error occurred: ${err}`); 58 | }); 59 | } 60 | else { 61 | session.endConversation('Sorry, I did not understand'); 62 | } 63 | } 64 | ); 65 | } 66 | 67 | id; name; waterfall; term; source; 68 | } 69 | 70 | export default searchDialog; -------------------------------------------------------------------------------- /src/server/helpers/AuthHelper.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | require('dotenv').config(); 4 | const request = require("request"); 5 | const builder = require("botbuilder"); 6 | const botauth = require("botauth"); 7 | const passport_azure_ad_1 = require("passport-azure-ad"); 8 | class AuthHelper { 9 | constructor(server, bot) { 10 | this._botAuth = new botauth.BotAuthenticator(server, bot, { 11 | session: true, 12 | baseUrl: `https://localhost:3980`, 13 | secret: 'SOME_SECRET', 14 | successRedirect: '/code' 15 | }); 16 | this._botAuth.provider('aadv2', (options) => { 17 | return new passport_azure_ad_1.OIDCStrategy({ 18 | redirectUrl: 'https://localhost:3980/botauth/aadv2/callback', 19 | realm: 'common', 20 | clientID: process.env.CLIENT_ID, 21 | clientSecret: process.env.CLIENT_SECRET, 22 | identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration', 23 | skipUserProfile: false, 24 | validateIssuer: false, 25 | allowHttpForRedirectUrl: true, 26 | responseType: 'code', 27 | responseMode: 'query', 28 | scope: ['email', 'profile', 'offline_access', 'mail.read'], 29 | passReqToCallback: true 30 | }, (req, iss, sub, profile, accessToken, refreshToken, done) => { 31 | if (!profile.displayName) { 32 | return done(new Error('No oid found'), null); 33 | } 34 | profile.accessToken = accessToken; 35 | profile.refreshToken = refreshToken; 36 | done(null, profile); 37 | }); 38 | }); 39 | } 40 | getAccessToken() { 41 | return [].concat(this._botAuth.authenticate('aadv2', {}), (session, results, next) => { 42 | let user = this._botAuth.profile(session, 'aadv2'); 43 | this.getAccessTokenWithRefreshToken(user.refreshToken).then((data) => { 44 | session.userData.accessToken = data.accessToken; 45 | session.userData.refreshToken = data.refreshToken; 46 | next({ response: data.accessToken, resumed: builder.ResumeReason.forward }); 47 | }, (err) => { 48 | next({ response: null, resumed: builder.ResumeReason.forward }); 49 | }); 50 | }); 51 | } 52 | getAccessTokenWithRefreshToken(refreshToken) { 53 | return new Promise((resolve, reject) => { 54 | var data = 'grant_type=refresh_token' 55 | + '&refresh_token=' + refreshToken 56 | + '&client_id=' + process.env.CLIENT_ID 57 | + '&client_secret=' + encodeURIComponent(process.env.CLIENT_SECRET); 58 | var options = { 59 | method: 'POST', 60 | url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token', 61 | body: data, 62 | json: true, 63 | headers: { 'Content-Type': 'application/x-www-form-urlencoded' } 64 | }; 65 | request(options, function (err, res, body) { 66 | if (err) 67 | return reject(err); 68 | resolve({ 69 | accessToken: body.access_token, 70 | refreshToken: body.refresh_token 71 | }); 72 | }); 73 | }); 74 | } 75 | } 76 | exports.AuthHelper = AuthHelper; 77 | //# sourceMappingURL=AuthHelper.js.map -------------------------------------------------------------------------------- /src/server/helpers/AuthHelper.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"AuthHelper.js","sourceRoot":"","sources":["AuthHelper.ts"],"names":[],"mappings":";;AAAA,OAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE,CAAC;AAG3B,mCAAmC;AAEnC,sCAAsC;AACtC,mCAAmC;AACnC,yDAAiD;AAEjD;IACI,YAAY,MAAW,EAAE,GAAyB;QAC9C,IAAI,CAAC,QAAQ,GAAG,IAAI,OAAO,CAAC,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE;YACtD,OAAO,EAAE,IAAI;YACb,OAAO,EAAE,wBAAwB;YACjC,MAAM,EAAG,aAAa;YACtB,eAAe,EAAE,OAAO;SAC3B,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,OAAO;YACpC,MAAM,CAAC,IAAI,gCAAY,CACnB;gBACI,WAAW,EAAE,+CAA+C;gBAC5D,KAAK,EAAE,QAAQ;gBACf,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS;gBAC/B,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,aAAa;gBACvC,gBAAgB,EAAE,gFAAgF;gBAClG,eAAe,EAAE,KAAK;gBACtB,cAAc,EAAE,KAAK;gBACrB,uBAAuB,EAAE,IAAI;gBAC7B,YAAY,EAAE,MAAM;gBACpB,YAAY,EAAE,OAAO;gBACrB,KAAK,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,WAAW,CAAC;gBAC1D,iBAAiB,EAAE,IAAI;aAC1B,EACD,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,IAAI;gBACpD,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC;oBACvB,MAAM,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,cAAc,CAAC,EAAE,IAAI,CAAC,CAAC;gBACjD,CAAC;gBACD,OAAO,CAAC,WAAW,GAAG,WAAW,CAAC;gBAClC,OAAO,CAAC,YAAY,GAAG,YAAY,CAAC;gBACpC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YACxB,CAAC,CAAC,CAAC;QACX,CAAC,CAAC,CAAC;IACP,CAAC;IAKD,cAAc;QACV,MAAM,CAAC,EAAE,CAAC,MAAM,CACZ,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,OAAO,EAAE,EAAE,CAAC,EACvC,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI;YAEnB,IAAI,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAEnD,IAAI,CAAC,8BAA8B,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,IAAS;gBAClE,OAAO,CAAC,QAAQ,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;gBAChD,OAAO,CAAC,QAAQ,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,CAAC;gBAClD,IAAI,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC;YAChF,CAAC,EAAE,CAAC,GAAG;gBACH,IAAI,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC;YACpE,CAAC,CAAC,CAAC;QACP,CAAC,CACJ,CAAC;IACN,CAAC;IAED,8BAA8B,CAAC,YAAoB;QAC/C,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM;YAC/B,IAAI,IAAI,GAAG,0BAA0B;kBAC/B,iBAAiB,GAAG,YAAY;kBAChC,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS;kBACrC,iBAAiB,GAAG,kBAAkB,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;YAExE,IAAI,OAAO,GAAG;gBACV,MAAM,EAAE,MAAM;gBACd,GAAG,EAAE,4DAA4D;gBACjE,IAAI,EAAE,IAAI;gBACV,IAAI,EAAE,IAAI;gBACV,OAAO,EAAE,EAAE,cAAc,EAAG,mCAAmC,EAAE;aACpE,CAAC;YAEF,OAAO,CAAC,OAAO,EAAE,UAAU,GAAG,EAAE,GAAG,EAAE,IAAI;gBACrC,EAAE,CAAC,CAAC,GAAG,CAAC;oBAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5B,OAAO,CAAC;oBACJ,WAAW,EAAE,IAAI,CAAC,YAAY;oBAC9B,YAAY,EAAE,IAAI,CAAC,aAAa;iBACnC,CAAC,CAAC;YACP,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAjFD,gCAiFC"} -------------------------------------------------------------------------------- /src/server/helpers/authHelper.ts: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | 3 | import * as https from 'https'; 4 | import * as request from 'request'; 5 | import * as restify from 'restify'; 6 | import * as builder from 'botbuilder'; 7 | import * as botauth from 'botauth'; 8 | import { OIDCStrategy } from 'passport-azure-ad'; 9 | 10 | export class AuthHelper { 11 | constructor(server: any, bot: builder.UniversalBot) { 12 | this._botAuth = new botauth.BotAuthenticator(server, bot, { 13 | session: true, 14 | baseUrl: `https://localhost:3980`, 15 | secret : 'SOME_SECRET', 16 | successRedirect: '/code' 17 | }); 18 | 19 | this._botAuth.provider('aadv2', (options) => { 20 | return new OIDCStrategy( 21 | { 22 | redirectUrl: 'https://localhost:3980/botauth/aadv2/callback', // redirect: /botauth/aadv2/callback 23 | realm: 'common', 24 | clientID: process.env.CLIENT_ID, 25 | clientSecret: process.env.CLIENT_SECRET, 26 | identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration', 27 | skipUserProfile: false, 28 | validateIssuer: false, 29 | allowHttpForRedirectUrl: true, 30 | responseType: 'code', 31 | responseMode: 'query', 32 | scope: ['email', 'profile', 'offline_access', 'mail.read'], 33 | passReqToCallback: true 34 | }, 35 | (req, iss, sub, profile, accessToken, refreshToken, done) => { 36 | if (!profile.displayName) { 37 | return done(new Error('No oid found'), null); 38 | } 39 | profile.accessToken = accessToken; 40 | profile.refreshToken = refreshToken; 41 | done(null, profile); 42 | }); 43 | }); 44 | } 45 | 46 | _botAuth : botauth.BotAuthenticator; 47 | _authOptions: any; 48 | 49 | getAccessToken() : builder.IDialogWaterfallStep[] { 50 | return [].concat( 51 | this._botAuth.authenticate('aadv2', {}), 52 | (session, results, next) => { 53 | // get token with refresh token 54 | let user = this._botAuth.profile(session, 'aadv2'); 55 | 56 | this.getAccessTokenWithRefreshToken(user.refreshToken).then((data: any) => { 57 | session.userData.accessToken = data.accessToken; 58 | session.userData.refreshToken = data.refreshToken; 59 | next({ response: data.accessToken, resumed: builder.ResumeReason.forward }); 60 | }, (err) => { 61 | next({ response: null, resumed: builder.ResumeReason.forward }); 62 | }); 63 | } 64 | ); 65 | } 66 | 67 | getAccessTokenWithRefreshToken(refreshToken: string){ 68 | return new Promise((resolve, reject) => { 69 | var data = 'grant_type=refresh_token' 70 | + '&refresh_token=' + refreshToken 71 | + '&client_id=' + process.env.CLIENT_ID 72 | + '&client_secret=' + encodeURIComponent(process.env.CLIENT_SECRET); 73 | 74 | var options = { 75 | method: 'POST', 76 | url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token', 77 | body: data, 78 | json: true, 79 | headers: { 'Content-Type' : 'application/x-www-form-urlencoded' } 80 | }; 81 | 82 | request(options, function (err, res, body) { 83 | if (err) return reject(err); 84 | resolve({ 85 | accessToken: body.access_token, 86 | refreshToken: body.refresh_token 87 | }); 88 | }); 89 | }); 90 | } 91 | } -------------------------------------------------------------------------------- /src/server/helpers/httpHelper.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const https = require("https"); 4 | class HttpHelper { 5 | static postJson(headers, host, path, payload) { 6 | return new Promise((resolve, reject) => { 7 | var options = { 8 | host: host, 9 | path: path, 10 | method: 'POST', 11 | headers: headers 12 | }; 13 | let post_req = https.request(options, function (response) { 14 | var body = ''; 15 | response.on('data', function (d) { 16 | body += d; 17 | }); 18 | response.on('end', function () { 19 | var error; 20 | if (response.statusCode === 200) { 21 | resolve(JSON.parse(body)); 22 | } 23 | else { 24 | error = new Error(); 25 | error.code = response.statusCode; 26 | error.message = response.statusMessage; 27 | error.innerError = body.trim(); 28 | reject(error); 29 | } 30 | }); 31 | }).on('error', function (err) { 32 | reject(err); 33 | }); 34 | post_req.write(JSON.stringify(payload)); 35 | post_req.end(); 36 | }); 37 | } 38 | } 39 | exports.HttpHelper = HttpHelper; 40 | //# sourceMappingURL=httpHelper.js.map -------------------------------------------------------------------------------- /src/server/helpers/httpHelper.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"httpHelper.js","sourceRoot":"","sources":["httpHelper.ts"],"names":[],"mappings":";;AAAA,+BAA+B;AAE/B;IAEI,MAAM,CAAC,QAAQ,CAAC,OAAW,EAAE,IAAY,EAAE,IAAY,EAAE,OAAY;QACjE,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM;YAC/B,IAAI,OAAO,GAAG;gBACV,IAAI,EAAE,IAAI;gBACV,IAAI,EAAE,IAAI;gBACV,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE,OAAO;aACnB,CAAC;YACF,IAAI,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,UAAU,QAAQ;gBACpD,IAAI,IAAI,GAAG,EAAE,CAAC;gBACd,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,UAAU,CAAC;oBAC3B,IAAI,IAAI,CAAC,CAAC;gBACd,CAAC,CAAC,CAAC;gBACH,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE;oBACf,IAAI,KAAK,CAAC;oBACV,EAAE,CAAC,CAAC,QAAQ,CAAC,UAAU,KAAK,GAAG,CAAC,CAAC,CAAC;wBAC9B,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;oBAC9B,CAAC;oBAAC,IAAI,CAAC,CAAC;wBACJ,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC;wBACpB,KAAK,CAAC,IAAI,GAAG,QAAQ,CAAC,UAAU,CAAC;wBACjC,KAAK,CAAC,OAAO,GAAG,QAAQ,CAAC,aAAa,CAAC;wBACvC,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;wBAC/B,MAAM,CAAC,KAAK,CAAC,CAAC;oBAClB,CAAC;gBACL,CAAC,CAAC,CAAC;YACP,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG;gBACxB,MAAM,CAAC,GAAG,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;YAGH,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;YACxC,QAAQ,CAAC,GAAG,EAAE,CAAC;QACnB,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AApCD,gCAoCC"} -------------------------------------------------------------------------------- /src/server/helpers/httpHelper.ts: -------------------------------------------------------------------------------- 1 | import * as https from 'https'; 2 | 3 | export class HttpHelper { 4 | 5 | static postJson(headers:any, host: string, path: string, payload: any) { 6 | return new Promise((resolve, reject) => { 7 | var options = { 8 | host: host, 9 | path: path, 10 | method: 'POST', 11 | headers: headers 12 | }; 13 | let post_req = https.request(options, function (response) { 14 | var body = ''; 15 | response.on('data', function (d) { 16 | body += d; 17 | }); 18 | response.on('end', function () { 19 | var error; 20 | if (response.statusCode === 200) { 21 | resolve(JSON.parse(body)); 22 | } else { 23 | error = new Error(); 24 | error.code = response.statusCode; 25 | error.message = response.statusMessage; 26 | error.innerError = body.trim(); 27 | reject(error); 28 | } 29 | }); 30 | }).on('error', function (err) { 31 | reject(err); 32 | }); 33 | 34 | // post the data 35 | post_req.write(JSON.stringify(payload)); 36 | post_req.end(); 37 | }); 38 | } 39 | } -------------------------------------------------------------------------------- /src/server/helpers/sentimentHelper.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | require('dotenv').config(); 4 | const httpHelper_1 = require("./httpHelper"); 5 | class SentimentHelper { 6 | static getSentimentScore(text) { 7 | return new Promise((resolve, reject) => { 8 | let header = { 9 | 'Ocp-Apim-Subscription-Key': process.env.COG_SUB_KEY, 10 | 'Content-Type': 'application/json', 11 | 'Accept': 'application/json' 12 | }; 13 | let payload = { documents: [] }; 14 | for (var i = 0; i < text.length; i++) 15 | payload.documents.push({ 16 | "language": "en", 17 | "id": i, 18 | "text": text[i] 19 | }); 20 | httpHelper_1.HttpHelper.postJson(header, 'westus.api.cognitive.microsoft.com', '/text/analytics/v2.0/sentiment', payload).then((data) => { 21 | let totalScore = 0.0; 22 | for (var i = 0; i < data.documents.length; i++) { 23 | totalScore += data.documents[i].score; 24 | } 25 | resolve(totalScore / data.documents.length); 26 | }, (err) => { 27 | reject(err); 28 | }); 29 | }); 30 | } 31 | } 32 | exports.SentimentHelper = SentimentHelper; 33 | //# sourceMappingURL=sentimentHelper.js.map -------------------------------------------------------------------------------- /src/server/helpers/sentimentHelper.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"sentimentHelper.js","sourceRoot":"","sources":["sentimentHelper.ts"],"names":[],"mappings":";;AAAA,OAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE,CAAC;AAG3B,6CAA0C;AAE1C;IAEI,MAAM,CAAC,iBAAiB,CAAC,IAAmB;QACxC,MAAM,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM;YAE/B,IAAI,MAAM,GAAG;gBACT,2BAA2B,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW;gBACpD,cAAc,EAAE,kBAAkB;gBAClC,QAAQ,EAAE,kBAAkB;aAC/B,CAAA;YAGD,IAAI,OAAO,GAAG,EAAC,SAAS,EAAE,EAAE,EAAC,CAAC;YAC9B,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE;gBAChC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;oBACnB,UAAU,EAAE,IAAI;oBAChB,IAAI,EAAE,CAAC;oBACP,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;iBAClB,CAAC,CAAC;YAGP,uBAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,oCAAoC,EAAE,gCAAgC,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAS;gBAExH,IAAI,UAAU,GAAG,GAAG,CAAC;gBACrB,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;oBAC7C,UAAU,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;gBAC1C,CAAC;gBAGD,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;YAChD,CAAC,EAAE,CAAC,GAAG;gBACH,MAAM,CAAC,GAAG,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAnCD,0CAmCC"} -------------------------------------------------------------------------------- /src/server/helpers/sentimentHelper.ts: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | 3 | import * as https from 'https'; 4 | import { HttpHelper } from './httpHelper'; 5 | 6 | export class SentimentHelper { 7 | // get sentiment score for all strings in the array 8 | static getSentimentScore(text: Array) { 9 | return new Promise((resolve, reject) => { 10 | // set header information, including cognitive services subscription key 11 | let header = { 12 | 'Ocp-Apim-Subscription-Key': process.env.COG_SUB_KEY, 13 | 'Content-Type': 'application/json', 14 | 'Accept': 'application/json' 15 | } 16 | 17 | // prepare the payload for the text analytics service 18 | let payload = {documents: []}; 19 | for (var i = 0; i < text.length; i++) 20 | payload.documents.push({ 21 | "language": "en", 22 | "id": i, 23 | "text": text[i] 24 | }); 25 | 26 | // use the HttpHelper to post the payload and get back sentiment 27 | HttpHelper.postJson(header, 'westus.api.cognitive.microsoft.com', '/text/analytics/v2.0/sentiment', payload).then((data: any) => { 28 | // aggregate the total sentiment score 29 | let totalScore = 0.0; 30 | for (var i = 0; i < data.documents.length; i++) { 31 | totalScore += data.documents[i].score; 32 | } 33 | 34 | // resolve the total score divided by the number of results 35 | resolve(totalScore / data.documents.length); 36 | }, (err) => { 37 | reject(err); 38 | }); 39 | }); 40 | } 41 | } -------------------------------------------------------------------------------- /src/server/server.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | require('dotenv').config(); 4 | const fs = require("fs"); 5 | const path = require("path"); 6 | const expressSession = require("express-session"); 7 | const restify = require("restify"); 8 | const builder = require("botbuilder"); 9 | const AuthHelper_1 = require("./helpers/AuthHelper"); 10 | const searchDialog_1 = require("./dialogs/searchDialog"); 11 | class Server { 12 | run() { 13 | var https_options = { 14 | key: fs.readFileSync(path.join(__dirname, '../etc/ssl/server.key')), 15 | certificate: fs.readFileSync(path.join(__dirname, '../etc/ssl/server.crt')) 16 | }; 17 | const server = restify.createServer(https_options); 18 | const bot = new builder.UniversalBot(new builder.ChatConnector({})); 19 | server.post('/api/messages', bot.connector('*').listen()); 20 | server.listen(process.env.PORT, () => console.log(`${server.name} listening to ${server.url}`)); 21 | server.get('/code', restify.serveStatic({ 22 | 'directory': path.join(__dirname, '../public'), 23 | 'file': 'code.html' 24 | })); 25 | bot.recognizer(new builder.LuisRecognizer(process.env.LUIS_MODEL_URL)); 26 | server.use(restify.queryParser()); 27 | server.use(restify.bodyParser()); 28 | server.use(expressSession({ secret: 'SOME_SECRET', resave: true, saveUninitialized: false })); 29 | const authHelper = new AuthHelper_1.AuthHelper(server, bot); 30 | let dlg = new searchDialog_1.default(authHelper); 31 | bot.dialog('/', [ 32 | function (session, args, next) { 33 | session.send('No intent matched'); 34 | } 35 | ]); 36 | bot.dialog(dlg.id, dlg.waterfall).triggerAction({ matches: dlg.name }); 37 | } 38 | } 39 | exports.Server = Server; 40 | const server = new Server(); 41 | server.run(); 42 | //# sourceMappingURL=server.js.map -------------------------------------------------------------------------------- /src/server/server.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"server.js","sourceRoot":"","sources":["server.ts"],"names":[],"mappings":";;AAAA,OAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE,CAAC;AAE3B,yBAAyB;AACzB,6BAA6B;AAC7B,kDAAkD;AAClD,mCAAmC;AACnC,sCAAsC;AACtC,qDAAgD;AAChD,yDAAkD;AAElD;IACI,GAAG;QAEC,IAAI,aAAa,GAAG;YAChB,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC;YACnE,WAAW,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC;SAC9E,CAAC;QACF,MAAM,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;QACnD,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,YAAY,CAChC,IAAI,OAAO,CAAC,aAAa,CAAC,EAGzB,CAAC,CACL,CAAC;QAGF,MAAM,CAAC,IAAI,CAAC,eAAe,EAAG,GAAG,CAAC,SAAS,CAAC,GAAG,CAA2B,CAAC,MAAM,EAAE,CAAC,CAAC;QACrF,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,IAAI,iBAAiB,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;QAChG,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC;YACpC,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,WAAW,CAAC;YAC9C,MAAM,EAAE,WAAW;SACtB,CAAC,CAAC,CAAC;QAGJ,GAAG,CAAC,UAAU,CAAC,IAAI,OAAO,CAAC,cAAc,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC;QAGvE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;QAClC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QACjC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAiB,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QAC9F,MAAM,UAAU,GAAG,IAAI,uBAAU,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAG/C,IAAI,GAAG,GAAG,IAAI,sBAAY,CAAC,UAAU,CAAC,CAAC;QACvC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE;YACZ,UAAU,OAAO,EAAE,IAAI,EAAE,IAAI;gBACzB,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;YACtC,CAAC;SACJ,CAAC,CAAC;QACH,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC,aAAa,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IAC3E,CAAC;CACJ;AAzCD,wBAyCC;AAED,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;AAE5B,MAAM,CAAC,GAAG,EAAE,CAAC"} -------------------------------------------------------------------------------- /src/server/server.ts: -------------------------------------------------------------------------------- 1 | require('dotenv').config(); 2 | 3 | import * as fs from 'fs'; 4 | import * as path from 'path'; 5 | import * as expressSession from 'express-session'; 6 | import * as restify from 'restify'; 7 | import * as builder from 'botbuilder'; 8 | import {AuthHelper} from './helpers/AuthHelper'; 9 | import searchDialog from './dialogs/searchDialog'; 10 | 11 | export class Server { 12 | run() { 13 | // create the server and initialize the bot 14 | var https_options = { 15 | key: fs.readFileSync(path.join(__dirname, '../etc/ssl/server.key')), 16 | certificate: fs.readFileSync(path.join(__dirname, '../etc/ssl/server.crt')) 17 | }; 18 | const server = restify.createServer(https_options); 19 | const bot = new builder.UniversalBot( 20 | new builder.ChatConnector({ 21 | //appId: process.env.MICROSOFT_APP_ID, 22 | //appPassword: process.env.MICROSOFT_APP_PASSWORD 23 | }) 24 | ); 25 | 26 | // set the bot to listen on /api/messages endpoint 27 | server.post('/api/messages', (bot.connector('*') as builder.ChatConnector).listen()); 28 | server.listen(process.env.PORT, () => console.log(`${server.name} listening to ${server.url}`)); 29 | server.get('/code', restify.serveStatic({ 30 | 'directory': path.join(__dirname, '../public'), 31 | 'file': 'code.html' 32 | })); 33 | 34 | // configure bot to leverage LUIS 35 | bot.recognizer(new builder.LuisRecognizer(process.env.LUIS_MODEL_URL)); 36 | 37 | // create authHelper 38 | server.use(restify.queryParser()); 39 | server.use(restify.bodyParser()); 40 | server.use(expressSession({ secret: 'SOME_SECRET', resave: true, saveUninitialized: false })); 41 | const authHelper = new AuthHelper(server, bot); 42 | 43 | // create dialogs for specific intents 44 | let dlg = new searchDialog(authHelper); 45 | bot.dialog('/', [ 46 | function (session, args, next) { 47 | session.send('No intent matched'); 48 | } 49 | ]); 50 | bot.dialog(dlg.id, dlg.waterfall).triggerAction({ matches: dlg.name }); 51 | } 52 | } 53 | 54 | const server = new Server(); 55 | 56 | server.run(); -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "removeComments": true, 6 | "sourceMap": true 7 | }, 8 | "exclude": [ 9 | "node_modules" 10 | ] 11 | } --------------------------------------------------------------------------------