Password Generator performance : Python vs Javascript (Google apps script) - javascript

I created a random code generator script via Google apps script. My goal is to generate 6000 uniques random codes (in spreadsheet) as fast as possible.
The following javascript code crashes with Google spreadsheet + apps script --> too long to execute and the same code under python generates 20,000 random codes in less than 1 second... I'm not a JS ninja, do you have any idea to optimize the JS code below ?
Code JS
function main(nbre_car,nbre_pass,number,letter_maj,letter_min,spec_car){
var nbre_car = 6;
var nbre_pass = 6000;
var number = true;
var letter_maj = false;
var letter_min = false;
var spec_car = false;
var prefixe="FOULE";
return generate_password(nbre_car,nbre_pass,number,letter_maj,letter_min,spec_car,prefixe)
}
function combinaison_possible(char_number,lenght_possible_char){
combinaison_nbre=Math.pow(lenght_possible_char,char_number)
return combinaison_nbre
}
function generate_password(nbre_car,nbre_pass,number=true,letter_maj=false,letter_min=false,spec_car=false,prefixe="") {
if (Number.isInteger(nbre_car)&&Number.isInteger(nbre_pass)){
}
else{
return "Veuillez rentrer un nombre entier pour les champs en bleu"
}
var nbre_car = nbre_car || 10;
var nbre_pass = nbre_pass || 3;
var pass_number="123456789";
var pass_letter_maj="ABCDEFGHIJKLMNPQRSTUVWXYZ";
var pass_letter_min="abcdefghijklmnpqrstuvwxyz"
var pass_spec_car="'(-è_çà)=:;,!."
// Check entry type
// Create an empty map which will contain all password
var col = new Map([]);
var prefixe=prefixe;
var list_char='';
list_char= letter_maj == true ? list_char+pass_letter_maj : list_char
list_char= number == true ? list_char+pass_number : list_char
list_char= letter_min == true ? list_char+pass_letter_min : list_char
list_char= spec_car == true ? list_char+pass_spec_car : list_char
// Teste les combinaisons possible entre le nombre de caractère demandés pour le password et la liste disponible
if (combinaison_possible(nbre_car,list_char.length)>=nbre_pass) {
// Création des mots de passe unique
while(col.size===0||nbre_pass>col.size) {
Logger.log("col.size : "+col.size)
Logger.log("nbre_pass : "+nbre_pass)
search_new_pass=true;
while (search_new_pass==true){
pass=create_one_password(nbre_car,list_char,prefixe)
Logger.log('nom du password : '+pass)
if (verify_unique(col,pass)!=true)
col.set({}, pass);
Logger.log("valeur de col : "+col)
search_new_pass=false;
}
}
}
else{
col = [];
col.push("Vous avez demander trop de mots de passe, cela va créer des doublons,Veuillez diminuer le nombre de mots de passe à afficher");
}
final_values=[...col.values()];
//Logger.log('valeur final de col : '+final_values)
console.log(Array.from(col.values()));
return Array.from(col.values());
}
function create_one_password(nbre_car,list_char,prefixe) {
var nbre_car = nbre_car;
s = '', r = list_char;
for (var i=0; i < nbre_car; i++) {
s += r.charAt(Math.floor(Math.random()*r.length));
}
return prefixe+s;
}
Code Python
import random
def combinaison_possible(char_number,lenght_possible_char):
combinaison_nbre=pow(lenght_possible_char,char_number)
return combinaison_nbre
def generate_password(nbre_car,nbre_pass,number=True,letter_maj=True,letter_min=True,spec_car=True,prefixe="FOULE") :
if(not isinstance(nbre_car,int) and isinstance(not nbre_pass,int)) :
print( "Veuillez rentrer un nombre entier pour les champs en bleu")
nbre_car = nbre_car
nbre_pass = nbre_pass
pass_number="123456789"
pass_letter_maj="ABCDEFGHIJKLMNPQRSTUVWXYZ"
pass_letter_min="abcdefghijklmnpqrstuvwxyz"
pass_spec_car="!##$%^&*()_+"
prefixe=prefixe
list_char=''
col={}
longueur_col=len(col)
list_char= list_char+pass_letter_maj if letter_maj else list_char
list_char= list_char+pass_letter_min if letter_min else list_char
list_char= list_char+pass_number if number else list_char
list_char= list_char+pass_spec_car if spec_car else list_char
if (combinaison_possible(nbre_car,len(list_char))>=nbre_pass) :
while(len(col)==0 or nbre_pass>len(col)):
longueur_col=len(col)
search_new_pass=True
while (search_new_pass==True):
pass_word = prefixe+''.join(random.choice(list_char) for i in range(nbre_car))
if pass_word not in col:
col[longueur_col]=pass_word
search_new_pass=False
print (col)
else :
print("Le nombre de mot de passe à générer est trop important par rapport au nombre de caractères possible")
generate_password(6,20000)

Performance-wise, the main difference between the Apps Script and Python versions is that the Apps Script code logs about 20,000 values in the Apps Script console, which is slow, while the Python code outputs 1 value.
The Apps Script code has several syntactical and semantical errors, including:
verify_unique() is undefined
col.set({}, pass) does not make sense; perhaps use an Array instead of a Map, find if a value is already in the list with col.includes(pass), insert values with col.push(pass), and use col instead of Array.from(col.values()) to retrieve the values
var prefixe = prefixe; is superfluous
See Apps Script at Stack Overflow and Clean Code JavaScript.

I think the code could be quite a bit easier. I did not study your code extensively. But this would be my approach to solve the problem. As you can see it takes less than one second to generate 20'000 passwords.
What actually really takes a long time is the duplicate check.
Aside from thath be careful when generating passwords without a cryptographically secure random algorithm.
Please have a look at this for how to use Crypto.getRandomValues()
const CHARACTER_POOL =
"123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.";
const PASSWORDS_TO_GENERATE = 20000;
const PASSWORD_LENGTH = 6;
const PREFIX = "";
const createPassword = () => {
let password = "";
for (let i = 0; i < PASSWORD_LENGTH; i++) {
// this is not secure
password += CHARACTER_POOL.charAt(
Math.floor(Math.random() * CHARACTER_POOL.length)
);
}
return `${PREFIX}${password}`;
};
const generatePassword = () => {
const passwords = [];
while (passwords.length < PASSWORDS_TO_GENERATE) {
const password = createPassword();
if (!passwords.includes(password)) {
passwords.push(password);
}
}
return passwords;
};
const start = new Date().getTime();
const passwords = generatePassword();
console.log(`It took ${(new Date().getTime() - start) / 1000} to generate ${passwords.length} passwords`);
console.log(passwords);

That's a lot of code for what seems a pretty straightforward problem. I didn't look closely at your version, but here's how I might handle the problem. It creates 20000 in about 20 milliseconds on my mid-level machine.
const genPasswords = (chars) => (n, length = 6, pre = '') => Array .from (
{length: n},
() => pre + Array.from({length}, () => chars[~~(Math.random() * chars.length)]) .join('')
)
const pwdGen = genPasswords ("123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.")
console.time('generate 20000')
const res = pwdGen (20000, 6, 'FOULE')
console.timeEnd('generate 20000')
console .log (res)
.as-console-wrapper {max-height: 100% !important; top: 0}
I store the characters to use in a closure, returning a function that takes the number to generate, their length, and a prefix.

Related

Google script loop running only 1 loop (google sheets)

I have a strange behavior on my google script for a google sheet from a previous IT guy.
The for loop run for 1 iteration instead of 800+
I got an array of rows "invoiceRows" that i can see on the Logger.log
I can log the invoiceRow.length (800+ rows), the invoiceRow[0] and the invoiceRow[invoiceRow.length-1]. Everything is correct.
Then I do a very simple for loop for(var i=0 ; i<invoiceRow.length ; i++){
Inside the loop, i=0 => correct
Outside the loop, i=1 => correct, if there were only 1 item in the array
There is no break nor continue (well, there is one for security purpose, but the log is not displayed).
I have a try catch with a log on e, but there is no exception.
There were a while loop before, which didn't work neither.
What id does is pretty straight forward : get rows of invoices rows, for each: populate a template sheet, create a pdf, then set the pdf url at the end of the line
// BOUCLE DE TRAITEMENT DES DONNEES
Logger.log('BOUCLE - avant ; nb d\'itérations: '+invoiceRows.length);
for(var i=0 ; i<invoiceRows.length ; i++){
var currentRow = startRow+i;
Logger.log(' - boucle item #'+i+", row #"+currentRow+": "+invoiceRows[i]);
if(invoiceRows[i][0]==""){
Logger.log(' id vide => break');
break;
}
Logger.log(' id #'+i+": "+invoiceRows[i][0]);
if (true) { // une raison de ne pas traiter la ligne ? Déjà faite ?
templateSheet.getRange("F10").setValue(invoiceRows[0][headerObj["Account Billing Address"]].replace(/<br>/g, "\n"));
templateSheet.getRange("A17").setValue(invoiceRows[0][headerObj["Invoice: Name"]].split(" ")[0]);
templateSheet.getRange("A18").setValue(invoiceRows[0][headerObj["Invoice: Name"]]);
templateSheet.getRange("G18").setValue(invoiceRows[0][headerObj["Date"]]);
templateSheet.getRange("G14").setValue(invoiceRows[0][headerObj["Account Siret"]]);
templateSheet.getRange("G15").setValue(invoiceRows[0][headerObj["Account TVA"]]);
templateSheet.getRange("B20").setValue(invoiceRows[0][headerObj["Account RRF"]]);
templateSheet.getRange("A22").setValue(invoiceRows[0][headerObj["Title"]]);
templateSheet.getRange("D22").setValue(invoiceRows[0][headerObj["Princing - Per Unit"]]);
templateSheet.getRange("F22").setValue(invoiceRows[0][headerObj["Princing - Nb of units"]]);
templateSheet.getRange("A24").setValue(invoiceRows[0][headerObj["Princing - Modify label"]]);
templateSheet.getRange("G24").setValue(invoiceRows[0][headerObj["Princing - Modify value"]]);
//templateSheet.getRange("F38").setValue((invoiceRows[0][headerObj["Princing - TVA"]] || 0) / 100);
templateSheet.getRange("F38").setValue(invoiceRows[0][headerObj["Princing - TVA"]]+"%");
templateSheet.getRange("B42").setValue(invoiceRows[0][headerObj["Account Payment Terms"]]);
templateSheet.getRange("B45").setValue(invoiceRows[0][headerObj["Account Mode de paiement"]]);
templateSheet.getRange("F9").setValue(invoiceRows[0][headerObj["Account Commercial Name"]]);
templateSheet.getRange("D23").setValue(invoiceRows[0][headerObj["Princing - Flat Fee"]]);
templateSheet.getRange("B21").setValue(invoiceRows[0][headerObj["Campaign Scope"]]);
Logger.log('template updated');
var sheetToPrint = templateSheet.copyTo(dummySpreadsheet);
SpreadsheetApp.flush();
Logger.log('template copied into dummySpreadsheet');
var totalFromTable = invoicesSheet.getRange(currentRow, parseInt(headerObj["Total HT"], 10) + 1).getValue();
Logger.log('total HT: '+totalFromTable);
var totalTemplate = templateSheet.getRange("G36").getValue();
Logger.log('total HT calculé dans le template: '+totalTemplate);
// contrôle si montant ht est cohérent entre ligne et template => poursuivre
if (
parseFloat(templateSheet.getRange("G36").getValue()).toFixed(2) == parseFloat(totalFromTable).toFixed(2)
&& totalFromTable
) {
Logger.log("contrôle cohérent entre template et ligne");
var dummySheets = dummySpreadsheet.getSheets();
for (var b = 0; b < dummySheets.length; b++) {
if (dummySheets[b].getName() != sheetToPrint.getName()) {
dummySpreadsheet.deleteSheet(dummySheets[b])
}
}
var blob = dummySpreadsheet.getAs("application/pdf");
blob.setName(invoiceRows[0][1] + '.pdf');
var uid = null;
var printId = null;
if (!folder) {
var folder = DriveApp.getFolderById("fakegooglefolderid");
}
var file = folder.createFile(blob);
Logger.log("file: "+JSON.stringify(file, null, 2));
Logger.log('headerObj["Drive Link"]: '+JSON.stringify(headerObj["Drive Link"], null, 2));
invoicesSheet.getRange(currentRow, parseInt(headerObj["Drive Link"], 10) + 1).setValue(file.getUrl())
SpreadsheetApp.flush();
} // fin du contrôle cohérent total ttc
// cas où il n'y a pas de total ht
else if(!totalFromTable) {
invoicesSheet.getRange(currentRow, parseInt(headerObj["Error"], 10) + 1).setValue("Empty total value")
}
else if (parseFloat(templateSheet.getRange("G36").getValue()).toFixed(2) != parseFloat(totalFromTable).toFixed(2)) {
invoicesSheet.getRange(currentRow, parseInt(headerObj["Error"], 10) + 1).setValue("Values not matching")
}
else {
invoicesSheet.getRange(currentRow, parseInt(headerObj["Error"], 10) + 1).setValue("Unknown")
}
}
else{ // si ligne pas traitée
}
invoiceRows = invoicesSheet.getRange(currentRow, 1, 1, lastColumn).getDisplayValues();
Logger.log(' fin de boucle i='+i);
}
Logger.log('BOUCLE - après ; items traités: '+i);
The loop just don't run again as it should, until it reach the 800+ for(var i=0 ; i<invoiceRow.length ; i++){
The script was working last month, as it does for years. I really don't understand this behavior.
Is there a know bug with google sheet script ?
In the end, i just made another function from scratch, with pieces of code that interest me : get the array, loop on it x times, treat data.
And it works this way.
Why the code above don't ? I really don't understand.
Thanks for your attention everyone.

Problem when printing data from an object array, it appears incorrectly

I have this program where there are a series of registered students and when they put their name, their data and the name of the teacher they have assigned.
When inserting a new student, the only thing that it does to me correctly is to print if the teacher exists or not, since the student's data does not show them to me, and finally I have a failure in the last line of the javascript code related to innerhtml , the error in question is:
Uncaught TypeError: Cannot set properties of null (setting
'innerHTML')
at mensaje.js:74
now the code:
html:
<button onclick="infoalumno()">Informacion del alumno</button>
<button onclick="insertar()">Introducir nuevo alumno</button>
<div id="info"></div>
and javascript code:
function alumno(nombre, edad, nota, profesor) {
this.nombre = nombre;
this.edad = edad;
this.nota = nota;
this.profesor = profesor;
}
function profesor(nombre, asginatura) {
this.nombre = nombre;
this.asginatura = asginatura;
}
var profesores = new Array(3);
profesores[0] = new profesor("Paco","Plastica");
profesores[1] = new profesor("Anton","Biologia");
profesores[2] = new profesor("Jacinto","Lengua");
var alumnos = new Array(2);
alumnos[0] = new alumno("Jose",24,7,profesores[0]);
alumnos[1] = new alumno("Jacobo",23,7,profesores[2]);
function infoalumno() {
var buscar = prompt("Inserta el nombre del alumno que quieres buscar");
var comprobar = false
for (let i = 0; i < alumnos.length; i++) {
if (buscar == alumnos[i].nombre) {
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor.nombre);
comprobar = true;
}
if (comprobar == false) {
document.write("Alumno " + buscar + "no existe");
}
}
}
function insertar() {
var comprobar2 = false;
var nombre = prompt("Insertar el nombre del alumno");
var edad = parseInt(prompt("Ingresa la edad"));
var nota = parseInt(prompt("Ingresa la nota"));
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor[i]);
alumnos.push(newalumno);
comprobar2=true;
break;//la sentencia break permite terminar de forma abrupta un bucle y la sentencia continue permite saltarse algunas repeticiones del bucle. ... La utilidad de break es terminar la ejecución del bucle cuando una variable toma un determinado valor o cuando se cumple alguna condición.
}
}
if(comprobar2==false){
document.write("Profesor "+profesor+" no existe");
}
}
var infoprofesor ="Profesores";
for (let i = 0; i < profesores.length; i++) {
infoprofesor = infoprofesor + profesores[i].nombre+"<br>";
}
document.getElementById("info").innerHTML = infoprofesor;
1)
The teacher does not appear his name instead appears [object Object]
In this code
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor);
This alumnos[i].profesor will be a Profesor object like from calling new Profesor(...). If you wanted to show the name it would look like alumnos[i].profesor.nombre
2)
And when inserting a new student, the only thing that it does to me
correctly is to print if the teacher exists or not.
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor);
alumnos.push(newalumno);
comprobar2=true;
break;
}
}
In this loop you have a related issue. The result from prompt will just be a string (your var profesor). However when you go to make your new alumno it expects a profesor object (with nombre/asignatura).
In this case you're probably want to do var newalumno = new alumno(nombre, edad, nota, profesores[i]);

.indexOf is not a function - Sum the total amount of a shopping cart

I am building a shopping cart and I am having issue getting the total amount of it.
let calculPrice = [];
for (productLocalStorage of productLocalStorage) {
let article = productLocalStorage.prix;
calculPrice.push(article);
};
const reducer = (accumulator, currentValue) => accumulator + currentValue;
const totalPrice = calculPrice.reduce(reducer, 0);
console.log(totalPrice);
To get the total amount I've created a loop which work fine but I have an error when I try to delete an item
"cart.js:77 Uncaught TypeError: productLocalStorage.indexOf is not a function
at HTMLButtonElement.<anonymous> (cart.js:77)"
This is my event from my delete button
let reachDeleteButton = document.querySelectorAll(".product-delete");
console.log(reachDeleteButton);
//Creation d'un tableau vide
let tab = [];
for (let i = 0; i < reachDeleteButton.length; i++){
reachDeleteButton[i].addEventListener("click", (event) => {
event.preventDefault();
//Récupération de l'index du produit associé au bouton supprimer
let getIndexOnLocalStorage = productLocalStorage.indexOf(productLocalStorage[i]);
console.log(getIndexOnLocalStorage);
tab = productLocalStorage
let response = confirm("Vous allez retirer ce produit de votre panier, voulez-vous continuer?")
if (response == true ) {
tab.splice(getIndexOnLocalStorage, 1)
productLocalStorage = localStorage.setItem("product", JSON.stringify(tab));
window.location.href ="cart.html";}
else {
}
})
}

Html and Javascript with google script function error

with Google Script i have created this html that send datas to a google sheet taking in input some data from the url (after /exec?P=tonno&Q=3&C=Cliente+1 he takes in input P,Q,C):
<!DOCTYPE html>
<html>
<head>
<title> Modulo di Ordine </title>
<script type="text/javascript">
function doGet(e){
//HtmlService.setTitle("This is MYTITLE");
var result = '<-- Riepilogo Ordine --> \n';
if (e.parameter == 'undefined') {
result += "ERRORE SCONOSCIUTO NELL'ACQUISTO! non verrà inviato l'ordine";
return ContentService.createTextOutput(result);
}
else {
var ID = '1sl0P4auOdX8i67kZ9LA8dGXm59I_fc_tSOaPaOpL1Ek'; // identificativo della cartella di foglio (Spreadsheet ID)
// var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
// var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var Cartella = SpreadsheetApp.openById(ID); // Cartella identificata da ID
var Foglio = Cartella.getSheets()[0]; // nella parentesi quadra il foglio ---> 0 = primo, 1 = secondo, ecc.
var Cella_R = Foglio.getRange(2,5); // riga 2, colonna 5 -> cella E2
var Inserite = Cella_R.getValue() + 1; // numero di righe inserite (letto dal foglio) incrementato di 1
Cella_R.setValue(Inserite); // scrive nel fogio il valore incrementato di «Inserite»
// var Riga = Foglio.getLastRow() + 1;
var Riga = Inserite + 2; // Riga in cui scrivere i dati
result += 'Codice Ordine: #' + Riga; // calcola la riga su cui scrivere i dati
var Cella_D = Foglio.getRange(Riga,1); // D = Data --------------> colonna 1
var Cella_O = Foglio.getRange(Riga,2); // O = Orario ------------> colonna 2
var Cella_T = Foglio.getRange(Riga,3); // T = Temperatura -------> colonna 3
var Cella_U = Foglio.getRange(Riga,4); // U = Umidità relativa --> colonna 4
var Cella_C = Foglio.getRange(Riga,5); // C = Cliente ----------->
var answer = "";
// SpreadsheetApp.setActiveSheet(sheet);
// var rowData = [];
var Giorno_Ora = new Date(); // legge data ed ora attuali
var Data = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'dd/MM/yyyy'); // estrae la data da Data_Ora
var Orario = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'HH.mm.ss' ); // estrae l'orario da Data_Ora
Cella_D.setValue(Data); //scrive la Data
Cella_O.setValue(Orario); //scrive l'orario
for (var parametro in e.parameter) {
var valore = Pulisci(e.parameter[parametro]); //estrae il valore del paramentro senza virgolette
switch (parametro) { // condizione case
case 'P':
Cella_T.setValue(valore); // Scrive il prodotto
result += '\nProdotto: ' + valore + ''; // Scrive messaggio risposta
break;
case 'C':
Cella_C.setValue(valore); // Scrive il cliente
result += '\nCliente: ' + valore + ''; // Scrive messaggio risposta
break;
case 'Q':
Cella_U.setValue(valore); // Scrive la quantità
result += '\nQuantità: ' + valore + ' pezzi'; // Scrive messaggio risposta
break;
default: //in caso di errore:
result += "\n\nParametri non validi!. L'ordine non verrà preso in considerazione";
}
} //se tutto va bene passa avanti con il successo
result += '\n\nEseguito con successo! Qualcuno provvederà a prendere in considerazione il suo ordine.';
}
return ContentService.createTextOutput(result); // Restituisce il Riepilogo dell'ordine
}
function Pulisci( value ) {
return value.replace(/^["']|['"]$/g, ""); // sostituisce cosa a cosa???
}
</script>
</head>
<body>
<p>Sicuro di voler procedere con l'ordine?</p> <br>
<input id="clickMe" type="button" value="clickme" onclick="doGet();" />
</body>
</html>
The problem is that when I press the button to call the function doGet(), this is the error and the function doesn't go on:
userCodeAppPanel:5 Uncaught TypeError: Cannot read property 'parameter' of undefined
at doGet (userCodeAppPanel:5)
at HTMLInputElement.onclick (userCodeAppPanel:1)
Can pls somebody help me?
ContentService, SpreadsheetApp, and even doGet(e) are server side functions they run on a Google Server not on your browser. You need to restructure your entire code and utilize some intermediate javascript functions and possibly google.script.run you would be well served to do a little more research in some of the examples provided here at SO.
The idea of using doGet(e) as a clientside function is rather ridculuous because the whole idea is that it's supposed to be an endpoint on the server. It's ridiculous to consider it as a clientside function.
To resolve the issue you are facing, you need to change your button HTML element to the below code -
<input id="clickMe" type="button" value="clickme" onclick="doGet(event);" />
Since you are using inline event handler, you need to pass the event as argument to onClick method. Please refer to this post in-case you have any queries.

HTML visible in chat

I have a problem when writing a html code in chat that appears in the box, this is dangerous and ugly to see, is there any javascript or html code to block html and cone files ?
if I write on the text input a html code such as appears in the box ie the code works, how do I block there is a way or some code to paste in the text?
Here is input:
<input type="text" name="chat" id="chattbox" placeholder="Ask what you want." onfocus="placeHolder ()">
var messages = [],
lastUserMessage = "",
botMessage = "",
botName = 'Jacob', t
talking = true;
function chatbotResponse() {
talking = true;
botMessage = "non ho capito";
var hi = ['Ciao {$mybb->user['username']}','mhhh','forte','haha','Chi sei?', 'mi vuoi bene?', 'Sono un bot questo non significa che io sia scemo', 'grande', 'boh', 'bah...', 'sei forte haha', 'ti piace stertix?', 'ok','se lo dici tu.','come vuoi', 'ho fame', 'Mi sto pulendo il naso... Quello che non ho :(', 'Hai ragione', 'Sei un grande', 'aaahhhhhhh!!!', 'mlmlml', 'cavolo', 'wow', 'figo', 'come mai?', 'forse', 'Si', 'No', 'mi piace parlare con te <3', 'spacco bottilia ammazzo familia', 'ti amo', 'ti voglio bene', 'che canzone ti piace?', 'che cantante ti piace?', 'so che pensi che sia stupido ma non lo sono.', 'ma lo sarai tu.', 'va bene', 'bello', 'molto', 'molto bello', 'cosa ne pensi di stertix?', ':D', ':)', ';)', '<3', ':O', 'Che fai?', 'quale?', 'quale', 'eh', 'grave', 'eccellente', 'giusto', 'grazie', 'eccellente', 'ottimo', 'ue guaglio bell stu orolog',];
botMessage = hi[Math.floor(Math.random()*(hi.length))];
var n = lastUserMessage.search(/\b(gatto|gatti)\b/i);
if (n !== -1) {
botMessage = 'Amo i gatti!';
}
var n = lastUserMessage.search(/\b(ciao|salve|ehi|we)\b/i);
if (n !== -1) {
var vr = ['Ciao {$mybb->user['username']}!', 'Ciao fra', 'Ciao amico', 'ehi {$mybb->user['username']}!', 'We {$mybb->user['username']}!',];
botMessage = vr[Math.floor(Math.random()*(vr.length))];
}
var n = lastUserMessage.search(/\b(bene)\b/i);
if (n !== -1) {
var vr = ['Ottimo','Meglio cosi', 'Mi fa piacere',];
botMessage = vr[Math.floor(Math.random()*(vr.length))];
}
var patt = /\b(cani)\b/i;
var result = patt.exec(lastUserMessage);
if (result) {
botMessage = 'Amo i ' + result[0];
}
var n = lastUserMessage.search(/\b(animali)\b/i);
if (n !== -1) {
botMessage = 'Amo gli animali!';
}
var n = lastUserMessage.search(/\b(come va|come stai)\b/i);
if (n !== -1) {
var vir = ['Benissimo, tu?','Bene dai...', 'bene tu?', 'male, tu?', 'Malissimo, tu?', 'diciamo, tu?',];
botMessage = vir[Math.floor(Math.random()*(vir.length))];
}
var n = lastUserMessage.search(/\b(che fai|che stai facendo)\b/i);
if (n !== -1) {
var vuyr = ['Nulla, parlo con te, tu che fai?','Niente, tu?', 'Mi annoio, tu?', 'Mi vedo film zozzi, tu?', 'cerco un modo per conquistare il mondo... na scherzo sono un bot pirla, tu che fai?', ];
botMessage = vuyr[Math.floor(Math.random()*(vuyr.length))];
}
I've commented the code -- basically, if a user enters a < and then, at some point later, types a > then everything between them is stripped out by regex. From what you're describing, this seems like what you're looking for.
var filterHtmlCodes = function() {
/*****
* Here, we're going to go through and strip
* any tags -- words wrapped in <>. Thus,
* users can still enter either symbol, but
* entering both will immediately strip the
* tag value. I'm triggering on every
* keyup, but it could as easily be done on every
* change, so as to block copy/paste, for example.
*****/
myChatEl.value = myChatEl.value.replace(/<(?:.|\n)*?>/gm, '')
};
// And I prefer to add my listeners outside of my HTML.
var myChatEl = document.querySelector("#chattbox");
myChatEl.addEventListener("keyup", filterHtmlCodes)
<input type="text" name="chat" id="chattbox" placeholder="Ask what you want.">

Categories

Resources