├── .babelrc ├── .gitignore ├── .npmignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── _config.yml ├── circle.yml ├── dist └── index.js ├── lib └── index.js ├── package.json └── test └── test_welcome.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["es2015", "stage-2"], 3 | "plugins": [] 4 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.DS_Store 3 | npm-debug.log -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | *.DS_Store 3 | npm-debug.log -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ospo@sfeir.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 |

GAS: Google Assistant Server 5 | 6 |

7 |

A Node.js server for your Google Assistant (and Google Home).

8 | 9 | 10 | 11 | ### Get it from NPM 12 | 13 | ```bash 14 | npm i -S @manekinekko/google-actions-server 15 | ``` 16 | 17 | ### Get it from Yarn 18 | 19 | ```bash 20 | $ yarn add @manekinekko/google-actions-server 21 | ``` 22 | ## How to use it 23 | 24 | See the [GAS Starter](https://github.com/manekinekko/google-actions-starter) for more details. 25 | 26 | ## GAS API 27 | 28 | Here is the simplest guide in order to use GAS: 29 | 30 | ```javascript 31 | import { ActionServer } from '@manekinekko/google-actions-server'; 32 | 33 | const agent = new ActionServer(); 34 | 35 | agent.welcome((assistant) => { 36 | agent.ask('Welcome Home. How can I help'); 37 | }); 38 | 39 | agent.intent(ActionServer.intent.action.TEXT, (assistant) => { 40 | 41 | // reads the user's request 42 | const userInput = assistant.getRawInput(); 43 | 44 | }) 45 | 46 | // start listening for commands (on port 8080) 47 | agent.listen(); 48 | 49 | ``` 50 | 51 | ### Intents 52 | 53 | Available intents are: 54 | 55 | #### ActionServer.intent.action.MAIN 56 | 57 | This intent is triggered when users invoke your action by name, such as "talk to ". This intent si required for every action package. 58 | 59 | #### ActionServer.intent.action.TEXT 60 | 61 | This intent is triggered when users speak input and you receive the input as a request to your fulfillment endpoint. 62 | 63 | #### ActionServer.intent.action.PERMISSION 64 | 65 | Triggered if Google Assistant needs to ask the user for more permissions (not implemented yet by GAS) 66 | 67 | ### ActionServer 68 | 69 | #### ActionServer(port = 8080) 70 | 71 | Create an HTTP server and set it to listen on port `port` (default: 8080). 72 | 73 | ### Agent 74 | 75 | Calling `new ActionServer()` will return an `Agent` instance, which exposes the following API: 76 | 77 | #### agent.intent(name, callback) 78 | 79 | Register a `callback` with an intent of type `ActionServer.intent.action.*`. When invoked, the `callback` function receives an instance of **[ActionsSdkAssistant](https://developers.google.com/actions/reference/ActionsSdkAssistant)**. For instance: 80 | 81 | ```javascript 82 | agent.welcome(ActionServer.intent.action.TEXT, (assistant) => { 83 | // assistant 84 | }); 85 | ``` 86 | 87 | #### agent.welcome(callback) 88 | 89 | Register a `callback` with the **ActionServer.intent.action.MAIN** intent. This is the same as: 90 | 91 | ``` 92 | agent.intent(ActionServer.intent.action.MAIN, (assistant) => { 93 | // assistant 94 | }); 95 | ``` 96 | 97 | Register a `callback` with the **ActionServer.intent.action.MAIN** intent. This is the same as: 98 | 99 | #### agent.listen() 100 | 101 | Starts the GAS server on port `8080` (the default port). This method **must be** called after you have registered all of your intents. 102 | 103 | #### agent.ask(message) 104 | 105 | A convenient method that abstracts away the `assistant.ask()` configuration. Typically, with `assistant.ask()` you have to: 106 | 107 | ```javascript 108 | const inputPrompt = assistant.buildInputPrompt(isSsml, message, noInputs); 109 | assistant.data = previousState; 110 | assistant.ask(inputPrompt); 111 | ``` 112 | 113 | With `agent.ask()`, you can just pass it the message: 114 | 115 | ```javascript 116 | agent.ask(message); 117 | ``` 118 | 119 | Of course, you can still call `assistant.ask()` if you want to provide a configuration. 120 | 121 | #### setGreetings(greetings) 122 | 123 | A convenient method to set a list of greeting messages that you will play randomly to the user. 124 | 125 | #### getRandomGreeting() 126 | 127 | A convenient method to get a random greeting message set using `agent.setGreetings()`. 128 | 129 | #### randomGreeting() 130 | 131 | A convenient method that will trigger a random greeting message for you. 132 | 133 | #### setConversationMessages(conversationMessages) 134 | 135 | A convenient method to set a list of random conversations asking the user for another query. For instant: `How can I help?` or `Do you have another request?`. 136 | 137 | #### getRandomConversationMessage() 138 | 139 | A convenient method to get a random conversation message set using `agent.setConversationMessages()`. 140 | 141 | #### agent.train(dataSetKey, data, fields = ['data'])) 142 | 143 | This method is used to provide a set of data that will be used by `agent.matchUserRequest()`. This could be the data that will be used by the assistant to interact with the user, or a set of Hot Words such as: 144 | 145 | ```javascript 146 | this.agent.train('hot_words', [ 147 | 'what time is it?', 148 | 'tell me the time', 149 | `what's the time`, 150 | //... 151 | ]); 152 | ``` 153 | 154 | Here is another use case, let's say you want to provide a decision list: 155 | 156 | ```javascript 157 | const decisionList = [ 158 | { 159 | 'scenario': 'I have one existing Observable, and I want to change each emitted value to be a constant value', 160 | 'operator': 'mapTo' 161 | }, 162 | { 163 | 'scenario': 'I have one existing Observable, and I want to change each emitted value to be a value calculated through a formula', 164 | 'operator': 'map' 165 | }, 166 | ... 167 | ]; 168 | ``` 169 | 170 | You would then provide it to GAS like so: 171 | 172 | ```javascript 173 | const fields = ['operator', 'scenario']; 174 | this.agent.train('decision_list', decisionList, fields); 175 | ``` 176 | 177 | Please note that the `fields` option has been provided since the items inside this decision list are stored in key/value pairs. 178 | 179 | **IMPORTANT: the first field (in the sample above: `operator`) will be used as the reference field: the field that will be returned by `agent.matchUserRequest()`.** 180 | 181 | #### matchUserRequest(dataSetKey, rawInput, responseCallback, lookupOptions = {}) 182 | 183 | **NOTE:** GAS uses [elasticlunr](https://github.com/weixsong/elasticlunr.js) that performs the [Full-Text Search](https://en.wikipedia.org/wiki/Full-text_search) technique to retrieve the matched documents. 184 | 185 | Use this method to match the user's input with a set of data provided in `agent.train()`. 186 | 187 | For instance, let's say you have the `decisionList` list from the example above; in order to find a matched document you would call `agent.matchUserRequest()` like so: 188 | 189 | ```javascript 190 | // get the user's input 191 | const rawInput = assistant.getRawInput(); 192 | 193 | // provide a lookup configuration (see below) 194 | const lookupOptions = {...}; 195 | 196 | // the callback that will be called 197 | const responseCallback = (foundDocuments, rawInput) => { ... }; 198 | 199 | // run the search operation 200 | const matchedDocuments = this.agent.matchUserRequest('decision_list', rawInput, responseCallback, lookupOptions); 201 | ``` 202 | 203 | The `matchedDocuments` would then contain the matched documents based on the `rawInput` string. In some case you may get false-positives, documents that are not relevant to the intended search question. 204 | In this case, you may provide a `lookupOptions` object in order to configure/tweak the search operation. 205 | 206 | **NOTE:** if no documents are found, an empty array is returned. 207 | 208 | ##### threshold 209 | 210 | You can provide the `threshold` property to filter out the false-positives. `threshold` can be either a Number or a Function. 211 | 212 | Using a number: 213 | 214 | ```javascript 215 | const lookupOptions = { 216 | threshold: 0.6 217 | }; 218 | ``` 219 | 220 | When using a function, it will be provided with the current entry from the data set. You can access the `score` property on that entry: 221 | 222 | ```javascript 223 | const lookupOptions = { 224 | threshold: entry => { 225 | return entry.score > 0.6; 226 | } 227 | }; 228 | ``` 229 | 230 | ##### fields 231 | 232 | The fields property is a [elasticlunr configuration query](https://github.com/weixsong/elasticlunr.js#52-configuration-query). For instance, we could provide the following configuration for the example from above: 233 | 234 | ```javascript 235 | const lookupOptions = { 236 | fields: { 237 | scenario: { 238 | boost: 2, 239 | bool: 'AND', 240 | expand: true 241 | }, 242 | operator: { 243 | boost: 1 244 | } 245 | } 246 | }; 247 | ``` 248 | 249 | See [elasticlunr configuration query](https://github.com/weixsong/elasticlunr.js#52-configuration-query) for more details. 250 | 251 | #### fetch(url, responseCallback, useCache = true) 252 | 253 | A convenient method to fetch a remote document. Useful if you want to get more information from a remote website. For instance: 254 | 255 | ```javascript 256 | agent.fetch(url, (error, content) => { 257 | if (error) { 258 | console.error(error); 259 | } 260 | else { 261 | console.log(content); 262 | } 263 | }); 264 | 265 | ``` 266 | 267 | 268 | # Disclaimer 269 | 270 | The current implementation is still a POC. It's obviously missing lots of features. Please open issues to discuss any feature you want to be added, submit suggestions, or anything else... 271 | All contributions are welcome ;) 272 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | machine: 2 | node: 3 | version: 7.2.0 4 | -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | Object.defineProperty(exports, "__esModule", { 4 | value: true 5 | }); 6 | exports.ActionServer = undefined; 7 | 8 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; 9 | 10 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 11 | 12 | var _actionsOnGoogle = require('actions-on-google'); 13 | 14 | var _express = require('express'); 15 | 16 | var _express2 = _interopRequireDefault(_express); 17 | 18 | var _bodyParser = require('body-parser'); 19 | 20 | var _bodyParser2 = _interopRequireDefault(_bodyParser); 21 | 22 | var _elasticlunr = require('elasticlunr'); 23 | 24 | var _elasticlunr2 = _interopRequireDefault(_elasticlunr); 25 | 26 | var _request = require('request'); 27 | 28 | var _request2 = _interopRequireDefault(_request); 29 | 30 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 31 | 32 | function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 33 | 34 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 35 | 36 | process.env.DEBUG = 'google-actions-server:*'; 37 | 38 | var l = function l() { 39 | for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { 40 | args[_key] = arguments[_key]; 41 | } 42 | 43 | return console.log.apply(console, args); 44 | }; 45 | 46 | var ActionServer = exports.ActionServer = function () { 47 | function ActionServer() { 48 | var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8080; 49 | 50 | _classCallCheck(this, ActionServer); 51 | 52 | this.actionsMap = new Map(); 53 | this.app = (0, _express2.default)(); 54 | this.app.set('port', process.env.PORT || port); 55 | this.app.use(_bodyParser2.default.json({ type: 'application/json' })); 56 | 57 | this.request = _request2.default; // node module 58 | 59 | // phrase random (incremental) counter 60 | this.conversationMessagesCounter = 0; 61 | this.conversationMessages = []; 62 | this.greetings = []; 63 | this.dataSetIndex = {}; 64 | this.requestCache = {}; 65 | } 66 | 67 | _createClass(ActionServer, [{ 68 | key: 'welcome', 69 | value: function welcome(callback) { 70 | this.intent(ActionServer.intent.action.MAIN, callback); 71 | } 72 | }, { 73 | key: 'intent', 74 | value: function intent(key, callback) { 75 | this.actionsMap.set(key, callback.bind(this)); 76 | } 77 | }, { 78 | key: 'setGreetings', 79 | value: function setGreetings(greetings) { 80 | if (Array.isArray(greetings) === false) { 81 | throw new Error('Greeting messages must be an array'); 82 | return false; 83 | } 84 | 85 | this.greetings = greetings; 86 | } 87 | }, { 88 | key: 'getRandomGreeting', 89 | value: function getRandomGreeting() { 90 | return this.greetings[Math.random() * this.greetings.length - 1 | 0]; 91 | } 92 | }, { 93 | key: 'randomGreeting', 94 | value: function randomGreeting() { 95 | this.ask(this.getRandomGreeting()); 96 | } 97 | }, { 98 | key: 'setConversationMessages', 99 | value: function setConversationMessages(conversationMessages) { 100 | if (Array.isArray(conversationMessages) === false) { 101 | throw new Error('"Next Questions" messages must be an array'); 102 | return false; 103 | } 104 | 105 | this.conversationMessages = conversationMessages; 106 | } 107 | }, { 108 | key: 'getRandomConversationMessage', 109 | value: function getRandomConversationMessage() { 110 | var messageIndex = this.conversationMessagesCounter++ % (this.conversationMessages.length - 1) || 0; 111 | return this.conversationMessages[messageIndex]; 112 | } 113 | }, { 114 | key: 'train', 115 | value: function train(dataSetKey, data) { 116 | var _this = this; 117 | 118 | var fields = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ['data']; 119 | 120 | 121 | if (!dataSetKey) { 122 | throw new Error('The "dataSetKey" parameter in "train()" is missing.'); 123 | return false; 124 | } 125 | 126 | if (Array.isArray(data) === false) { 127 | throw new Error('The "data" parameter in "train()" is missing.'); 128 | return false; 129 | } 130 | 131 | this.dataSetIndex[dataSetKey] = { 132 | __raw: { 133 | data: data, 134 | fields: fields 135 | }, 136 | __index: (0, _elasticlunr2.default)(function () { 137 | var lunr = this; 138 | 139 | // if the user has provided a custom schema, use it. 140 | // otherwise use the default schema: "data" 141 | var refField = fields[0]; 142 | lunr.setRef(refField); 143 | fields.map(function (field) { 144 | lunr.addField(field); 145 | }); 146 | lunr.saveDocument(false); 147 | }) 148 | }; 149 | 150 | data.map(function (key) { 151 | if ((typeof key === 'undefined' ? 'undefined' : _typeof(key)) !== 'object') { 152 | key = { 153 | 'data': key 154 | }; 155 | } 156 | _this.dataSetIndex[dataSetKey].__index.addDoc(key); 157 | }); 158 | } 159 | }, { 160 | key: 'matchUserRequest', 161 | value: function matchUserRequest(dataSetKey, rawInput, responseCallback) { 162 | var lookupOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; 163 | 164 | 165 | if (!dataSetKey) { 166 | throw new Error('The "dataSetKey" parameter in "matchUserRequest()" is missing.'); 167 | return false; 168 | } 169 | 170 | if (!this.dataSetIndex || !this.dataSetIndex[dataSetKey]) { 171 | throw new Error('"' + dataSetKey + '" entry was not initialized. Call "train(\'' + dataSetKey + '\', hotWords)" to train a set of data.'); 172 | return false; 173 | } 174 | 175 | var dataSet = this.dataSetIndex[dataSetKey]; 176 | var refField = dataSet.__raw.fields[0]; 177 | 178 | var queryTimeBoosting = { 179 | expand: false, 180 | fields: _defineProperty({}, refField, { 181 | expand: false 182 | }) 183 | }; 184 | if (lookupOptions.fields) { 185 | queryTimeBoosting.fields = lookupOptions.fields; 186 | } 187 | 188 | var filterByScore = function filterByScore(d) { 189 | return true; 190 | }; // allow all scores 191 | if (lookupOptions.threshold) { 192 | if (typeof lookupOptions.threshold === 'number') { 193 | filterByScore = function filterByScore(d) { 194 | return d.score > parseFloat(lookupOptions.threshold); 195 | }; 196 | } else if (typeof lookupOptions.threshold === 'function') { 197 | filterByScore = lookupOptions.threshold; 198 | } else { 199 | throw new Error('The "threshold" parameter in lookups must either a function or a number.'); 200 | return false; 201 | } 202 | } 203 | 204 | var found = dataSet.__index.search(rawInput, queryTimeBoosting); 205 | 206 | var fileredResult = found.sort(function (d1, d2) { 207 | return d1.score >= d2.score; 208 | }).filter(filterByScore).map(function (d) { 209 | return d.ref; 210 | }); 211 | 212 | if (responseCallback) { 213 | responseCallback(fileredResult, rawInput); 214 | } 215 | return fileredResult; 216 | } 217 | 218 | // request remote http URL 219 | 220 | }, { 221 | key: 'fetch', 222 | value: function fetch(url, responseCallback) { 223 | var useCache = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; 224 | 225 | 226 | if (!url) { 227 | throw new Error('The "url" parameter is missing'); 228 | return false; 229 | } else if (!responseCallback) { 230 | console.warn('It seems you did not provide a callback when requesting "' + url + '"'); 231 | } 232 | 233 | var urlSymbol = Symbol(url); 234 | 235 | if (useCache) { 236 | var cachedResponse = this.requestCache[urlSymbol]; 237 | if (cachedResponse) { 238 | responseCallback(null, cachedResponse); 239 | return cachedResponse; 240 | } else { 241 | return this._doRequest(url, responseCallback); 242 | } 243 | } else { 244 | return this._doRequest(url, responseCallback); 245 | } 246 | return null; 247 | } 248 | }, { 249 | key: '_doRequest', 250 | value: function _doRequest(url, responseCallback) { 251 | var _this2 = this; 252 | 253 | var urlSymbol = Symbol(url); 254 | 255 | return this.request(url, function (error, response, html) { 256 | if (!error && response.statusCode == 200) { 257 | 258 | _this2.requestCache[urlSymbol] = {}; 259 | if (html) { 260 | _this2.requestCache[urlSymbol] = html; 261 | } else { 262 | console.warn('Response from "' + url + '" was empty.'); 263 | } 264 | responseCallback(null, html); 265 | } else { 266 | responseCallback(error, null); 267 | } 268 | }); 269 | } 270 | 271 | // a convenient method to abstract the assistant "ask" process 272 | 273 | }, { 274 | key: 'ask', 275 | value: function ask(message) { 276 | var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 277 | 278 | var inputPrompt = this.assistant.buildInputPrompt(true, message, ['Sorry']); 279 | this.assistant.data = data; 280 | this.assistant.ask(inputPrompt); 281 | } 282 | 283 | /** 284 | * @todo 285 | */ 286 | 287 | }, { 288 | key: 'requestNamePermission', 289 | value: function requestNamePermission(context) { 290 | // assistant.isPermissionGranted() 291 | var permission = this.assistant.SupportedPermissions.NAME; 292 | this.assistant.askForPermission(content, permission); 293 | } 294 | }, { 295 | key: '_handleRequest', 296 | value: function _handleRequest() { 297 | var _this3 = this; 298 | 299 | this.app.post('/', function (request, response) { 300 | _this3.assistant = new _actionsOnGoogle.ActionsSdkAssistant({ request: request, response: response }); 301 | _this3.assistant.handleRequest(_this3.actionsMap); 302 | }); 303 | } 304 | }, { 305 | key: 'listen', 306 | value: function listen() { 307 | this._handleRequest(); 308 | var server = this.app.listen(this.app.get('port'), function () { 309 | console.log('App listening on port %s', server.address().port); 310 | console.log('Press Ctrl+C to quit.'); 311 | }); 312 | return server; 313 | } 314 | }]); 315 | 316 | return ActionServer; 317 | }(); 318 | 319 | ActionServer.intent = { 320 | action: { 321 | MAIN: 'assistant.intent.action.MAIN', 322 | TEXT: 'assistant.intent.action.TEXT', 323 | PERMISSION: 'assistant.intent.action.PERMISSION' 324 | } 325 | }; 326 | ; -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.env.DEBUG = 'google-actions-server:*'; 4 | 5 | const l = (...args) => console.log.apply(console, args); 6 | 7 | import { ActionsSdkAssistant } from 'actions-on-google'; 8 | import express from 'express'; 9 | import bodyParser from 'body-parser'; 10 | import elasticlunr from 'elasticlunr'; 11 | import request from 'request'; 12 | 13 | export class ActionServer { 14 | 15 | static intent = { 16 | action: { 17 | MAIN: 'assistant.intent.action.MAIN', 18 | TEXT: 'assistant.intent.action.TEXT', 19 | PERMISSION: 'assistant.intent.action.PERMISSION' 20 | } 21 | }; 22 | 23 | actionsMap; 24 | app; 25 | assistant; 26 | handlers; 27 | onDefault; 28 | 29 | constructor(port = 8080) { 30 | this.actionsMap = new Map(); 31 | this.app = express(); 32 | this.app.set('port', (process.env.PORT || port)); 33 | this.app.use(bodyParser.json({ type: 'application/json' })); 34 | 35 | this.request = request; // node module 36 | 37 | // phrase random (incremental) counter 38 | this.conversationMessagesCounter = 0; 39 | this.conversationMessages = []; 40 | this.greetings = []; 41 | this.dataSetIndex = {}; 42 | this.requestCache = {}; 43 | } 44 | 45 | welcome(callback) { 46 | this.intent(ActionServer.intent.action.MAIN, callback); 47 | } 48 | 49 | intent(key, callback) { 50 | this.actionsMap.set(key, callback.bind(this)); 51 | } 52 | 53 | setGreetings(greetings) { 54 | if (Array.isArray(greetings) === false) { 55 | throw new Error('Greeting messages must be an array'); 56 | return false; 57 | } 58 | 59 | this.greetings = greetings; 60 | } 61 | 62 | getRandomGreeting() { 63 | return this.greetings[(Math.random() * this.greetings.length - 1) | 0]; 64 | } 65 | 66 | randomGreeting() { 67 | this.ask(this.getRandomGreeting()); 68 | } 69 | 70 | setConversationMessages(conversationMessages) { 71 | if (Array.isArray(conversationMessages) === false) { 72 | throw new Error('"Next Questions" messages must be an array'); 73 | return false; 74 | } 75 | 76 | this.conversationMessages = conversationMessages; 77 | } 78 | 79 | getRandomConversationMessage() { 80 | const messageIndex = (this.conversationMessagesCounter++ % (this.conversationMessages.length - 1)) || 0; 81 | return this.conversationMessages[messageIndex]; 82 | } 83 | 84 | train(dataSetKey, data, fields = ['data']) { 85 | 86 | if (!dataSetKey) { 87 | throw new Error('The "dataSetKey" parameter in "train()" is missing.'); 88 | return false; 89 | } 90 | 91 | if (Array.isArray(data) === false) { 92 | throw new Error('The "data" parameter in "train()" is missing.'); 93 | return false; 94 | } 95 | 96 | this.dataSetIndex[dataSetKey] = { 97 | __raw: { 98 | data, 99 | fields 100 | }, 101 | __index: elasticlunr(function() { 102 | const lunr = this; 103 | 104 | // if the user has provided a custom schema, use it. 105 | // otherwise use the default schema: "data" 106 | const refField = fields[0]; 107 | lunr.setRef(refField); 108 | fields.map(field => { 109 | lunr.addField(field); 110 | }); 111 | lunr.saveDocument(false); 112 | }) 113 | }; 114 | 115 | data.map(key => { 116 | if (typeof key !== 'object') { 117 | key = { 118 | 'data': key 119 | }; 120 | } 121 | this.dataSetIndex[dataSetKey].__index.addDoc(key); 122 | }); 123 | } 124 | 125 | matchUserRequest(dataSetKey, rawInput, responseCallback, lookupOptions = {}) { 126 | 127 | if (!dataSetKey) { 128 | throw new Error('The "dataSetKey" parameter in "matchUserRequest()" is missing.'); 129 | return false; 130 | } 131 | 132 | if (!this.dataSetIndex || !this.dataSetIndex[dataSetKey]) { 133 | throw new Error(`"${dataSetKey}" entry was not initialized. Call "train('${dataSetKey}', hotWords)" to train a set of data.`); 134 | return false; 135 | } 136 | 137 | const dataSet = this.dataSetIndex[dataSetKey]; 138 | const refField = dataSet.__raw.fields[0]; 139 | 140 | let queryTimeBoosting = { 141 | expand: false, 142 | fields: { 143 | [refField]: { 144 | expand: false 145 | } 146 | } 147 | }; 148 | if (lookupOptions.fields) { 149 | queryTimeBoosting.fields = lookupOptions.fields; 150 | } 151 | 152 | let filterByScore = d => true; // allow all scores 153 | if (lookupOptions.threshold) { 154 | if (typeof lookupOptions.threshold === 'number') { 155 | filterByScore = d => d.score > parseFloat(lookupOptions.threshold); 156 | } else if (typeof lookupOptions.threshold === 'function') { 157 | filterByScore = lookupOptions.threshold; 158 | } else { 159 | throw new Error(`The "threshold" parameter in lookups must either a function or a number.`); 160 | return false; 161 | } 162 | } 163 | 164 | let found = dataSet.__index.search(rawInput, queryTimeBoosting); 165 | 166 | const fileredResult = found 167 | .sort((d1, d2) => d1.score >= d2.score) 168 | .filter(filterByScore) 169 | .map(d => d.ref); 170 | 171 | if (responseCallback) { 172 | responseCallback(fileredResult, rawInput); 173 | } 174 | return fileredResult; 175 | } 176 | 177 | // request remote http URL 178 | fetch(url, responseCallback, useCache = true) { 179 | 180 | if (!url) { 181 | throw new Error('The "url" parameter is missing'); 182 | return false; 183 | } else if (!responseCallback) { 184 | console.warn(`It seems you did not provide a callback when requesting "${url}"`); 185 | } 186 | 187 | const urlSymbol = Symbol(url); 188 | 189 | if (useCache) { 190 | const cachedResponse = this.requestCache[urlSymbol]; 191 | if (cachedResponse) { 192 | responseCallback(null, cachedResponse); 193 | return cachedResponse; 194 | } else { 195 | return this._doRequest(url, responseCallback); 196 | } 197 | } else { 198 | return this._doRequest(url, responseCallback); 199 | } 200 | return null; 201 | } 202 | 203 | _doRequest(url, responseCallback) { 204 | 205 | const urlSymbol = Symbol(url); 206 | 207 | return this.request(url, (error, response, html) => { 208 | if (!error && response.statusCode == 200) { 209 | 210 | this.requestCache[urlSymbol] = {}; 211 | if (html) { 212 | this.requestCache[urlSymbol] = html; 213 | } else { 214 | console.warn(`Response from "${url}" was empty.`); 215 | } 216 | responseCallback(null, html); 217 | } else { 218 | responseCallback(error, null); 219 | } 220 | }); 221 | } 222 | 223 | // a convenient method to abstract the assistant "ask" process 224 | ask(message, data = {}) { 225 | let inputPrompt = this.assistant.buildInputPrompt(true, message, [`Sorry`]); 226 | this.assistant.data = data; 227 | this.assistant.ask(inputPrompt); 228 | } 229 | 230 | /** 231 | * @todo 232 | */ 233 | requestNamePermission(context) { 234 | // assistant.isPermissionGranted() 235 | let permission = this.assistant.SupportedPermissions.NAME; 236 | this.assistant.askForPermission(content, permission); 237 | } 238 | 239 | _handleRequest() { 240 | this.app.post('/', (request, response) => { 241 | this.assistant = new ActionsSdkAssistant({ request, response }); 242 | this.assistant.handleRequest(this.actionsMap); 243 | }); 244 | } 245 | 246 | listen() { 247 | this._handleRequest(); 248 | const server = this.app.listen(this.app.get('port'), function() { 249 | console.log('App listening on port %s', server.address().port); 250 | console.log('Press Ctrl+C to quit.'); 251 | }); 252 | return server; 253 | } 254 | }; 255 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@manekinekko/google-actions-server", 3 | "description": "Google actions Node.js server ", 4 | "version": "2.0.6", 5 | "license": "MIT", 6 | "author": { 7 | "name": "Wassim Chegham", 8 | "email": "github@wassimchegham.com" 9 | }, 10 | "engines": { 11 | "node": "> 5" 12 | }, 13 | "main": "./dist/index.js", 14 | "homepage": "https://github.com/manekinekko/google-actions-server", 15 | "bugs": "https://github.com/manekinekko/google-actions-server/issues", 16 | "private": false, 17 | "repository": { 18 | "type": "git", 19 | "url": "git@github.com:manekinekko/google-actions-server.git" 20 | }, 21 | "scripts": { 22 | "start": "nodemon lib/index.js --exec babel-node", 23 | "build": "babel lib -d dist", 24 | "deploy": "npm run build && npm version patch && git push --tags && git push && npm publish", 25 | "test": "npm run build && mocha" 26 | }, 27 | "dependencies": { 28 | "@manekinekko/google-actions-binary": "^1.0.0", 29 | "actions-on-google": "^1.0.0", 30 | "body-parser": "^1.15.2", 31 | "express": "^4.14.0", 32 | "ngrok": "^2.2.4", 33 | "nodemon": "^1.11.0", 34 | "babel-cli": "^6.18.0", 35 | "babel-preset-es2015": "^6.18.0", 36 | "babel-preset-stage-2": "^6.18.0", 37 | "elasticlunr": "^0.9.5", 38 | "request": "^2.79.0" 39 | }, 40 | "devDependencies": { 41 | "mocha": "^3.2.0", 42 | "chai": "^3.5.0", 43 | "supertest": "^3.0.0" 44 | }, 45 | "keywords": [ 46 | "google", 47 | "gactions", 48 | "google home", 49 | "google assistant", 50 | "google actions", 51 | "assistant" 52 | ] 53 | } 54 | -------------------------------------------------------------------------------- /test/test_welcome.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var ActionServer = require('../dist/index').ActionServer; 4 | 5 | var chai = require('chai'); 6 | var expect = chai.expect; 7 | var request = require('supertest'); 8 | 9 | describe('ActionServer', function() { 10 | var actionServer; 11 | var express; 12 | 13 | beforeEach(function() { 14 | actionServer = new ActionServer(); 15 | express = actionServer.listen(); 16 | }); 17 | 18 | afterEach(function() { 19 | express.close(); 20 | }); 21 | 22 | it('binds to port 8080 by default', function() { 23 | expect(actionServer.app.settings.port).to.equal(8080); 24 | }); 25 | 26 | it('responds to an invalid payload', function() { 27 | return request(express) 28 | .post('/') 29 | .expect(400).then(function(response) { 30 | expect(response.text).to.equal('Action Error: Missing inputs from request body'); 31 | }); 32 | }); 33 | 34 | it('responds to a valid payload', function() { 35 | actionServer.welcome(function() { 36 | this.ask("Hello!"); 37 | }); 38 | 39 | return request(express) 40 | .post('/') 41 | .send({ 42 | 'inputs': [{ 43 | 'intent': 'assistant.intent.action.MAIN' 44 | }] 45 | }) 46 | .expect(200).then(function(response) { 47 | expect(response.body.expected_inputs[0] 48 | .input_prompt.initial_prompts[0] 49 | .ssml).to.equal('Hello!'); 50 | }); 51 | }); 52 | }); 53 | --------------------------------------------------------------------------------