├── .gitignore ├── .npmignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── api-ai-botkit.js ├── package.json └── samples ├── sample_bot.js └── slack ├── .dockerignore ├── .gitignore ├── BUILD.md ├── Dockerfile ├── LICENSE ├── README.md ├── app.json ├── package.json ├── src └── index.js └── start.sh /.gitignore: -------------------------------------------------------------------------------- 1 | ### Node template 2 | # Logs 3 | logs 4 | *.log 5 | npm-debug.log* 6 | 7 | # Runtime data 8 | pids 9 | *.pid 10 | *.seed 11 | 12 | # Directory for instrumented libs generated by jscoverage/JSCover 13 | lib-cov 14 | 15 | # Coverage directory used by tools like istanbul 16 | coverage 17 | 18 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 19 | .grunt 20 | 21 | # node-waf configuration 22 | .lock-wscript 23 | 24 | # Compiled binary addons (http://nodejs.org/api/addons.html) 25 | build/Release 26 | 27 | # Dependency directory 28 | # https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git 29 | node_modules 30 | 31 | # Created by .ignore support plugin (hsz.mobi) 32 | 33 | *.DS_Store 34 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | examples/ 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement 9 | (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you 12 | own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). 15 | 16 | Follow either of the two links above to access the appropriate CLA and 17 | instructions for how to sign and return it. Once we receive it, we'll be able to 18 | accept your pull requests. 19 | 20 | ## Contributing A Patch 21 | 22 | 1. Submit an issue describing your proposed change to the repo in question. 23 | 1. The repo owner will respond to your issue promptly. 24 | 1. If your proposed change is accepted, and you haven't already done so, sign a 25 | Contributor License Agreement (see details above). 26 | 1. Fork the desired repo, develop and test your code changes. 27 | 1. Ensure that your code adheres to the existing style in the sample to which 28 | you are contributing. Refer to the 29 | [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the 30 | recommended coding standards for this organization. 31 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 32 | 1. Submit a pull request. 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DEPRECATED api-ai-botkit 2 | 3 | | Deprecated | 4 | |-------| 5 | | This Dialogflow client library and Dialogflow API V1 [have been deprecated and will be shut down on October 23th, 2019](https://blog.dialogflow.com/post/migrate-to-dialogflow-api-v2/). Please migrate to Dialogflow API V2 and the [v2 client library](https://cloud.google.com/dialogflow-enterprise/docs/reference/libraries/nodejs) | 6 | 7 | [![npm](https://img.shields.io/npm/v/api-ai-botkit.svg)](https://www.npmjs.com/package/api-ai-botkit) 8 | 9 | Utility lib for creating bots. So far only tested with Slack. 10 | 11 | For usage sample code see `examples/sample_bot.js` 12 | 13 | ## Steps for using lib 14 | 15 | Install library from npm 16 | ```sh 17 | npm install --save api-ai-botkit 18 | ``` 19 | 20 | Import Library 21 | ```js 22 | const apiaibotkit = require('api-ai-botkit'); 23 | ``` 24 | 25 | Create `apiai` object using token from http://api.ai website 26 | ```js 27 | const apiai = apiaibotkit(apiaiToken); 28 | ``` 29 | 30 | Use `apiai` object in `controller.hears` 31 | ```js 32 | controller.hears('.*', ['direct_message', 'direct_mention', 'mention'], function (bot, message) { 33 | apiai.process(message, bot); 34 | }); 35 | ``` 36 | 37 | Implement different reactions to appropriate actions 38 | ```js 39 | apiai 40 | .action('smalltalk.greetings', function (message, resp, bot) { 41 | var responseText = resp.result.fulfillment.speech; 42 | bot.reply(message, responseText); 43 | }) 44 | .action('input.unknown', function (message, resp, bot) { 45 | bot.reply(message, "Sorry, I don't understand"); 46 | }); 47 | ``` 48 | ## License 49 | See [LICENSE](LICENSE). 50 | 51 | ## Terms 52 | Your use of this sample is subject to, and by using or downloading the sample files you agree to comply with, the [Google APIs Terms of Service](https://developers.google.com/terms/). 53 | 54 | This is not an official Google product. 55 | -------------------------------------------------------------------------------- /api-ai-botkit.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 'use strict'; 18 | 19 | const Botkit = require('botkit'); 20 | const apiai = require('apiai'); 21 | 22 | const uuidV4 = require('uuid/v4'); 23 | const Entities = require('html-entities').XmlEntities; 24 | const decoder = new Entities(); 25 | 26 | module.exports = function (apiaiToken) { 27 | return createApiAiProcessing(apiaiToken); 28 | }; 29 | 30 | function isDefined(obj) { 31 | if (typeof obj == 'undefined') { 32 | return false; 33 | } 34 | 35 | if (!obj) { 36 | return false; 37 | } 38 | 39 | return obj != null; 40 | } 41 | 42 | function createApiAiProcessing(token) { 43 | let worker = {}; 44 | 45 | worker.apiaiService = apiai(token); 46 | worker.sessionIds = {}; 47 | 48 | worker.actionCallbacks = {}; 49 | worker.allCallback = []; 50 | 51 | worker.action = function (action, callback) { 52 | if (worker.actionCallbacks[action]) { 53 | worker.actionCallbacks[action].push(callback); 54 | } else { 55 | worker.actionCallbacks[action] = [callback]; 56 | } 57 | 58 | return worker; 59 | }; 60 | 61 | worker.all = function (callback) { 62 | worker.allCallback.push(callback); 63 | return worker; 64 | }; 65 | 66 | 67 | worker.process = function (message, bot) { 68 | try { 69 | 70 | if (isDefined(message.text)) { 71 | let userId = message.user; 72 | 73 | let requestText = decoder.decode(message.text); 74 | requestText = requestText.replace("’", "'"); 75 | 76 | if (isDefined(bot.identity) && isDefined(bot.identity.id)) { 77 | // it seems it is Slack 78 | 79 | if (message.user == bot.identity.id) { 80 | // message from bot can be skipped 81 | return; 82 | } 83 | 84 | if (message.text.indexOf("<@U") == 0 && message.text.indexOf(bot.identity.id) == -1) { 85 | // skip other users direct mentions 86 | return; 87 | } 88 | 89 | let botId = '<@' + bot.identity.id + '>'; 90 | if (requestText.indexOf(botId) > -1) { 91 | requestText = requestText.replace(botId, ''); 92 | } 93 | 94 | userId = message.channel; 95 | } 96 | 97 | if (!(userId in worker.sessionIds)) { 98 | worker.sessionIds[userId] = uuidV4(); 99 | } 100 | 101 | let request = worker.apiaiService.textRequest(requestText, 102 | { 103 | sessionId: worker.sessionIds[userId], 104 | originalRequest: { 105 | data: message, 106 | source: "api-ai-botkit" 107 | } 108 | }); 109 | 110 | request.on('response', (response) => { 111 | 112 | worker.allCallback.forEach((callback) => { 113 | callback(message, response, bot); 114 | }); 115 | 116 | if (isDefined(response.result)) { 117 | let action = response.result.action; 118 | 119 | if (isDefined(action)) { 120 | if (worker.actionCallbacks[action]) { 121 | worker.actionCallbacks[action].forEach((callback) => { 122 | callback(message, response, bot); 123 | }); 124 | } 125 | } 126 | } 127 | }); 128 | 129 | request.on('error', (error) => { 130 | console.error(error); 131 | }); 132 | 133 | request.end(); 134 | } 135 | 136 | } catch (err) { 137 | console.error(err); 138 | } 139 | }; 140 | 141 | return worker; 142 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-ai-botkit", 3 | "version": "1.1.1", 4 | "description": "Utility lib for creating Slack bots", 5 | "main": "api-ai-botkit.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/api-ai/api-ai-botkit.git" 9 | }, 10 | "bugs": { 11 | "url": "https://github.com/api-ai/api-ai-botkit/issues" 12 | }, 13 | "scripts": { 14 | "test": "echo \"Error: no test specified\" && exit 1" 15 | }, 16 | "keywords": [ 17 | "apiai", 18 | "bot" 19 | ], 20 | "author": "Danil Skachkov (https://api.ai)", 21 | "license": "Apache-2.0", 22 | "dependencies": { 23 | "apiai": "^3.0.3", 24 | "botkit": "^0.4.9", 25 | "html-entities": "^1.2.0", 26 | "uuid": "^3.0.1" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /samples/sample_bot.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 'use strict'; 18 | 19 | const Botkit = require('botkit'); 20 | const apiaibotkit = require('../api-ai-botkit'); 21 | 22 | const slackToken = process.env.SLACK_TOKEN; 23 | const apiaiToken = process.env.APIAI_TOKEN; 24 | 25 | const apiai = apiaibotkit(apiaiToken); 26 | const controller = Botkit.slackbot(); 27 | 28 | controller.hears('.*', ['direct_message', 'direct_mention', 'mention'], function (bot, message) { 29 | apiai.process(message, bot); 30 | }); 31 | 32 | controller.on('reaction_added', function (bot, message) { 33 | console.log(message); 34 | }); 35 | 36 | apiai.all(function (message, resp, bot) { 37 | console.log(resp.result.action); 38 | }); 39 | 40 | apiai 41 | .action('smalltalk.greetings', function (message, resp, bot) { 42 | let responseText = resp.result.fulfillment.speech; 43 | bot.reply(message, responseText); 44 | }) 45 | .action('input.unknown', function (message, resp, bot) { 46 | bot.reply(message, "Sorry, I don't understand"); 47 | }); 48 | 49 | controller.spawn({ 50 | token: slackToken 51 | }).startRTM(); -------------------------------------------------------------------------------- /samples/slack/.dockerignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | node_modules/ 3 | *.iml 4 | samples/ -------------------------------------------------------------------------------- /samples/slack/.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | node_modules/ 3 | api-ai-slack-bot.iml 4 | npm-debug.log -------------------------------------------------------------------------------- /samples/slack/BUILD.md: -------------------------------------------------------------------------------- 1 | # Build instructions 2 | 3 | To build 4 | 5 | ```sh 6 | build -t xvir/api-ai-slack-bot . 7 | ``` 8 | 9 | To push 10 | ```sh 11 | push xvir/api-ai-slack-bot 12 | ``` -------------------------------------------------------------------------------- /samples/slack/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:5.10 2 | 3 | MAINTAINER xVir 4 | 5 | RUN mkdir -p /usr/app/src 6 | WORKDIR /usr/app 7 | COPY . /usr/app 8 | 9 | RUN npm install 10 | RUN chmod +x start.sh 11 | 12 | CMD ["./start.sh"] 13 | -------------------------------------------------------------------------------- /samples/slack/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /samples/slack/README.md: -------------------------------------------------------------------------------- 1 | # Api.ai Slack Integration 2 | 3 | ## Overview 4 | 5 | Api.ai Slack integration allows you to create Slack bots with natural language understanding based on Api.ai technology. 6 | 7 | [![Deploy to Heroku](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) 8 | 9 | To launch a bot, you’ll need the Linux OS. To launch it in other operating systems, use [Docker Toolbox](https://www.docker.com/products/docker-toolbox). 10 | 11 | Api.ai documentation: 12 | 13 | - [How to create an Api.ai agent](https://docs.api.ai/docs/get-started#step-1-create-agent) 14 | - [How to obtain Api.ai authentication keys](https://docs.api.ai/docs/authentication) 15 | 16 | You’ll need 2 keys: 17 | 18 | - Client access token for Api.ai 19 | - Slack bot API token 20 | 21 | To obtain a Slack bot API token, create a new bot integration here: https://slack.com/apps/A0F7YS25R-bots. 22 | 23 | ## Bot Launch 24 | 25 | To launch the bot, use one of the following commands: 26 | 27 | **For background launch mode (-d parameter):** 28 | 29 | ```sh 30 | docker run -d --name slack_bot \ 31 | -e accesstoken="api.ai access key" \ 32 | -e slackkey="slack bot key" \ 33 | speaktoit/api-ai-slack-bot 34 | ``` 35 | 36 | **For interactive launch mode (-it parameter):** 37 | 38 | ```sh 39 | docker run -it --name slack_bot \ 40 | -e accesstoken="Api.ai client access key" \ 41 | -e slackkey="Slack bot user key" \ 42 | speaktoit/api-ai-slack-bot 43 | ``` 44 | 45 | To stop the bot from running in the interactive mode, press CTRL+C. 46 | 47 | In the background mode, you can control the bot’s state via simple commands: 48 | 49 | 50 | - `docker start slack_bot` 51 | - `docker stop slack_bot`, 52 | 53 | where `slack_bot` is the container name from the `run` command. 54 | 55 | ## Custom Bot Launch 56 | 57 | If you want to customize your bot behavior, follow the steps below. 58 | 59 | 1. Clone the repository https://github.com/api-ai/api-ai-slack-bot 60 | 61 | 2. Change the code to `index.js` 62 | 63 | 3. In the Docker, use the `run` command specifying the full path to the directory containing the `index.js` file: 64 | 65 | ```sh 66 | docker run -d --name slack_bot \ 67 | -e accesstoken="Api.ai client token" \ 68 | -e slackkey="Slack bot user key" \ 69 | -v /full/path/to/your/src:/usr/app/src \ 70 | speaktoit/api-ai-slack-bot 71 | ``` 72 | 73 | ## Code Notes 74 | 75 | Bot implementation is based on the Slack Botkit: https://github.com/howdyai/botkit. 76 | 77 | Message processing is done by the following code: 78 | 79 | ```javascript 80 | controller.hears(['.*'],['direct_message','direct_mention','mention', 'ambient'], function(bot,message) { 81 | console.log(message.text); 82 | if (message.type == "message") { 83 | if (message.user == bot.identity.id) { 84 | // message from bot can be skipped 85 | } 86 | else { 87 | var requestText = message.text; 88 | var channel = message.channel; 89 | if (!(channel in sessionIds)) { 90 | sessionIds[channel] = uuid.v1(); 91 | } 92 | var request = apiAiService.textRequest(requestText, { sessionId: sessionIds[channel] }); 93 | request.on('response', function (response) { 94 | console.log(response); 95 | if (response.result) { 96 | var responseText = response.result.fulfillment.speech; 97 | if (responseText) { 98 | bot.reply(message, responseText); 99 | } 100 | } 101 | }); 102 | request.on('error', function (error) { 103 | console.log(error); 104 | }); 105 | request.end(); 106 | } 107 | } 108 | }); 109 | ``` 110 | 111 | This code extracts the text from each message: 112 | 113 | `var requestText = message.text;` 114 | 115 | And sends it to Api.ai: 116 | 117 | `var request = apiAiService.textRequest(requestText, { sessionId: sessionIds[channel] });` 118 | 119 | If a non-empty response is received from Api.ai, the bot will respond with the received text: 120 | 121 | `bot.reply(message, responseText);` 122 | -------------------------------------------------------------------------------- /samples/slack/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "API.AI with Slack integration", 3 | "description": "Api.ai Slack integration allows you to create Slack bots with natural language understanding based on Api.ai technology.", 4 | "repository": "https://github.com/api-ai/api-ai-slack-bot", 5 | "logo": "https://console.api.ai/api-client/assets/img/logo-black.png", 6 | "keywords": ["api.ai", "slack", "natural language"], 7 | "env": { 8 | "accesstoken": { 9 | "description": "Client access token for Api.ai", 10 | "value": "" 11 | }, 12 | "slackkey": { 13 | "description": "Slack bot user API token", 14 | "value": "" 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /samples/slack/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-ai-slack-bot", 3 | "version": "1.0.0", 4 | "description": "API.AI Slack Bot", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "start": "node src/index.js", 8 | "test": "echo \"Error: no test specified\" && exit 1" 9 | }, 10 | "author": "Danil Skachkov (https://api.ai)", 11 | "license": "Apache-2.0", 12 | "dependencies": { 13 | "apiai": "^2.0.7", 14 | "async": "^2.0.1", 15 | "botkit": "0.0.12", 16 | "html-entities": "^1.2.0", 17 | "node-uuid": "^1.4.7" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /samples/slack/src/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | // Module must be started with environment variables 19 | // 20 | // accesskey="api.ai client access key" 21 | // slackkey="slack bot key" 22 | // 23 | 24 | 'use strict'; 25 | 26 | const Botkit = require('botkit'); 27 | 28 | const apiai = require('apiai'); 29 | const uuid = require('node-uuid'); 30 | const http = require('http'); 31 | 32 | const Entities = require('html-entities').XmlEntities; 33 | const decoder = new Entities(); 34 | 35 | const apiAiAccessToken = process.env.accesstoken; 36 | const slackBotKey = process.env.slackkey; 37 | 38 | const apiAiService = apiai(apiAiAccessToken); 39 | 40 | const sessionIds = new Map(); 41 | 42 | const controller = Botkit.slackbot({ 43 | debug: false 44 | //include "log: false" to disable logging 45 | }); 46 | 47 | var bot = controller.spawn({ 48 | token: slackBotKey 49 | }).startRTM(); 50 | 51 | controller.on('rtm_close', function (bot, err) { 52 | console.log('** The RTM api just closed, reason', err); 53 | 54 | try { 55 | 56 | // sometimes connection closing, so, we should restart bot 57 | if (bot.doNotRestart != true) { 58 | let token = bot.config.token; 59 | console.log('Trying to restart bot ' + token); 60 | 61 | restartBot(bot); 62 | } 63 | 64 | } catch (err) { 65 | console.error('Restart bot failed', err); 66 | } 67 | }); 68 | 69 | function restartBot(bot) { 70 | bot.startRTM(function (err) { 71 | if (err) { 72 | console.error('Error restarting bot to Slack:', err); 73 | } 74 | else { 75 | let token = bot.config.token; 76 | console.log('Restarted bot for %s', token); 77 | } 78 | }); 79 | } 80 | 81 | function isDefined(obj) { 82 | if (typeof obj == 'undefined') { 83 | return false; 84 | } 85 | 86 | if (!obj) { 87 | return false; 88 | } 89 | 90 | return obj != null; 91 | } 92 | 93 | controller.hears(['.*'], ['direct_message', 'direct_mention', 'mention', 'ambient'], (bot, message) => { 94 | try { 95 | if (message.type == 'message') { 96 | if (message.user == bot.identity.id) { 97 | // message from bot can be skipped 98 | } 99 | else if (message.text.indexOf("<@U") == 0 && message.text.indexOf(bot.identity.id) == -1) { 100 | // skip other users direct mentions 101 | } 102 | else { 103 | 104 | let requestText = decoder.decode(message.text); 105 | requestText = requestText.replace("’", "'"); 106 | 107 | let channel = message.channel; 108 | let messageType = message.event; 109 | let botId = '<@' + bot.identity.id + '>'; 110 | let userId = message.user; 111 | 112 | console.log(requestText); 113 | console.log(messageType); 114 | 115 | if (requestText.indexOf(botId) > -1) { 116 | requestText = requestText.replace(botId, ''); 117 | } 118 | 119 | if (!sessionIds.has(channel)) { 120 | sessionIds.set(channel, uuid.v1()); 121 | } 122 | 123 | console.log('Start request ', requestText); 124 | let request = apiAiService.textRequest(requestText, 125 | { 126 | sessionId: sessionIds.get(channel), 127 | contexts: [ 128 | { 129 | name: "generic", 130 | parameters: { 131 | slack_user_id: userId, 132 | slack_channel: channel 133 | } 134 | } 135 | ] 136 | }); 137 | 138 | request.on('response', (response) => { 139 | console.log(response); 140 | 141 | if (isDefined(response.result)) { 142 | let responseText = response.result.fulfillment.speech; 143 | let responseData = response.result.fulfillment.data; 144 | 145 | if (isDefined(responseData) && isDefined(responseData.slack)) { 146 | replyWithData(bot, message, responseData); 147 | } else if (isDefined(responseText)) { 148 | replyWithText(bot, message, responseText); 149 | } 150 | 151 | } 152 | }); 153 | 154 | request.on('error', (error) => console.error(error)); 155 | request.end(); 156 | } 157 | } 158 | } catch (err) { 159 | console.error(err); 160 | } 161 | }); 162 | 163 | function replyWithText(bot, message, responseText) { 164 | bot.reply(message, responseText, (err, resp) => { 165 | if (err) { 166 | console.error(err); 167 | } 168 | }); 169 | } 170 | 171 | function replyWithData(bot, message, responseData) { 172 | try { 173 | bot.reply(message, responseData.slack); 174 | } catch (err) { 175 | bot.reply(message, err.message); 176 | } 177 | } 178 | 179 | 180 | //Create a server to prevent Heroku kills the bot 181 | const server = http.createServer((req, res) => res.end()); 182 | 183 | //Lets start our server 184 | server.listen((process.env.PORT || 5000), () => console.log("Server listening")); -------------------------------------------------------------------------------- /samples/slack/start.sh: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Google Inc. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | #!/usr/bin/env bash 16 | 17 | node src/index.js --------------------------------------------------------------------------------