-
Notifications
You must be signed in to change notification settings - Fork 6
Preserving the Original Message
A common question I've seen asked is "how do I get access to the user's original message that was passed in? The version of the message before it was run through substitutions, made lowercase, and had special symbols removed from it." Often this is because the bot developer is writing an object macro and needs the user's message to be left intact -- for example to accept a floating-point number from the user (the decimal would be removed normally).
Put their original message into a user variable using the setUservar()
function of your RiveScript interpreter, and then retrieve the value inside your object macro.
# Where your code gets the reply from your bot, copy their
# message into a user variable that can be retrieved later:
bot.setUservar(username, "origMessage", message);
var reply = bot.reply(username, message);
Then, an object macro can look up their original message: casing and symbols included.
// Say you wanted the bot to be able to do floating-point math, but the
// decimal place in the user's message normally gets stripped out...
+ what is * divided by *
- <call>floating_point_divide</call>
> object floating_point_divide javascript
// To retrieve the user's original message:
var orig = rs.getUservar( rs.currentUser(), "origMessage" );
// Note that the origMessage is the *full* original message, so
// you need to re-parse the wildcards out.
var match = orig.match(/what is (-?[0-9\.]+) divided by (-?[0-9\.]+)/i);
if (match == undefined) {
return "Those don't look like valid numbers.";
}
var a = parseFloat(match[1]);
var b = parseFloat(match[2]);
if (a === NaN || b === NaN) {
return "Those don't look like valid numbers.";
}
if (b === 0) {
return "I can't divide by zero.";
}
return a + " / " + b + " = " + (a / b);
< object
Example output:
You> What is 5 divided by 2?
Bot> 5 / 2 = 2.5
You> What is 3.1415 divided by 1.06
Bot> 3.1415 / 1.06 = 2.9636792452830187
You> What is 8 divided by 0?
Bot> I can't divide by zero.
You> What is 8 divided by 0.00?
Bot> I can't divide by zero.
You> What is A divided by C?
Bot> Those don't look like valid numbers.
The original message stored this way would be the user's full message, without any wildcards parsed out. So in the above example I had to use my own regular expression to parse the user's message, because the wildcards used in the trigger were derived from the user's formatted message, so they would have lost their original symbols and formatting.