### Install and Run Example Source: https://github.com/aichaos/rivescript-js/blob/master/eg/json-server-async/README.md Commands to install dependencies and run the weatherman.js example. ```bash npm install && node weatherman.js ``` -------------------------------- ### Install and Run Built-in Server Source: https://github.com/aichaos/rivescript-js/blob/master/eg/web-client/README.md Install project dependencies and start the built-in Grunt server to test the web client example. This command also automatically opens the web browser. ```bash # Install dependencies (run from the root of the rivescript-js project) $ npm install # Start the built-in server. This also automatically opens your web browser # to the correct URL. $ grunt server ``` -------------------------------- ### Install and Run http-server Source: https://github.com/aichaos/rivescript-js/blob/master/eg/web-client/README.md Install the http-server package globally and use it to serve the web client example. Ensure you build the RiveScript JS file first. ```bash # If you don't already have http-server: % npm install -g http-server # From the root of the rivescript-js project... % cd ~/git/rivescript-js # Build the `dist/rivescript.js` packed for the web browser, and then run # the Node http-server. % npm run dist % http-server ``` -------------------------------- ### Install and Run JSON Server Source: https://github.com/aichaos/rivescript-js/blob/master/eg/json-server/README.md Steps to install dependencies and run the Node.js JSON server example. This includes building RiveScript-JS sources if necessary. ```bash # Build the JavaScript sources from the CoffeeScript first. Run these from # the root of the rivescript-js repo. $ npm install $ grunt # Then, from the eg/json-server directory, install the JSON server's # dependencies (expressjs, etc.) $ npm install # And run the server. $ node server.js ``` -------------------------------- ### Setup development environment with make Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Installs dependencies and sets up the development environment. This is an alternative to npm scripts for Node.js versions >= 7. ```bash make setup ``` -------------------------------- ### Starting the RiveScript Interactive Shell (npm install) Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Instructions for launching the RiveScript interactive shell when RiveScript.js is installed locally via npm. This command is run from the project's root directory. ```bash npx riveshell /path/to/brain ``` -------------------------------- ### Starting the RiveScript Interactive Shell (npm install -g) Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Instructions for launching the RiveScript interactive shell when RiveScript.js is installed globally via npm. This command can be run from any directory. ```bash riveshell /path/to/brain ``` -------------------------------- ### Run RiveScript Router Example Source: https://github.com/aichaos/rivescript-js/blob/master/eg/router/README.md Commands to build the RiveScript-JS project and run the router example from the command line. ```bash [rivescript-js]$ grunt dist [rivescript-js]$ cd eg/router [router]$ node router.js ``` -------------------------------- ### Build and Run Persistence Example Source: https://github.com/aichaos/rivescript-js/blob/master/eg/persistence/README.md Commands to build the RiveScript-JS project and run the persistence example bot from the command line. ```bash # From the root of the rivescript-js project, build the JS sources. $ grunt # From the persistence example folder, run the bot. $ cd eg/persistence/ $ node bot.js ``` -------------------------------- ### Install Dependencies and Run Slack Bot Source: https://github.com/aichaos/rivescript-js/blob/master/eg/slack-bot/README.md Install the Slackbot's dependencies and run the bot from the slack-bot folder. The bot will connect to Slack and display a welcome message. ```bash cd eg/slack-bot/ npm install node slack-bot.js [Wed Sep 23 2015 12:00:48 GMT-0700 (PDT)] INFO Connecting... Welcome to Slack. You are admiral of YourSlackOrg ``` -------------------------------- ### Install Build Dependencies Source: https://github.com/aichaos/rivescript-js/blob/master/CONTRIBUTING.md Install the necessary Node.js and npm dependencies for development and building the RiveScript-JS project. Ensure you have Node.js and npm installed globally. ```bash # CLI dependencies if you don't have them already $ npm install -g babel-cli webpack uglify-js nodeunit # Install dev dependencies for rivescript-js $ npm install ``` -------------------------------- ### Install rivescript-redis Source: https://github.com/aichaos/rivescript-js/blob/master/contrib/redis/README.md Install the Redis cache driver using npm. ```bash npm install rivescript-redis ``` -------------------------------- ### Example Output of CoffeeScript Handler Source: https://github.com/aichaos/rivescript-js/blob/master/eg/coffeescript/README.md This shows the expected output when running the CoffeeScript handler example with a specific input. ```bash % node coffeebot.js > coffee test Bot> Testing CoffeeScript object: Hello, soandso! ``` -------------------------------- ### Build and Run Telnet Server Source: https://github.com/aichaos/rivescript-js/blob/master/eg/telnet-server/README.md Commands to install dependencies, build the project, and run the Node.js telnet server. ```bash # Build the JavaScript sources from the CoffeeScript first. Run these from # the root of the rivescript-js repo. $ npm install $ grunt # Run the server. $ node tcp-server.js ``` -------------------------------- ### Install RiveScript-Contrib-CoffeeScript Source: https://github.com/aichaos/rivescript-js/blob/master/contrib/coffeescript/README.md Install the CoffeeScript handler using npm. ```bash npm install rivescript-contrib-coffeescript ``` -------------------------------- ### Catch-all Trigger Example Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html This example shows how to use the '*' trigger as a catch-all for messages that do not match any other triggers. ```RiveScript + * - I don't know what to say to that! ``` -------------------------------- ### Handling No Reply Found Example Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html This example demonstrates how to ensure a normal reply is provided for a trigger, even if conditions are not met. ```RiveScript + hello * != undefined => Hello there, . - Hi there. ``` -------------------------------- ### Run npm build script Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Compiles ES2015+ sources to ES5 for distribution. Ensure you have Node.js and npm installed. ```bash npm run build ``` -------------------------------- ### Example Output Source: https://github.com/aichaos/rivescript-js/blob/master/eg/second-reply/README.md The output shows the chatbot sending an initial message and then a second, delayed message to the user. ```bash % node bot.js > reply test [Soandso] reply test [Bot] @Soandso: Wait for it... > [Bot] @Soandso: Second reply! ``` -------------------------------- ### Example Session Data Structure Source: https://github.com/aichaos/rivescript-js/blob/master/docs/sessions.md Illustrates the expected JSON structure for retrieving all variables from all users, mapping usernames to their respective variable objects. ```json { "user1": { "topic": "random", "name": "Alice" }, "user2": { "topic": "random", "name": "Bob" } } ``` -------------------------------- ### Example Chatbot Interaction and Output Source: https://github.com/aichaos/rivescript-js/blob/master/eg/persistence/README.md Illustrates the command-line interaction with the bot and its responses during two separate runs, showing state persistence. ```bash $ node bot.js Enter your username [default: soandso]: kirsle Hello kirsle Type /quit to quit. > Hello bot Bot> How do you do. Please state your problem. > My name is Noah Bot> Noah, nice to meet you. > /quit $ node bot.js Enter your username [default: soandso]: kirsle Hello kirsle Type /quit to quit. > How are you? Bot> What is it you really want to know? > What is my name? Bot> Your name is Noah. > /quit ``` -------------------------------- ### External Server Directory Structure Source: https://github.com/aichaos/rivescript-js/blob/master/eg/web-client/README.md Example directory structure for deploying the web client to an external server like Apache. Ensure all necessary files and folders are uploaded correctly. ```text /brain /admin.rive /begin.rive /... /chat.css /chat.html /datadumper.js /jquery-1.7.2.min.js /rivescript.js ``` -------------------------------- ### Promise-based ReplyAsync Example Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Illustrates how to use the now-obsolete `replyAsync` function with Promises to handle asynchronous replies from the bot. ```javascript rs.replyAsync(user, message).then(function(reply) { console.log("Bot>", reply); }).catch(function(error) { console.error("Error: ", error); }); ``` -------------------------------- ### Slack Bot Integration Source: https://github.com/aichaos/rivescript-js/blob/master/eg/README.md An example demonstrating how to connect a RiveScript bot to the Slack chat platform. ```javascript const { RTMClient } = require('@slack/client'); const RiveScript = require('rivescript'); const rtm = new RTMClient(process.env.SLACK_API_TOKEN); const rs = new RiveScript(); rs.loadDirectory('brain',). then(function() { rs.sortReplies(); rtm.on('message', (event) => { if (event.subtype && event.subtype === 'bot_message') return; const reply = rs.reply(event.user, event.text); rtm.sendMessage(reply, event.channel); }); rtm.start(); }); ``` -------------------------------- ### Callback-based ReplyAsync Example Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Demonstrates the usage of the `replyAsync` function with a traditional callback to process the bot's response or any errors. ```javascript rs.replyAsync(username, msg, this, function(error, reply) { if (!error) { console.log("Bot>", reply); } else { console.error("Error: ", error); } }); ``` -------------------------------- ### Learning Bot Interaction Example Source: https://github.com/aichaos/rivescript-js/blob/master/eg/learning/README.md Demonstrates the interactive learning process of the RiveScript bot. The bot learns new responses based on user input and applies them in subsequent interactions. Shows both initial unknown responses and learned responses. ```bash % cd eg/learning % node bot.js > Hello [Soandso] Hello [Bot] I don't know how to reply to that. Why not teach me? Just say: when I say hello you say (what you want me to say) For example: when I say hello bot you say hello human. > when I say hello you say Hello human! [Soandso] when I say hello you say Hello human! [Bot] I have learned: when you say "hello" I should say "Hello human!" > Hello [Soandso] Hello [Bot] Hello human! > My name is Noah [Soandso] My name is Noah [Bot] Nice to meet you, Noah. > Who is Kirsle? [Soandso] Who is Kirsle? [Bot] I don't know how to reply to that. Why not teach me? Just say: when I say who is kirsle you say (what you want me to say) For example: when I say hello bot you say hello human. > when I say who is * you say I've never heard of before in my life!! [Soandso] when I say who is * you say I've never heard of before in my life!! [Bot] I have learned: when you say "who is *" I should say "I've never heard of Undefined before in my life!!" > Who is Kirsle? [Soandso] Who is Kirsle? [Bot] I've never heard of Kirsle before in my life!! > Who is Linus Torvalds? [Soandso] Who is Linus Torvalds? [Bot] I've never heard of Linus Torvalds before in my life!! ``` -------------------------------- ### Install RiveScript-JS via npm Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Use this command to install the RiveScript-JS module in your Node.js project. ```bash npm install rivescript ``` -------------------------------- ### Telnet Server Example Source: https://github.com/aichaos/rivescript-js/blob/master/eg/README.md A simple telnet server that listens on port 2001 for TCP socket connections and chats with users. ```javascript const net = require('net'); const RiveScript = require('rivescript'); const server = net.createServer((socket) => { const rs = new RiveScript(); rs.loadDirectory('brain',). then(function() { rs.sortReplies(); const userId = socket.remoteAddress + ':' + socket.remotePort; socket.write('Welcome! Type your message:\n'); socket.on('data', (data) => { const message = data.toString().trim(); const reply = rs.reply(userId, message); socket.write(reply + '\n'); }); }); }); server.listen(2001, () => { console.log('Telnet server listening on port 2001'); }); ``` -------------------------------- ### Example RiveScript Code Source: https://github.com/aichaos/rivescript-js/blob/master/eg/deparse/README.md This is a sample RiveScript file (`example.rive`) demonstrating various features like variables, substitutions, arrays, topics, and custom objects. It serves as input for the deparsing example. ```rivescript ! version = 1.0 ! var name = Aiden ! var age = 5 ! sub what's = what is ! array colors = red blue green yellow cyan magenta black white > begin + request - {ok} < begin + hello bot - Hello human. + hi robot @ hello bot + my name is * - >Nice to meet you, . - >Hello, . + what is my name * != undefined => Your name is . - You didn't tell me your name. > topic game-global + help - How to play... < topic > topic game-room-1 inherits game-global + look - You're in a room labeled "1". < topic > object reverse javascript var msg = args.join(" "); return msg.split("").reverse().join(""); < object + say * in reverse - reverse ``` -------------------------------- ### Example Output of Router Bot Source: https://github.com/aichaos/rivescript-js/blob/master/eg/router/README.md Sample interaction with the RiveScript router bot, showing responses to various commands. ```text % node router.js Note: type `/quit` to exit. You> hello bot [Captain's Log] Unhandled message: hello bot Bot> No reply for that one. Try one of these: add 5 and 7 what is 12 divided by 3 reverse hello world say hi robot to me backwards You> add 5 and 7 Bot> 12 You> reverse how are you? Bot> uoy era woh You> say hi robot to me backwards Bot> tobor ih ``` -------------------------------- ### Starting the RiveScript Interactive Shell (GitHub Clone) Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Instructions for launching the RiveScript interactive shell when the repository is cloned directly from GitHub. This command is run using Node.js from the project's root directory. ```bash node shell.js /eg/brain ``` -------------------------------- ### RiveScript Data Structure Example Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/parser.html This is an example of the data structure returned after parsing a RiveScript document. It includes sections for begin data, topics with triggers and replies, and parsed object macros. ```javascript { "begin": { "global": {}, "var": {}, "sub": {}, "person": {}, "array": {}, }, "topics": { "random": { "includes": {}, "inherits": {}, "triggers": [ { "trigger": "hello bot", "reply": [], "condition": [], "redirect": "", "previous": null, }, ... ] } }, "objects": [ { "name": "", "language": "", "code": [], } ] } ``` -------------------------------- ### Using a Custom Session Manager Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/sessions.html Instantiate RiveScript with a custom session manager by passing it in the options. This example shows how to use a Redis session manager. ```javascript const RedisSessions = require("rivescript-contrib-redis"); // Provide the sessionManager option to use this instead of // the default MemorySessionManager. var bot = new RiveScript({ sessionManager: new RedisSessions("localhost:6379") }); ``` -------------------------------- ### Persisted User Data Example (JSON) Source: https://github.com/aichaos/rivescript-js/blob/master/eg/persistence/README.md A sample JSON file representing the persisted state of a user's variables, including conversation history and specific data like their name. ```javascript // kirsle.json { "topic": "random", "__history__": { "input": [ "what is my name", "how are you", "my name is noah", "hello bot", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined" ], "reply": [ "Your name is Noah.", "What is it you really want to know?", "Noah, nice to meet you.", "How do you do. Please state your problem.", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined" ] }, "__lastmatch__": "(what is my name|who am i|do you know my name|do you know who i am){weight=10}", "__initialmatch__": "(what is my name|who am i|do you know my name|do you know who i am){weight=10}", "name": "Noah" } ``` -------------------------------- ### Normal Promise Usage for Bot Reply Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Demonstrates how to use the `reply` function with standard Promise handling to get a response from the RiveScript bot. ```javascript bot.reply(username, message, this).then(function(reply) { console.log("Bot>", reply); }); ``` -------------------------------- ### CoffeeScript Object Macro Example Source: https://github.com/aichaos/rivescript-js/blob/master/contrib/coffeescript/README.md Example of a CoffeeScript object macro definition for reversing a string. This macro is then called by a RiveScript trigger. ```rivescript > object reverse coffeescript msg = args.join " " return msg.split("").reverse().join("") < object + reverse * - reverse ``` -------------------------------- ### Test JSON Server API with Curl Source: https://github.com/aichaos/rivescript-js/blob/master/eg/json-server/README.md Example using curl to send a POST request to the JSON server's /reply endpoint and display the response. Demonstrates setting content type and sending JSON data. ```bash curl -i \ -H "Content-Type: application/json" \ -X POST -d '{"username":"soandso","message":"hello bot"}' \ http://localhost:2001/reply HTTP/1.1 200 OK X-Powered-By: Express Content-Type: application/json; charset=utf-8 Content-Length: 913 ETag: W/"391-AgDgznci+rSclUCAK4w2EA" Date: Tue, 19 Jan 2016 00:49:27 GMT Connection: keep-alive { "status": "ok", "reply": "How do you do. Please state your problem.", "vars": { "topic": "random", "__history__": { "input": [ "hello bot", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined" ], "reply": [ "How do you do. Please state your problem.", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined", "undefined" ] }, "__lastmatch__": "(hello|hi|hey|howdy|hola|hai|yo) [*]", "__initialmatch__": "(hello|hi|hey|howdy|hola|hai|yo) [*]" } } ``` -------------------------------- ### RiveScript Brain Example Source: https://github.com/aichaos/rivescript-js/blob/master/eg/README.md Demonstrates the standard default RiveScript brain using .rive files to implement an Eliza-like bot with added triggers for RiveScript features. ```rivescript + hello - Hello there! + what is your name - I am RiveScript-js. + what is \\"a \\"\\"quote\\"\\"? - That is a "quote". ``` -------------------------------- ### CoffeeScript Object Macros Source: https://github.com/aichaos/rivescript-js/blob/master/eg/README.md An example of using the `rivescript-contrib-coffeescript` module to enable CoffeeScript language for object macros. ```javascript const RiveScript = require('rivescript'); require('rivescript-contrib-coffeescript')(RiveScript); const rs = new RiveScript(); rs.loadDirectory('brain',). then(function() { rs.sortReplies(); // ... bot logic ... }); ``` ```coffeescript # Example CoffeeScript object macro # + hello coffee # - # return "Hello from CoffeeScript!" # ``` -------------------------------- ### Configuring Custom Error Messages Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html This example shows how to set custom error messages during RiveScript object construction and afterwards. ```JavaScript var bot = new RiveScript({ errors: { replyNotFound: "I don't know how to reply to that." } }); bot.errors.objectNotFound = "Something went terribly wrong."; ``` -------------------------------- ### Router Style Engine Usage Source: https://github.com/aichaos/rivescript-js/blob/master/eg/README.md Example of using the RiveScript engine in a 'router' style, mapping triggers directly to JavaScript handlers without RiveScript boilerplate. ```javascript const RiveScript = require('rivescript'); const rs = new RiveScript(); rs.setHandler('hello', function(rs, user, message, data) { return 'Hello there!'; }); rs.setHandler('goodbye', function(rs, user, message, data) { return 'Goodbye!'; }); rs.loadDirectory('brain',). then(function() { rs.sortReplies(); console.log(rs.reply('user1', 'hello')); console.log(rs.reply('user1', 'goodbye')); }); ``` -------------------------------- ### Handling User Variables Asynchronously with RiveScript-JS Source: https://github.com/aichaos/rivescript-js/wiki/Asynchronous-Support This example demonstrates how to retrieve user variables after a reply and store them asynchronously, for instance, in Redis. This pattern allows you to manage user data outside of RiveScript's synchronous core. ```javascript bot.replyAsync(username, message, this).then(function(reply) { // After the reply, get all the user's data and store them somewhere. var userdata = bot.getUservars(username); redisClient.set(username, JSON.stringify(userdata), redisClient.print); // And do whatever you want with the reply. messengerDriver.sendMessage(username, reply); }); ``` -------------------------------- ### Handling Nestable Tags with Call Source: https://github.com/aichaos/rivescript-js/blob/master/Changes.md Demonstrates the use of nestable tags like and with a JavaScript object macro for dynamic variable manipulation. The example shows how to set a variable using the result of a function call. ```rivescript + * - add_hello > ^ The answer is: . > object add_hello javascript return "hello:" + args[0]; < object ``` -------------------------------- ### Get All User Variables Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Get all variables for a specific user, or all data about all users if no user is provided. This is an asynchronous operation. ```javascript bot.getUservars("user1"); // Or to get all user data: bot.getUservars(); ``` -------------------------------- ### Get Bot Variable Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Get a bot variable's value. This is equivalent to using `` in RiveScript. ```javascript bot.getVariable("name"); ``` -------------------------------- ### Get Single User Variable Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Get a specific variable from a user. Returns the string "undefined" if the variable is not defined. This is an asynchronous operation. ```javascript bot.getUservar("user1", "name"); ``` -------------------------------- ### Run npm dist script Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Produces a full distributable build using Babel and Webpack. This is for creating browser-ready bundles. ```bash npm run dist ``` -------------------------------- ### Send User Message and Get Bot Reply Source: https://github.com/aichaos/rivescript-js/blob/master/eg/web-client/chat.html Captures user input, displays it in the chat, and sends it to the RiveScript interpreter to get a reply. The bot's response is then displayed, and the chat window scrolls to the bottom. ```javascript function sendMessage () { var text = $("#message").val(); $("#message").val(""); $("#dialogue").append("
You: " + text + "
"); rs.reply("soandso", text, this).then(function(reply) { reply = reply.replace(/\n/g, "
"); $("#dialogue").append("
Bot: " + reply + "
"); $("#dialogue").animate({ scrollTop: $("#dialogue").height() }, 1000); }).catch(function(e) { window.alert(e.message + "\n" + e.line); console.log(e); }); return false; } ``` -------------------------------- ### Connect to Telnet Server Source: https://github.com/aichaos/rivescript-js/blob/master/eg/telnet-server/README.md Connect to the running telnet server using the telnet client. ```bash % telnet localhost 2001 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Hello 127.0.0.1:50529! This is RiveScript.js v1.1.4 running on Node! Type /quit to disconnect. You> Hello bot. Bot> Hi. What seems to be your problem? ``` -------------------------------- ### Compile Documentation with Python Source: https://github.com/aichaos/rivescript-js/blob/master/CONTRIBUTING.md Compile the project's documentation using Python and the 'markdown' module. This process generates Markdown files from the source code comments. ```bash $ mkvirtualenv rivescript # (if you use virtualenvwrapper) $ pip install markdown $ python mkdoc.py ``` -------------------------------- ### Loading RiveScript from a File Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Demonstrates how to load RiveScript code from a single file or an array of files using Promises. ```JavaScript async loadFile(string path || array path) ``` -------------------------------- ### Initialize RiveScript Interpreter and Load Brain Files Source: https://github.com/aichaos/rivescript-js/blob/master/eg/web-client/chat.html Creates a new RiveScript interpreter instance and loads brain files from the 'brain/' directory. This code should only run if the RiveScript library is loaded correctly. It uses Promises for asynchronous loading and error handling. ```javascript var rs; if (window.RiveScript === undefined) { document.querySelector("#webpack-error").style.display = "block"; } else { rs = new RiveScript({ debug: debugMode, onDebug: onDebug }); rs.loadFile([ "../brain/begin.rive", "../brain/admin.rive", "../brain/clients.rive", "../brain/eliza.rive", "../brain/myself.rive", "../brain/rpg.rive", "../brain/javascript.rive" ]).then(onReady).catch(onError); rs.setSubroutine('fancyJSObject', function(rs, args){ // doing complex stuff here }); } ``` -------------------------------- ### Dynamically Generated RiveScript Code Source: https://github.com/aichaos/rivescript-js/blob/master/eg/router/README.md An example of RiveScript code that is generated dynamically by the router script, mapping a pattern to a `` macro. ```rivescript + [*] what is # * [by|to|and] # - math "" "" "" ``` -------------------------------- ### Run shell.js with make Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Executes the shell.js script using ES2015+ sources directly. No build steps are required for this command. ```bash make run ``` -------------------------------- ### RiveScript Conditional Limitation Example Source: https://github.com/aichaos/rivescript-js/blob/master/eg/json-server-async/README.md This RiveScript code illustrates a limitation where asynchronous object macros are not supported within the conditional side of '*Conditions'. ```rivescript + is it sunny outside * weather == sunny => It appears it is! - It doesn't look sunny outside. ``` -------------------------------- ### Using a Custom Session Manager Source: https://github.com/aichaos/rivescript-js/blob/master/docs/sessions.md Demonstrates how to configure RiveScript to use a custom session manager, such as RedisSessions, by passing it as an option during bot initialization. ```javascript const RedisSessions = require("rivescript-contrib-redis"); // Provide the sessionManager option to use this instead of // the default MemorySessionManager. var bot = new RiveScript({ sessionManager: new RedisSessions("localhost:6379") }); ``` -------------------------------- ### Define Async Subroutine with Promises Source: https://github.com/aichaos/rivescript-js/blob/master/eg/json-server-async/README.md Example of defining an asynchronous subroutine using RiveScript's Promise alias. This subroutine resolves with a simple string. ```javascript var rs = new RiveScript(); rs.setSubroutine("asyncHelper", function(rs, args) { // RiveScript comes bundled with RSVP.js which you can // access through RiveScript.Promise alias // but you are free to use your own Promise implementation return new rs.Promise(function(resolve, reject) { resolve('hello there'); }); }) ``` -------------------------------- ### Run tests directly with make Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Executes NodeUnit tests on ES2015+ test sources without pre-compilation. This is faster than 'npm run test' for direct testing. ```bash make test ``` -------------------------------- ### Retrieve Current User ID Source: https://github.com/aichaos/rivescript-js/blob/master/docs/rivescript.md Get the ID of the user who invoked a JavaScript object macro. Returns undefined if called outside a reply context. ```javascript currentUser() ``` -------------------------------- ### Build RiveScript-JS Library Source: https://github.com/aichaos/rivescript-js/blob/master/eg/slack-bot/README.md Build the JavaScript library from the CoffeeScript code. Run this from the root of the rivescript-js project. ```bash $ grunt ``` -------------------------------- ### Node.js Usage of CoffeeScript Handler Source: https://github.com/aichaos/rivescript-js/blob/master/contrib/coffeescript/README.md Register and use the CoffeeScript handler in a Node.js environment. This example demonstrates loading replies and testing a CoffeeScript object macro. ```javascript var RiveScript = require("rivescript"), RSCoffeeScript = require("rivescript-contrib-coffeescript"); var bot = new RiveScript(); // Register the CoffeeScript handler. bot.setHandler("coffeescript", new RSCoffeeScript(bot)); // Load your replies like normal, and `>object * coffeescript` macros will be // loaded and usable just like JavaScript ones. bot.loadDirectory("./replies", function() { bot.sortReplies(); var reply = bot.reply("reverse hello world"); if (reply === "dlrow olleh") { console.log("It works!"); } }); ``` -------------------------------- ### Loading RiveScript from a String Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Illustrates how to load RiveScript source code directly from a string synchronously. ```JavaScript bool stream (string code[, func onError]) ``` -------------------------------- ### Asynchronous Reply with Promises Source: https://github.com/aichaos/rivescript-js/blob/master/eg/README.md Demonstrates using the `replyAsync()` method with a JavaScript object macro that returns a promise. ```javascript const RiveScript = require('rivescript'); const rs = new RiveScript(); rs.loadDirectory('brain',). then(function() { rs.sortReplies(); rs.setVariable('user1', 'name', 'Alice'); rs.replyAsync('user1', 'get name').then(function(reply) { console.log(reply); }); }); ``` ```rivescript + get name - return Promise.resolve('My name is ' + rs.getUservar('user1', 'name')); ``` -------------------------------- ### Initialize RiveScript with Redis Session Manager Source: https://github.com/aichaos/rivescript-js/blob/master/contrib/redis/README.md Import and configure RiveScript with the RedisSessionManager, specifying connection options for Redis. ```javascript const RiveScript = require("rivescript"), RedisSessionManager = require("rivescript-redis"); let bot = new RiveScript({ utf8: true, sessionManager: new RedisSessionManager({ host: "localhost", port: 6369, prefix: "rivescript/" }) }); ``` -------------------------------- ### Async-Await Usage for Bot Reply Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Shows how to use the `reply` function within an `async` function using the `await` keyword for cleaner asynchronous code. ```javascript async function getReply(username, message) { var reply = await bot.reply(username, message); console.log("Bot>", reply); } ``` -------------------------------- ### Node.js Execution Output Source: https://github.com/aichaos/rivescript-js/blob/master/eg/scope/README.md Shows the output of running the bot.js script, illustrating the effect of the 'scope' parameter on JS macros and their access to 'this'. ```bash % node bot.js Bot> Testing the scope! Function result: It works! this.hello: Hello world this.counter: 1 > scope test Bot> Testing the scope! Function result: It works! this.hello: Hello world this.counter: 2 > scope test Bot> Testing the scope! Function result: It works! this.hello: Hello world this.counter: 3 ``` -------------------------------- ### Run npm test script Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Builds and runs tests using NodeUnit. This script compiles both application and test sources. ```bash npm run test ``` -------------------------------- ### Async Reply with Promises Source: https://github.com/aichaos/rivescript-js/blob/master/eg/json-server-async/README.md Demonstrates how to handle asynchronous replies from RiveScript using the replyAsync method and promise .then() and .catch() handlers. ```javascript // using promises rs.replyAsync(username, message).then(function(reply) { // good to go }).catch(function(error){ // something went wrong }); ``` -------------------------------- ### Clone the RiveScript-JS Repository Source: https://github.com/aichaos/rivescript-js/blob/master/CONTRIBUTING.md Fork and clone the RiveScript-JS repository to your local machine. This is the first step before making any contributions. ```bash $ git clone git@github.com:your-username/rivescript-js.git ``` -------------------------------- ### Conditional with Async Object Macro (Issue) Source: https://github.com/aichaos/rivescript-js/wiki/Asynchronous-Support This example demonstrates a scenario where using an asynchronous object macro on the left side of a conditional fails due to RiveScript's two-phase tag processing. The `` tag is not resolved in time for the conditional check. ```RiveScript + is it sunny outside * weather == sunny => Yes it is! - No it's not. ``` -------------------------------- ### Loading RiveScript Documents in Node.js Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Demonstrates how to load RiveScript documents from a directory or individual files using the RiveScript.js library. This method is asynchronous and requires handlers for completion and errors. Suitable for Node.js environments. ```javascript var bot = new RiveScript(); // Load a directory full of RiveScript documents (.rive files). This is for // Node.JS only: it doesn't work on the web! bot.loadDirectory("brain").then(loading_done).catch(loading_error); // Load an individual file. bot.loadFile("brain/testsuite.rive").then(loading_done).catch(loading_error); // Load a list of files all at once (the best alternative to loadDirectory // for the web!) bot.loadFile([ "brain/begin.rive", "brain/admin.rive", "brain/clients.rive" ]).then(loading_done).catch(loading_error); // All file loading operations are asynchronous, so you need handlers // to catch when they've finished. If you use loadDirectory (or loadFile // with multiple file names), the success function is called only when ALL // the files have finished loading. function loading_done() { console.log("Bot has finished loading!"); // Now the replies must be sorted! bot.sortReplies(); // And now we're free to get a reply from the brain! // RiveScript remembers user data by their username and can tell // multiple users apart. let username = "local-user"; // NOTE: the API has changed in v2.0.0 and returns a Promise now. bot.reply(username, "Hello, bot!").then(function(reply) { console.log("The bot says: " + reply); }); } // It's good to catch errors too! function loading_error(error, filename, lineno) { console.log("Error when loading files: " + error); } ``` -------------------------------- ### Run npm webpack script Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Creates the dist/rivescript.js file directly from sources using Webpack and Babel. This is independent of the 'npm run build' process. ```bash npm run webpack ``` -------------------------------- ### User Variable Persistence Source: https://github.com/aichaos/rivescript-js/blob/master/eg/README.md Shows how to achieve persistence for user variables, allowing the bot to remember its state with users even after shutdown and restart. ```javascript const RiveScript = require('rivescript'); const fs = require('fs'); const rs = new RiveScript({ storage: 'file', storageOptions: { folder: './data' } }); rs.loadDirectory('brain',). then(function() { rs.sortReplies(); // ... bot logic ... // Variables are automatically saved to ./data/user_variables.json }); ``` -------------------------------- ### Run npm uglify script Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Minifies the Webpack-generated JavaScript file. This command creates dist/rivescript.min.js. ```bash npm run uglify ``` -------------------------------- ### Initialize RiveScript with CoffeeScript Handler Source: https://github.com/aichaos/rivescript-js/blob/master/eg/coffeescript/README.md This code demonstrates how to import and register the CoffeeScript handler for RiveScript. It allows object macros to be written in CoffeeScript. ```javascript // If using Node, import these modules; if using the web, just embed their // .js files and `RiveScript` and `RSCoffeeScript` are both available on the // global window scope. var RiveScript = require("rivescript"), RSCoffeeScript = require("rivescript-contrib-coffeescript"); // Make your RiveScript bot instance. var bot = new RiveScript(); // Register the CoffeeScript handler. In this example we register the handler // for both "coffee" and "coffeescript", so that object macros that name either // one will both be handled. bot.setHandler("coffeescript", new RSCoffeeScript(bot)); bot.setHandler("coffee", new RSCoffeeScript(bot)); // Proceed to load replies, etc... bot.loadFile("brain.rive", function() { bot.sortReplies(); // ... }) ``` -------------------------------- ### Loading RiveScript from a Directory Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/rivescript.html Shows how to recursively load RiveScript documents from a directory using Promises. This function is not supported in web environments. ```JavaScript async loadDirectory (string path) ``` -------------------------------- ### Run npm clean script Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Removes all generated build files from the project directory. Use this to clean up artifacts. ```bash npm run clean ``` -------------------------------- ### loadDirectory Source: https://github.com/aichaos/rivescript-js/blob/master/docs/rivescript.md Asynchronously loads RiveScript documents from all files within a specified directory recursively. This method is not available in web environments. ```APIDOC ## loadDirectory(string path) ### Description Load RiveScript documents from a directory recursively. For backwards compatibility, this function can take callbacks instead of returning a Promise: > `rs.loadDirectory(path, onSuccess(), onError(err, filename, lineno))` This function is not supported in a web environment. ### Method N/A (This is a function call, not an HTTP method) ### Parameters - **path** (string) - The path to the directory containing RiveScript files. ### Response * resolves: `()` * rejects: `(string error, string filename, number lineno)` ``` -------------------------------- ### RiveScript Initialize Topic Method Signature Source: https://github.com/aichaos/rivescript-js/blob/master/docs/html/parser.html The `initTopic` method is a private helper function used to initialize the topic tree during the parsing phase. It sets up the topic structure within the AST. ```javascript private void initTopic (object topics, string name) ``` -------------------------------- ### Resolve OpenSSL legacy provider error Source: https://github.com/aichaos/rivescript-js/blob/master/README.md Sets the NODE_OPTIONS environment variable to use the legacy OpenSSL provider. This is a workaround for a common error on certain Fedora/Node.js versions. ```bash export NODE_OPTIONS=--openssl-legacy-provider ```