is there a way to make my code non case sensitive - node.js

I'm trying to make a bot able to read an input automatically, no need for a command and then check the input against a list of defined words. I have managed to get this working but i'm having trouble in such a way that if anything varies from the word on the list, the bot ignores it. Code is as follows, all help is appreciated:
bot.on('message', message => {
for (i = 0; i < blacklist.length; i++)
{
//var check = blacklist[i].trim();
if (blacklist[i].trim().length > 0){
var lookup = '\\b'+blacklist[i]+'\\b';
var re = new RegExp(lookup);
var foundpos = message.content.search(re)
if(foundpos >=0) {
message.delete();
break;
}}}
for(i in blacklist) {
console.log(blacklist[i]);
}
})

Related

Wait for a function to create modified Array

I'm writing React app. After clicking one button, I want the file to be downloaded. Before that, the array that I have has to be modified in order to have the downloaded report in proper format.
The problem I have is that I don't know how to force getReports() to wait for setInOrder() to process the data. Therefore code doesn't enter the loop.
export const setInOrder = async (objects) => {
var sortedObjectsAll = new Object();
for (let i = 0; i < objects.length; ++i) {
if (sortedObjectsAll.hasOwnProperty(objects[i].addedBy)) {
sortedObjectsAll[objects[i].addedBy].push(objects[i]);
} else {
sortedObjectsAll[objects[i].addedBy] = new Array();
}
}
return sortedObjectsAll
}
export const getReports = async (objects) => {
const sortedObjectsAll = await setInOrder(objects) // This is correct but not available instantly
console.log(sortedObjectsAll) // this is correctly printed
const reports = new Array();
for (let j = 0; j < sortedObjectsAll.length; ++j) {
console.log("Never enters here")
reports.push(createReport(sortedObjectsAll[j]))
}
return reports
}
I'm trying to use await or async somehow, but can't solve it. I see some Promises advised but I don't know how to really return the resulting variable to the code that actually downloads the report.
First you do not need to write an async-await something like that, because it is not an async operation (and if you write one and do not have any await in it, it will wait for nothing).
Second you want to iterate through an object, and not through an array, and that is the problem. Replace with the following (there are other solutions as well):
for (const key in sortedObjectsAll) {
...
}

Handling playlist with youtube-sr gone wrong

Okay, so I need to handle a youtube playlist link because I need the video id for each of the videos. But as always something goes terribly wrong, the built-in function called getPlaylist is trying to parse the playlist details to JSON, but it's filtering code isn't that right and it tries to parse this
I only want the JSON object that is colored blue, not the gibberish in red. How can I do it?
static getPlaylist(html, limit = 100) {
if (!limit || typeof limit !== "number") limit = 100;
if (limit <= 0) limit = 100;
const videos = [];
let parsed;
let playlistDetails;
try {
const rawJSON = `${html.split("{\"playlistVideoListRenderer\":{\"contents\":")[1].split("}],\"playlistId\"")[0]}}]`;
parsed = JSON.parse(rawJSON);
let log = html.split("{\"playlistSidebarRenderer\":")[1].split("\n")[0].slice(0, -3)
console.log(log);
// This is the part where it crashes because it tries to convert the JSON and the gibberish
playlistDetails = JSON.parse(html.split("{\"playlistSidebarRenderer\":")[1].split("\n")[0].slice(0, -3)).items;
} catch (e) {
return null;
}
These are a few lines of code that I need to work, how can I filter out the gibberish?
I got it working thanks to #Cannicide.
I just added a split with the starting data of the gibberish
playlistDetails = JSON.parse(html.split("{\"playlistSidebarRenderer\":")[1].split("\n")[0].slice(0, -3).split("}};</script><link rel=\"alternate\" media=\"handheld\" href=\"https://m.youtube.com/playlist?list=")[0]).items;

Nodejs Webdav read multiple files (Problem with Array)

I am starting using NodeJs and webdav, I am using websockets to receive a list with the names of the images that I need to send to my app and then I have a for loop to send them to my app, but for some reason some of the images are undefined.
I am starting using NodeJs and webdav so I have no idea what's wrong.
for(let i = 0; i < ImagemList.length; i++){
wfs.readFile(ImagemList[i], "binary", function(err, data) {
Imagens[i] = data;
if(Imagens.length == ImagemList.length){
socket.emit("ImagemPost", Imagens);
}
});
}
For some reason I can't acess the variable "i" and for some reason the data was going to a random place leaving empty spots.
I've updated the code and it still goes to random places (don't know why) but doesn't leave any empty spot.
My array is still random if someone can help me.
Imagem = Imagem.replace("[", "");
Imagem = Imagem.replace("]", "");
let ImagemList = Imagem.split(", ");
let Imagens = [];
let contador = 0;
for(let o = 0; o < ImagemList.length; o++){
wfs.readFile(ImagemList[o], "binary", function(err, data) {
Imagens[contador] = (data);
contador++;
if(Imagens.length == ImagemList.length){
socket.emit("ImagemPost", Imagens);
}
});
}

Using socketio-file-upload to upload multiple files

Im using NodeJS with socket.io and socketio-file-upload to upload multiple files, it works great! However I'm having an issue where I'm trying to save the name attribute of the input these files come to save them into my DB.
When I upload 1 or more files, I can't seem to access the input field name or something that shows me which of the files come from which input field.
Here is my front:
var uploader = new SocketIOFileUpload(socket);
var array_files_lvl_3 = [
document.getElementById("l3_id_front"),
document.getElementById("l3_id_back"),
document.getElementById("l3_address_proof_1"),
document.getElementById("l3_address_proof_2"),
document.getElementById("l3_passport")
];
uploader.listenOnArraySubmit(document.getElementById("save_level_3"), array_files_lvl_3);
And here is my back:
var uploader = new siofu();
uploader.dir = "uploads/userL3";
uploader.listen(socket);
uploader.on('saved', function(evnt){
console.log(evnt);
//this "event" variable has a lot of information
//but none of it tells me the input name where it came from.
});
This is what the "evnt" variable holds:
Unfortunately the library doesn't send that information. So there is nothing existing config you can do. So this needs code modification.
client.js:374
var _fileSelectCallback = function (event) {
var files = event.target.files || event.dataTransfer.files;
event.preventDefault();
var source = event.target;
_baseFileSelectCallback(files, source);
client.js:343
var _baseFileSelectCallback = function (files, source) {
if (files.length === 0) return;
// Ensure existence of meta property on each file
for (var i = 0; i < files.length; i++) {
if (source) {
if (!files[i].meta) files[i].meta = {
sourceElementId: source.id || "",
sourceElementName: source.name || ""
};
} else {
if (!files[i].meta) files[i].meta = {};
}
}
After these changes I am able to get the details in event.file.meta
I'm the author of socketio-file-upload.
It looks like the specific input field is not currently being recorded, but this would not be a hard feature to add. Someone opened a new issue and left a backpointer to this SO question.
A workaround would be to directly use submitFiles instead of listenOnArraySubmit. Something like this might work (untested):
// add a manual listener on your submit button
document.getElementById("save_level_3").addEventListener("click", () => {
let index = 0;
for (let element of array_files_lvl_3) {
let files = element.files;
for (let file of files) {
file.meta = { index };
}
uploader.submitFiles(files);
index++;
}
});

Node.js while loop return deffered result

What I'm trying to do is this, I have 2 users an attacker and a defender. I want the call hit() function until one of the runs out of Health, hit() should be called on turns, first attacker, then defender, then attacker and so on until one reaches 0 hp.
My idea was to do it with a while loop, with current code all I get is the console.log from hit(), an infinite loop. The data from hit() is returned correctly if it's not inside a loop ... I could simply just work in the while loop and not use the hit function but it would mean repeating a lot of code, since there will be a few things to consider before a hit actually happens.
If you have an alternative to the while loop I'm open to ideas, also I should mention I'm new at node so keep it as simple as possible please. Thank you.
This is the relevant part of the code:
var prepareAttack = function(attacker,defender) {
connectdb().done(function(connection) {
query(connection,'SELECT * FROM members WHERE name = ?', attacker).done(function(result) {
var attackerData = result[0][0]
query(connection,'SELECT * FROM members WHERE name = ?', defender).done(function(result) {
var defenderData = result[0][0]
var attackerHp = attackerData.hp
var defenderHp = defenderData.hp
while(attackerHp > 0 && defenderHp > 0) {
hit(attackerData,defenderData).done(function(result){
defenderHp = result;
console.log(defenderHp)
})
hit(defenderData, attackerData).done(function(result) {
attackerHp = result;
console.log(attackerHp)
})
}
})
})
})
}
var hit = function (attackerData, defenderData) { // simplified code just relevant parts inside.
console.log('hitting')
var defer = Q.defer()
var newHp = 0;
defer.resolve(newHp)
return defer.promise
}

Resources