From 5a83ed8f7d485d8d15b3bcc6eef44a3df0f6ab2d Mon Sep 17 00:00:00 2001 From: geekboysupreme Date: Wed, 10 Oct 2018 21:19:35 +0530 Subject: [PATCH] Design Updates --- LICENSE | 201 +++++++++++++++++++++++++ README.md | 294 +++++++++++++++++++++++++++++++++++++ source/bots.js | 366 ++++++++++++++++++++++++++++++++++++++++++++++ source/index.html | 96 ++++++++++++ source/srcbot.js | 15 ++ 5 files changed, 972 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 source/bots.js create mode 100644 source/index.html create mode 100644 source/srcbot.js diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..9f6e4b0 --- /dev/null +++ b/README.md @@ -0,0 +1,294 @@ +Javascript Chatbot +================== + +A chatbot 'library' that makes it easy to develop chatbots that respond to users commands. It's still a work in progress, so expect more features to come soon. + +Setting up Javascript Chatbot +----------------------------- + +Chatbot requires [jQuery](https://jquery.com/) as a dependency. To use a bot, first import the `bots.js` file, and then the bot. After this, you will be able to use Javascript Chatbot. + +A version of Chatbot for NodeJS is currently not available, but will be soon. + +Creating a Chatbot +------------------ + +Each chatbot should live in its own Javascript file, with the name of the chatbot as the file name. +To add a chatbot, use the `Bots.push()` function: + + Bots.push({ + "name": "[Bot name]", + "precatch": function(text) { + return text; + }, + "actions": [], + "postcatch": function(text) { + return text; + }, + + "functions": {}, + "synonyms": [], + "variables": {} + }); + +Only the `name` property is required. All of the other properties default to the ones below. + +** How it Works ** + +To understand how to create a working bot, you should first understand the basic pieces. + +When a message is sent to the chatbot, the `precatch(text)` function is first called with the first parameter as the message. The return value of this function is then used for the rest of the processing. *You must return something from this function, or else you will end up with an error*! + +After the `precatch()` function is called, the bot system will then process the bots actions. These are contained in the `actions` property, and should look something like this: + + "actions": [ + { + "catch": ["hello"], + "response": "Hello!" + }, + { + "catch": ["*how are you*"], + "response": [ + "I'm good thanks! What about you?", + "Um.. alright, I guess.", + "I don't feel well." + ] + } + ] + +The bot system will look through each of these objects in the `actions` array to find one that matches. If one matches, it will then call the `postcatch()` function and output the value (more on this later). The chatbot system finds a match using the `catch` parameter. It is case *and* punctuation insensitive. Wildcards can also be used with an asterisk (`*`). If the `catch` contains multiple elements in the array, then all will be checked, and if one or more matches, the response will be taken. + +In the case shown above, if the user enters `hello` in any case or with any punctuation, the chatbot will output `Hello!`, as this is what is specified in the `response` property. However, if the user enters some text including `how are you` (because of the asterisk before and after), the chatbot will output one of the responses, picked randomly. + +Catches can also contain a `from` property, which will prevent the catch from matching unless the user is the user specified. The `from` property can also contain wildcards. + +Responses can contain more than just response text, howevever. The chatbot system allows you to specify actions to take the next time a message is received by the chatbot: + + "actions": [ + { + "catch": ["how are you*"], + "response": [ + { + "text": "I'm good thanks! What about you?", + "actions": [ + { + "catch": ["*good*"], + "response": "That's good!", + "from": "{PREVIOUS}" + }, + { + "catch": ["*ok*"], + "response": "Oh, ok.", + "from": "{PREVIOUS}" + }, + { + "catch": ["*bad*], + "response": "That's too bad.", + "from": "{PREVIOUS}" + }, + { + "catch": ["*"], + "response": "ANSWER ME!", + "from": "{PREVIOUS}" + } + ] + } + ] + }, + { + "catch": ["*hello*"], + "response": "Hello!" + } + ] + +For now, let's just assume that setting `from` to `{PREVIOUS}` will mean that the action only responds to the person who initated the last response. A conversation using this code would look like this: + + User > hello there! + Chat > Hello! // Responds to the catch in the original stream + User > how are you? + Chat > I'm good thanks! What about you? // Initiates a new stream branching from the original one + User > hello again + Chat > ANSWER ME! // Responds from the new stream, rather than the original one + User > hello again! + Chat > Hello! // The previous stream has finished, so we go back to the original + User > how are you? + Chat > I'm good thanks! What about you? // Entering the new stream again + User > I'm good thanks + Chat > That's good! // A response from the new stream + User > hello + Chat > Hello! // The previous stream has, again, finished, so we go back to the original + +As you can see, if a match is found in the current 'stream', the chatbot system will not fallback to the previous stream (in this case, when the user says `hello again` after saying `how are you?`, which matches the wildcard in the `how are you?` response stream). + +**Understanding Streams** + +The chatbot system uses a special 'streaming' system which allows it to understand which catch set it should process. The image below demonstrates this streaming by using the above code as an example: + + +After the bots trigger for `how are you*` is triggered, a new stream is created containing a new set of responses. Each of these responses will break out of the stream, and if none of the responses match, then the system will go back and see if any responses from previous streams match. In this case, this will never happen because a 'default' match has been provided at the end of the second stream. + +You can re-use streams by defining `functions`. These are contained in the `functions` property of the bot. The key of the item in the `functions` object is the name of the function, and the value should be an array containing the catches. You can specify to use a certain function in a catch like the following: + + { + "catch": "how are you*", + "response": [ + { + "text": "I'm good!", + "actions": "MYFUNCTION" + } + ] + } + +As you can see, by specifying a non-array in the `actions` you can use a function, which you can also use in other catches. This can also be used to achieve a loop: + + "functions": { + "MYFUNCTION": [ + { + "text": "hello*", + "response": [{ + "text": "Hello!!", + "actions": "MYFUNCTION" + }] + }, + { + "text": "what*", + "response": [{ + "text": "That's a good question", + "actions": "MYFUNCTION" + }] + } + ] + } + +This will cause `MYFUNCTION` to loop *if* the message matches either `hello*` or `what*`. Otherwise, it will fall back to the previous stream. + +**Using Synonyms** + +Synonyms allow you to test for words where the user could enter similar words. Synonyms also allow you to give semi-random responses that look unique every time. + +A list of synonyms should be contained in the `synonyms` property of the bot object. It should be structured like this: + + "synonyms": [ + ["hello", "hi", "howdy"], + ["goodbye", "bye", "see you"] + ] + +In a catch, you can specify if a word should allow synonym variations by surrounding the word with carrots (`^`).. For example, using the synonym list above, the following would all work for the catch `^hello^ there!`... + +- `hello there!` +- `hi there!` +- `howdy there!` + +You can also put in multiple synonym variations in the one catch. For example, the following would all work for the catch `^hello^ and ^goodbye^`... + +- `hello and goodbye` +- `hello and bye` +- `hello and see you` +- `hi and goodbye` +- `hi and bye` +- `hi and see you` +- `howdy and goodbye` +- `howdy and bye` +- `howdy and see you` + +Additionally, synonyms can also be used in responses to give random-ish responses... For example, the response `^goodbye^ now!` could output either: + +- `goodbye now!` +- `bye now!` +- `see you now!` + +**Using Variables** + +Variables allow you to store and re-use pieces of information. In text, you can use a variable with curly brackets surrounding the name of the variable. For example, if there is a variable called `BOT` which was equal to `MyBot`, using the response `Hello from {BOT}` would output `Hello from MyBot`. The bot system also comes with a list of predefined variables: + +- `{USER}` - The user who sent the message +- `{PREVIOUS}` - The user who sent the previous message (for use in streams) +- `{BOT}` - The name of the current bot + +You can define custom variables in the `variables` property of the bot object. To return dynamic contents, the variables can be functions: + + "variables": { + "TIME": function(bot) { + return (new Date()).toString(); + }, + "MYVARIABLE": "myvalue" + } + +If the variable is a function, the bot is passed in as the first parameter, and the value of the variable should be returned. + +To allow user input from variables, you can also use input clauses in your catches. These look like this: + + { + "catch": ["*name is {=NAME}"], + "response": ["Hello, {NAME}"] + } + +By placing an equal sign (`=`) before the variable name, the value placed in the message where that statement is will be placed into the variable. When comparing messages and catches, these input clauses evalutate to a wildcard. + +**Important Note** Input clauses can return strange results if surrounded by wildcards. An input clause can only use the information directly around it until the next asteriskes on either side to track which piece of information to grab and place into the variable, and as such can return incorrect results. *Using multiple input clauses in a catch can sometimes work, but is generally not recommended.* + +Variables can also be gotten or set in the `precatch`, `postcatch`, or other variable functions using the bots `.getVariable("variable name")` or `.setVariable("variable name", "new value")` functions. In `precatch` and `postcatch` the bot is accessible through `this`. + +** Postcatches ** +The post catch function, which you can set with the `postcatch` property of the bot object, allows you to do extra processing of the text before it is outputted. The format for this is the same as `precatch`. The input text comes in, and you should return the output text. + +Note: variables are processed before *and* after the `postcatch` function is called, meaning that the `postcatch` function *can* return variables in text. + +Using the Chatbot System +------------------------ + +Now that we know how to *create* a chatbot, let's find out how to load that chatbot and use it. All of these functions exist in the `Bots` object. + +Once a bot has been added, it's object can be gotten using `Bots.find("name of bot")`. *The name is case-insensitive.* This function returns a bot object which contains the above properties, as well as some added ones: + +- `.setVariable(name, value)` allows you to set a variable for the bot +- `.getVariable(name)` allows you to get a variable +- `.processActionQueue(message)` processes the current action queue using the specified method (not recommended for use - see `Bots.processActions()` instead +- `.actionQueue` an array containing a list of actions +- `.nextActionQueue` an array containing a list of actions for next time + +In addition to using the variables on the bot, the `Bots` object also has some useful properties: + +- `.setVariable(name, value)` sets a variable for all bots (note that if a bot already has a value it will use its own value instead) +- `.push(bot)` adds a bot to the bot system +- `.find(name)` finds a bot +- `.sendMessage(botname, message, variables)` sends a message to the specified bot, also setting the specified variables +- `.processActions(bot, message)` adds an item to the action queue and then executes it +- `.utils` an object providing utilities + +So, let's say we've created a bot called `MyBot`. Here's how we call it. + + var out = Bots.sendMessage("MyBot", "hello", { "USER": "me" }); + console.log(out); + +`Bots.sendMessage()` will process the action queue (where streams are stored), and return the required result. Using this, we can create a live bot chat page: + +**Javascript** + + $(function() { + var input = $("input"), username = "me"; + $("form").submit(function(e) { + var r = Bots.sendMessage("MyBot", input.val(), { "USER": username }); + $("

").appendTo("div").text("[" + username + "] " + input.val()).fadeIn("fast", toBottom); + input.val(""); + + setTimeout(function() { + for (var i = 0; i < r.length; i++) { + $("

").appendTo("div").text(r[i]).fadeIn("fast", toBottom); + } + }, Math.random() * 1000); + + e.preventDefault(); + return false; + }); + }); + + function toBottom() { + $("
").scrollTop($("div").get("scrollHeight")); + } + +**HTML** + +
+ +
diff --git a/source/bots.js b/source/bots.js new file mode 100644 index 0000000..d409f7c --- /dev/null +++ b/source/bots.js @@ -0,0 +1,366 @@ +var Bots = {}; +(function($) { + var variables = {}, botlist = []; + + Bots.setVariable = function(name, value) { + variables = setVariableWrapper(name, value, variables); + } + + Bots.push = function(bot) { + console.log(bot.variables); + var d = { + "precatch": function(text) { return text; }, + "actions": [], + "postcatch": function(text) { return text; }, + "functions": {}, + "synonyms": [], + "variables": {} + }; + bot = $.extend({}, d, bot); + console.log(bot.variables); + + bot.setVariable = function(name, value) { + bot.variables = setVariableWrapper(name, value, bot.variables); + } + bot.getVariable = function(name) { + var ret = false; + if (bot.variables.hasOwnProperty(name)) ret = bot.variables[name]; + else if (variables.hasOwnProperty(name)) ret = variables[name]; + + assert(ret, "Can't find variable called " + name + " for bot " + bot.name); + + return ret(bot); + } + + bot.processActionQueue = function(message) { + var outs = []; + for (var x = 0; x < bot.actionQueue.length; x++) { + var actions = bot.actionQueue[x]; + + if (!$.isArray(actions)) actions = bot.functions[actions]; + assert(actions, "No such action function called " + actions + " for bot " + bot.name); + + var match = false; + for (var i = 0; i < actions.length; i++) { + var action = actions[i]; + var c = action["catch"], r = action["response"]; + + if (!$.isArray(c)) c = [c]; + if (!$.isArray(r)) r = [r]; + + for (var y = 0; y < c.length; y++) { + var options = getSynonymOptions(c[y], bot); + for (var z = 0; z < options.length; z++) { + if (catchMatches(options[z], message, bot)) { + match = true; + break; + } + } + } + + if (match) { + + var response = arrayRandom(r); + if (typeof response !== 'object') response = { "text": response || "" }; + + var from = action["from"] || "*"; + + if (catchMatches(from, bot.getVariable("USER"), bot)) { + if (!$.isArray(response["text"])) response["text"] = [response["text"]]; + var rtext = arrayRandom(response["text"]); + + bot.setVariable("INPUT", message); + var synonymed = replaceSynonyms(replaceVariables(rtext, rtext, bot), bot); + if (response["actions"]) { + bot.nextActionQueue.push(response["actions"]); + } + + outs.push(synonymed); + + break; + } + } + } + if (match) break; + } + //console.log(bot.actionQueue, bot.nextActionQueue); + bot.actionQueue = bot.nextActionQueue; + bot.nextActionQueue = []; + //console.log(bot.nextActionQueue); + + return outs; + } + + bot.actionQueue = []; + bot.nextActionQueue = []; + + botlist.push(bot); + } + + Bots.find = function(name) { + for (var i = 0; i < botlist.length; i++) { + if (botlist[i].name.toLowerCase() == name.toLowerCase()) return botlist[i]; + } + assert(false, "Can't find a bot called " + name); + return false; + } + + Bots.sendMessage = function(botname, message, variables) { + var bot = Bots.find(botname); + + for (var key in variables) { + if (variables.hasOwnProperty(key)) { + bot.setVariable(key, variables[key]); + } + } + + message = bot.precatch.call(bot, message); + message = Bots.processActions(bot, message); + + if (message.length > 0) { + message = $.map(message, function(val) { + var post = bot.postcatch.call(bot, val); + return replaceVariables(post, post, bot); + }); + } + + bot.setVariable("PREVIOUS", bot.getVariable("USER")); + + return message; + } + + Bots.processActions = function(bot, message) { + var actions = bot.actions; + + bot.actionQueue.push(bot.actions); + var r = bot.processActionQueue(message); + return r; + + /*var outs = []; + for (var i = 0; i < actions.length; i++) { + var action = actions[i]; + var c = action["catch"], r = action["response"]; + + if (!Array.isArray(c)) c = [c]; + if (!Array.isArray(r)) r = [r]; + + var match = false; + for (var x = 0; x < c.length; x++) { + var options = getSynonymOptions(c[x], bot); + for (var y = 0; y < options.length; y++) { + if (catchMatches(options[y], message, bot)) { + match = true; + break; + } + } + } + + if (match) { + var response = arrayRandom(r); + if (typeof response !== 'object') response = { "text": response }; + + var from = response["from"] || "*"; + + if (catchMatches(from, bot.getVariable("USER"), bot)) { + //console.log(replaceVariables(response["text"], response["text"], bot)); + var synonymed = replaceSynonyms(replaceVariables(response["text"], response["text"], bot), bot); + //console.log("S: " + synonymed); + outs.push(synonymed); + } + } + } + + return outs;*/ + } + + Bots.utils = { + "debug": true + }; + + /* Utility functions */ + function log(text, important) { + if (Bots.utils.debug) { + var title = "[Bots] "; + if (important) title += "[Important] "; + console.log(title + text); + } + } + function assert(value, fmsg, tmsg) { + if (!value) { + if (fmsg === undefined) fmsg = "Assertion failed."; + log(fmsg, true); + } else if (tmsg !== undefined) log(tmsg); + } + + function setVariableWrapper(name, value, object) { + if (typeof value !== 'function') { + var plainvalue = value; + value = function() { return plainvalue; } + } + + object[name.toUpperCase()] = value; + return object; + } + + function getSynonym(original, list) { + return arrayRandom(getSynonymList(original, list)); + } + + function getSynonymList(original, list) { + assert(list !== undefined, "No such list for synonyms '" + original + "'"); + + for (var i = 0; i < list.length; i++) { + var slist = list[i]; + if (slist.indexOf(original) > -1) return slist; + } + return [original]; + } + + function arrayRandom(array) { + return array[Math.floor(Math.random() * array.length)]; + } + + function removePunctuation(text) { + var punctuationLess = text.replace(/[\.,-\/#!$%\^&;:{}=\-_`~()@\+\?><\[\]\+]/g, ""); + return punctuationLess.replace(/\s{2,}/g, " "); + } + + function replaceVariables(text, message, bot) { + var pieces = getByDelimiter(text, "{", "}"); + + for (var x = 1; x < pieces.length; x += 2) { + var piece = pieces[x]; + if (piece.charAt(0) === "=") { + var vname = piece.slice(1); + + var wordpos = false; + if (text.indexOf("*") < text.indexOf("{" + piece + "}")) { + wordpos = (pieces.length - x - 1) * -1; + } + else wordpos = x; + + var splitmessage = message.split(" "); + + if (wordpos < 0) wordpos = splitmessage.length + wordpos; + + var word = removePunctuation(splitmessage[wordpos]); + if (word !== undefined) bot.setVariable(vname, word); + + pieces[x] = "*"; + } else { + if (pieces[x] !== "") pieces[x] = bot.getVariable(piece); + } + } + //console.log(text + ", " + pieces.join("")); + + return pieces.join(""); + } + + function replaceSynonyms(text, bot) { + var pieces = getByDelimiter(text, "^", "^"); + //console.log(pieces); + for (var i = 1; i < pieces.length; i += 2) { + pieces[i] = getSynonym(pieces[i], bot.synonyms); + } + return pieces.join(""); + } + function getSynonymOptions(text, bot) { + var pieces = getByDelimiter(text, "^", "^"); + + var synonyms = [], words = [], wcount = 0; + for (var i = 1; i < pieces.length; i+= 2) { + //console.log(bot); + synonyms.push(getSynonymList(pieces[i], bot.synonyms)); + words.push(pieces[i]); + wcount++; + } + + //console.log(pieces); + function allPossibleCases(arr) { + if (arr.length === 1) return [arr[0]]; + + var result = []; + var remaining = allPossibleCases(arr.slice(1)); + for (var i = 0; i < remaining.length; i++) { + for (var j = 0; j < arr[0].length; j++) { + result.push([arr[0][j]].concat(remaining[i])); + } + } + return result; + } + //words = allPossibleCases(words); + synonyms = getCombinations(synonyms, wcount); + + var results = [], wpos = 0; + for (var i = 0; i < synonyms.length; i++) { + var options = synonyms[i], pcopy = pieces.slice(); + for (var x = 0; x < options.length; x++) { + pcopy[x * 2 + 1] = options[x]; + } + results.push(pcopy.join("")); + } + + + //console.log(results, words); + return results; + } + + function getCombinations(arr, n){ + var i,j,k,elem,l = arr.length,childperm,ret=[]; + if(n == 1){ + for(var i = 0; i < arr.length; i++){ + for(var j = 0; j < arr[i].length; j++){ + ret.push([arr[i][j]]); + } + } + return ret; + } + else{ + for(i = 0; i < l; i++){ + elem = arr.shift(); + for(j = 0; j < elem.length; j++){ + childperm = getCombinations(arr.slice(), n-1); + for(k = 0; k < childperm.length; k++){ + ret.push([elem[j]].concat(childperm[k])); + } + } + } + return ret; + } + i=j=k=elem=l=childperm=ret=[]=null; + } + + function getByDelimiter(text, start, end) { + if (text.indexOf(start) < 0 || text.indexOf(end) < 0) return [text, ""]; + + var firstpieces = text.split(start), pieces = []; + for (var i = 0; i < firstpieces.length; i++) { + var secondpieces = firstpieces[i].split(end); + pieces.push.apply(pieces, secondpieces); + } + assert(pieces.length > 0, "Not enough pieces in text " + text); + + return pieces; + } + + function catchMatches(ctext, message, bot) { + ctext = removePunctuation(replaceVariables(ctext, message, bot)).toLowerCase(); + message = removePunctuation(message).toLowerCase(); + + console.log(message, ctext, wildCompare(message, ctext)); + return wildCompare(message, ctext); + } + + function wildCompare(string, search) { + if (search.indexOf('*') < 0 && string != search) return false; + if ((string.length < 1 && search.length > 0) || (search.length < 1 && string.length > 0)) return false; + + var startIndex = 0, array = search.split('*'); + for (var i = 0; i < array.length; i++) { + var index = string.indexOf(array[i], startIndex); + if (index == -1) return false; + else startIndex = index; + } + return true; + } +}(jQuery)); \ No newline at end of file diff --git a/source/index.html b/source/index.html new file mode 100644 index 0000000..ed851f2 --- /dev/null +++ b/source/index.html @@ -0,0 +1,96 @@ + + + + + Bot Tester + + + + + + + + + + + + +
+
+ +
+ + + diff --git a/source/srcbot.js b/source/srcbot.js new file mode 100644 index 0000000..6323df5 --- /dev/null +++ b/source/srcbot.js @@ -0,0 +1,15 @@ +Bots.push({ + "name": "Image Parsing Bot", + "precatch": function(text) { + return text.replace("'", " ' ").replace('"', ' " '); + }, + "actions": [ + { + "catch": ["", ''], + "response": "" + } + ], + "postcatch": function(text) { + return "The source is " + this.getVariable("N"); + } +}); \ No newline at end of file