Add confirm prompt in another language - javascript

How to add the confirm Prompt and Good bye message in another language based on user choice of language. Lets say I want to add a spanish version thats says goodbye
.cancelAction(
"cancelRequest", "Thank you for reaching out, Good bye!",
{
matches: /^nevermind$|^cancel$|^cancel.*request/i,
confirmPrompt: "This will cancel your request. Are you sure?"
}
);

You can do this using a variable which value is set depending on the language. This variable can then be used to get the corresponding text from an object.
For example:
var language = "spanish";
var cancelTextFromLang = {
spanish: "Gracias por comunicarte, ¡Adiós!",
english: "Thank you for reaching out, Good bye!",
french: "Merci d'avoir tendu la main, au revoir!"
};
console.log(cancelTextFromLang[language])
You can apply this to your given code like so:
var language = "spanish";
var cancelTextFromLang = {
spanish: "Gracias por comunicarte, ¡Adiós!",
english: "Thank you for reaching out, Good bye!",
french: "Merci d'avoir tendu la main, au revoir!"
};
.cancelAction(
"cancelRequest", cancelTextFromLang[language],
{
matches: /^nevermind$|^cancel$|^cancel.*request/i,
confirmPrompt: "This will cancel your request. Are you sure?"
}
);

Im using session.userData.languagePreference and Im thinking to add an if statement inside the cancelAction but the syntax is wrong, I cant put the if statement there :/
.cancelAction(
if ( session.userData.languagePreference = 0;) {
"cancelRequest", "Thank you for reaching out, Good bye!",
{
matches: /^nevermind$|^cancel$|^cancel.*request/i,
confirmPrompt: "This will cancel your request. Are you sure?"
}
);

The Bot Framework supports localization. You can read about how to do this in Node here. This page will explain how to determine the language for the bot user either via prompting the user or automatically. it also describes how to add the language strings for your prompts.
They key to bot localization is the session.preferredLocal() method. This method saves and gets the user specific locale preference.
The easiest method to determine the language locale and set it is to prompt the user. Here's a Node example
bot.dialog('/localePicker', [
function (session) {
// Prompt the user to select their preferred locale
builder.Prompts.choice(session, "What's your preferred language?", 'English|Español');
},
function (session, results) {
// Update preferred locale
var locale;
switch (results.response.entity) {
case 'English':
locale = 'en';
break;
case 'Español':
locale = 'es';
break;
}
session.preferredLocale(locale, function (err) {
if (!err) {
// Locale files loaded
session.endDialog(`Your preferred language is now ${results.response.entity}`);
} else {
// Problem loading the selected locale
session.error(err);
}
});
}
]);
The first part of this code prompts the user for their preferred language and gives them English and Spanish as the two option available. Based on the user response, the locale code is then set by calling session.preferredLocale().
In order to make use of the user's preferred locale, you will need a corresponding localization prompt file. These files will contain the various bot prompts in the corresponding language. You will need one file per language you intend on supporting.
Normally, these files will be in ./locale/{language}/index.json where {language} is the language code, (ex 'en' or'es'). The files are json and will look like this:
for English
{
"greeting": ["Hello!", "Hi there"]
}
and for Spanish
{
"greeting": ["Hola!", "Hola"]
}
Here is an example of how you code would look
var bot = new builder.UniversalBot(connector, [
function (session) {
session.send("greeting");
session.beginDialog('/localePicker');
},
function (session) {
builder.Prompts.text(session, "text_prompt");
}
]);
Behind the scenes, what's basically happening,the index.json file returned by session.preferredLocale() is searched for the prompt, if it finds one, it returns that otherwise it will return the prompt set for the default locale.

Related

Passing information from inquirer prompt to another function? Node.js

Just getting back to coding and doing some practice on some fun code I came across from a friend.
I am using inquirer to ask the user what attack they would like to use. I then want to pass that information into another function.
I am having trouble finding a way to take the option from the array that the user chooses, and use it outside of the attackPrompt function.
Almost anything helps. Thanks.
let attacks = [
"Slap",
"Bite",
"Kick",
]
function attackPrompt() {
let attackChoice = [{
name:"attack",
type:"list",
message:"Choose your attack.",
choices: attacks
}]
inquirer.prompt(attackChoice).then((answer) => {
attackChosen(attackOption);
console.log("MY STRING HERE", answer.attack)
//trying to make a function where I can pass the information to another maybe?
function attackChosen() {
let optionFromChooseAttack = answer
// console.log("I PUT THIS STRING HERE", optionFromChooseAttack)
}
})
}
attackPrompt();

Only allow certain fields (Firestore Rules)

Im trying to create a rule that only allows certain fields to be updated within my firestore rules, so I thought about doing a function like so:
function checkFieldsSent() {
for(field in request.resource.data) {
if (!(field in ['userRole', 'userName', 'messageType', 'userMessage', 'userHonourLevel', 'userAvatar', 'userChatPosted', 'userLevel', 'userChatMessage'])) { return false }
}
return true
}
of course as you can imagine, firestore moans about the use of "FOR" and "Return" within that function.
Does anyone know a solution? So if the request comes through with fields that ARE NOT ALLOWED to be updated it disallows the update.
Kind Regards,
Josh
Loops are not allowed in the rules. But there is a new data type available since February that gives a nice solution: Map.Diff.
function checkFieldsSent() {
let forbiddenfields = ['userRole', 'userName', 'messageType', 'userMessage', 'userHonourLevel', 'userAvatar', 'userChatPosted', 'userLevel', 'userChatMessage'];
return !request.resource.data.diff(resource.data).affectedKeys().hasAny(forbiddenfields);
}
More details here

Paylike modal amount parameter

I'm currently testing the paylike's web sdk and I can use the sandbox easy. But how can I avoid the user can change the amount on the client side? The amount parameter is required, but how can I ensure about after a success callback about the amount? Can I get it from the server side?
The following code is fine, but I have problem with the amount parameter
<script src="//sdk.paylike.io/3.js"></script>
<script>
var paylike = Paylike('your key');
paylike.popup({
currency: 'DKK',
amount: 1000,
}, function( err, res ){
if (err)
return console.log(err);
console.log(res.transaction.id);
alert('Thank you!');
});
</script>
Two steps are important regarding transactions. The first step is authorization.
Authorization is done with the code you added here, on the frontend. The user can tamper with the amount, but this is merely a reservation and is not taking funds from the payer credit card.
The second step is called capture. You can only capture the funds from the Paylike dashboard, or via your server. When you do that, you generally send the same amount that you initially wanted the user to pay, and if the authorization were less, you would get an error. You can also fetch the transaction to inspect the amount that was authorized if you want to reject an order, for example. You can also send a custom parameter that you might use to validate on the server, similar to a checksum if you want to.
You have a private key, which users are not able to get, so that makes it safe. The 2 step approach is a validation on its own, but as I mentioned, you can also inspect the transaction.
You can check the API docs here: https://github.com/paylike/api-docs, where you will also find links to client-side SDKs.
If you are using PHP, using the PHP library (which I maintain) you can do this to inspect a transaction:
$paylike = new \Paylike\Paylike($private_api_key);
$transactions = $paylike->transactions();
$transaction = $transactions->fetch($transaction_id);
The transaction variable will look like this:
{
"id":"5da8272132aad2256xxxxxxx",
"test":true,
"merchantId":"594d3c455be12d547xxxxxx",
"created":"2019-10-17T08:32:34.362Z",
"amount":35,
"refundedAmount":0,
"capturedAmount":0,
"voidedAmount":0,
"pendingAmount":35,
"disputedAmount":0,
"card":{
"id":"5da82743735e61604xxxxxxx",
"bin":"410000",
"last4":"0000",
"expiry":"2023-11-30T22:59:59.999Z",
"code":{
"present":true
},
"scheme":"visa"
},
"tds":"none",
"currency":"JPY",
"custom":{
"email":"customer#example.com",
"orderId":"Could not be determined at this point",
"products":[
[
{
"ID":"48",
"name":"Hoodie with Pocket",
"quantity":"1"
}
]
],
"customer":{
"name":"John Doe",
"email":"customer#example.com",
"phoneNo":"020 91X XXXX",
"address":"123 Main Street, New York, NY 10030",
"IP":"10.0.2.2"
},
"platform":{
"name":"WordPress",
"version":"5.2.4"
},
"ecommerce":{
"name":"WooCommerce",
"version":"3.7.1"
},
"paylikePluginVersion":"1.7.2"
},
"recurring":false,
"successful":true,
"error":false,
"descriptor":"PHP API WRAPPER TEST",
"trail":[
]
}

JavaScript search not allowing for zero

Please see the Sample Fiddle
If you enter either of the example codes in the search box, you'll get a result that pops up in a jQuery UI Dialog.
The first example is 006.
Here's the code...
if (ccode == 006) {
sarcomment = '006';
sardefinition = 'If you need to make corrections to your information, you may either make them online at www.fafsa.gov, or by using this SAR. You must use your Federal Student Aid PIN to access your record online. If you need additional help with your SAR, contact your school’s financial aid office or visit www.fafsa.gov and click the “Help” icon on the FAFSA home page. If your mailing address or e-mail address changes, you can make the correction online or send in the correction on your SAR. ';
saractionneeded = 'N/A';
}
Immediately after that, you'll see the code for code 030.
Here's the code...
if (ccode == 030) {
sarcomment = '030';
sardefinition = 'We are unable to read all of the information on your FAFSA or SAR because it was damaged. Please review all of the items on this SAR and make any corrections as needed.';
saractionneeded = 'N/A';
}
The set up for the code 006 and 030 are the same. What I've learned here is that any of these search criteria that I create that ends with a 0 (zero), will result in an undefined query.
Not sure how to resolve this and seeking your assistance.
Numbers that begin with a 0 in old & backward compatible versions of JavaScript are octal.
030 = 0*8^2 + 3*8^1 + 0*8^0 = 24
Strict mode turns octal numbers into a syntax error
Here's a suggestion for cleaning up that code. Instead of a long train of if statements — each one of which provides a chance for some subtle bug to creep in — you could instead use an object to map codes onto blocks of information. That would look something like this:
function showc_code(ccode){
var codeTable = {
'006': {
definition: 'If you need to make corrections to your information, you may either make them online at www.fafsa.gov, or by using this SAR. You must use your Federal Student Aid PIN to access your record online. If you need additional help with your SAR, contact your school’s financial aid office or visit www.fafsa.gov and click the “Help” icon on the FAFSA home page. If your mailing address or e-mail address changes, you can make the correction online or send in the correction on your SAR. ',
action: 'N/A'
},
'030': {
definition: 'We are unable to read all of the information on your FAFSA or SAR because it was damaged. Please review all of the items on this SAR and make any corrections as needed.',
action: 'N/A'
},
'040': {
definition: 'Whatever',
action: 'Something something'
},
// ... other codes ...
};
if (codeTable[ccode] != null) {
sarcomment = ccode;
sardefinition = codeTable[ccode].definition;
saractionneeded = codeTable[ccode].action;
}
else {
// unknown code ... do whatever
}
// ... rest of your code to show the dialog ...
}
That way the mapping from code to relevant information is just data, with no "moving parts".

Writing script for states and capitals

I'm trying to learn Javascript, and I need help with this question that i have been pondering on for a while now.
I need help with writing a script that prompts for the abbreviation of a New England state and alerts the capital of that state. For example if your user inputs NH, your script should alert Concord.
Only using the most simple JavaScript:
var capitals = { ME: "Augusta", NH: "Concord", VT: "Montpelier", MA: "Boston", CT: "Hartford", RI: "Providence" };
var abb = prompt('Abbreviation?');
alert(capitals[abb]);
There are a couple ways you could do this: if you want to use javascript exclusively, you have two options:
Store the associated values in a javascript object
var capitals = {AL:"Montgomery",AK:"uhhh..alaska's capital",...};
and then your function might look like this:
function GetCapitalFor(abbr){
alert(capitals[abbr]);
}
Use a third party library
I don't know of one in particular, but I'm sure one exists.
If you are also working with a server, you could store the pairs in a database and then run the function on the server (probably using AJAX). Something like this:
$.ajax({
type:"POST",
data: {abbreviation: abbr}, //where abbr is the user's input (MAKE SURE TO SANITIZE)
success: function(result)
{ alert(result);}
});
and on the server side, you'll query a database table for the abbreviation.
For something as trivial as this though, I'd probably just go with option 1.

Categories

Resources