JavaScript How to create a new object in a function? - javascript

I'm writing up a discord bot that will store a request from a message via an object.
The idea is you call a function that will create a new object that can be referenced as a way to store information, rather than having 1 giant file or variable that has to be referenced every time a request to display said information.
Currently my code is setup with a rudimentary version of what I want.
var order1 = {
content: "",
author: "",
}
var order2 = {
content: "",
author: "",
}
var order3 = {
content: "",
author: "",
}
Even from my limited experience of programming, I know that is something is repeated, and often, there is usually a more effective way to write it.
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
// Interpret Command
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
var messagecont = message.content.replace('!haul.order', ""); // Remove command string
if(command === 'haul.order'){
message.channel.send("Hual order for:" + messagecont + " by: " + message.author.username);
orderNum++; // Update the current number order
if (orderNum > 3) {
message.channel.send("Sorry we only have 3 storage objects! Our programmer is to lazy to fix
this!");
}
if (orderNum == 1) {
order1.content = messagecont;
order1.author = message.author.username + ". ";
} else if (orderNum == 2) {
order2.content = messagecont;
order2.author = message.author.username + ". ";
} else if (orderNum == 3) {
order3.content = messagecont;
order3.author = message.author.username + ". ";
}
} else if (command =="show.orders") {
message.channel.send("Orderlist:" + order1.content + " by: " + order1.author + order2.content + " by: " + order2.author + order3.content + " by: " + order3.author);
}
});
For demonstration this code currently has only three storage objects, however adding more would "fix" the issue but in the wrong way. I ask again, is there a way to create a new object via a function? Something like order1, than order2 gets created. I know Create.object() exists, but from my knowledge, it only applies a template to a variable you had to declare.

It would be more dynamic by storing the orders in an array. To such array you may push() as many entries as you like.
//REM: Containing all the orders
const _listOfOrders = [];
document.querySelector('button').addEventListener('click', function(){
//REM: Getting input values
let tContent = document.getElementById('content')?.value || '';
let tAuthor = document.getElementById('author')?.value || '';
//REM: Adding the values to the list of orders
_listOfOrders.push({
Content: tContent,
Author: tAuthor
});
//REM: Outputting the current list
console.table(_listOfOrders)
});
<input type = 'text' id = 'content' value = 'Content'>
<input type = 'text' id = 'author' value = 'Author'>
<button>order</button>
Open the console to see the result.

Related

Google Scripts - getFrom() is not a function error

I had this working before, without an issue, however ever since I put a filter in to remove all threads with more than 1 email it is now coming up with the not a function error. I remove the filter and it still comes up with the error, unsure what has caused this to completely break on me
function extractEmails() {
var htmlBody = getEmailHtml();
var labelName = "auto-reply-incoming";
// get all email threads that match label
var receivedSearchQuery = "label:"+labelName+" -is:sent";
var threads = GmailApp.search(receivedSearchQuery, 0, 500);
threads.forEach ((t, i) => {
let messages = t.getMessages();
let name = messages.getFrom();
let messageCount = t.getMessageCount();
if (messageCount > 1) {
label.removeFromThread(t);
}
if (messageCount <= 1) {
message.reply("Hi " +name+" \n" + "insert text here");
}
});
};
accidentally removed part of the script, fixed with the following code:
messages.forEach ((m, j) => {
let name = m.getFrom();
m.reply("Hi " +name+" \n" + "insert text here");
});
Replace
let name = messages.getFrom();
by
let name = messages[0].getFrom();
The above because getFrom() is method from Class GmailMessage but messages is an Array.
Reference
https://developers.google.com/apps-script/reference/gmail/gmail-message#getfrom

Unhandled rejection SequelizeDatabaseError when passing dynamic query in where clause

I am trying to decompose a user's get request and put it in a variable named query. then pass the var query into the sequelize's findAll method using it's where clause, it seems like Sequelize thinks i am looking for a table CALLED query when in reality i am trying to pass the object. I'm sorry if i can not explain very well, but here is the code and the error:
var info = [];
//link example: localhost:8081/filter/?descripiton=san+francisco&houseType=house&numOfBedroom=3&numOfBathroom=2&houseSize=500&price=1200
exports.filterListings = function(req) {
//create an object literal which we will return, and has a nested object named filteredList inside.
//filteredList contains an array named listings where we will put listings that match our filter inside
let response = {
filteredList: {listings: []},
};
//now we need to see how the user wants us to filter the listings
const query = req.query;
//do some logic where we decompose query
if(query.descripiton != undefined) {
//info = info + 'descripiton: ' + query.descripiton+', ';
info.push('descripiton: ' + query.descripiton+', ');
console.log(info);
}
if(query.houseType != undefined) {
//info = info + 'houseType: ' + query.houseType+', ';
info.push('houseType: ' + query.houseType+', ');
//console.log(info);
}
if(query.numOfBedroom != undefined) {
//info = info + 'numOfBedroom: ' + query.numOfBedroom+', ';
info.push('numOfBedroom: ' + query.numOfBedroom+', ');
}
if(query.numOfBathroom != undefined) {
//info = info + 'numOfBathroom: ' + query.numOfBathroom+', ';
info.push('numOfBathroom: ' + query.numOfBathroom+', ');
}
if(query.houseSize != undefined) {
//info = info + 'houseSize: ' + query.houseSize+', ';
info.push('houseSize: ' + query.houseSize+', ');
}
if(query.price != undefined) {
//info = info + 'price: ' + query.price;
info.push('price: ' + query.price);
}
and then when i try to pass the info variable
listingModel.findAll({
//error because it wont recognize the variable search nor will it recognize info
where: {info}
}).then(listings => {
// so we loop through listings and insert what we have found into the response (which we are going to return)
for(var i = 0; i < listings.length; i++) {
response.filteredList.listings.push(listings[i]);
}; // loop where we insert data into response done
I want it to find all listings based on the dynamic query but i am getting the error:
Unhandled rejection SequelizeDatabaseError: Unknown column 'Listing.info' in 'where clause'
Thank you very much for the potential help!
Let's try to sort through your problems one by one. Sorry for the pun :p
Instead of using multiple if for creating your filtered list. Use for ... in. Then use that array of objects along with Sequelize.Op to create your query.
Example:
const Op = require('sequelize').Op;
const whereClause = [];
const query = req.query;
for(const key in query) {
if(query[key] !== '' && query[key] !== null) {
//object will be pushed to the array like "houseType:big"
whereClause.push({key:query[key]})
}
}
//you now have the where clause
//use it in your query with Op.and
listingModel.findAll({
where: {
[Op.and]: whereClause,
}
});
More info about querying with Sequelize - Operators

Firebase - Toggling value with transactions

I'm trying to let users favorite a project. I'm storing these projects at 2 places so I have to update them simultaneously. After looking at the firebase docs, using transactions seemed to be the best option.
.
Function to toggle the favorite status:
function toggleFavorite (projectReference, uid) {
projectReference.transaction(function(project) {
console.log('Before-Favorites :' + project.favoriteCount);
if (project.favorites && project.favorites[uid]) {
project.favoriteCount--;
project.favorites[uid] = null;
} else {
project.favoriteCount++;
if(!project.favorites) {
project.favorites= {};
}
project.favorites[uid] = true;
}
console.log(' After-Favorites :' + project.favoriteCount);
return project;
});
};
Function to add the eventListeners to the projects:
function AddToFavorite (uid, authorId) {
const favoriteList = document.querySelectorAll('.btnFavorite');
for(var i = 0; i<favoriteList.length; i++) {
favoriteList[i].addEventListener('click', function(event) {
const projectId = this.dataset.id;
console.log(projectId);
const globalProjectRef = firebase.database().ref('/projects/' + projectId);
const userProjectRef = firebase.database().ref('/user-projects/' + authorId + '/' + projectId);
toggleFavorite(globalProjectRef,uid);
toggleFavorite(userProjectRef,uid);
});
}
}
I want to store the uid of the current user under a 'favorites' node within the project location.
When i want to store the data I can see it appearing in the database but removing it after instantly. Followed by that i get an error in the console that my project object is null.
What's the best way of solving this issue ?

Discord bot Error Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Do anyone know the problem at this javascript bot?
The window (Start.bat) just open and close. Main error is at line 100 - 115!
I use it on my discord server and i need a bot to ban words. The bot is edited to ban words, but now it don't work. (Line 100 - 115)
I hope someone knows the problem.
It is made for a bot named The parrot, and i need a working code.
Code:
const Discord = require('discord.js');
const bot = new Discord.Client();
var fs = require("fs");
var oldAuthor;
// ADD YOUR BOT'S TOKEN HERE
const token = " *censored* ";
bot.on('ready', () => {
});
bot.on('message', message => {
// Makes sure the first word is ~createcommand
var checkMessage = message.content.split(" ");
if(checkMessage[0] == "~lagkommando")
{
// commandText gets grabbed by splitting the string with |
// commandName gets grabbed by splitting the string with spaces
// command Name must have '~' in it just so you can't use any word you
// want
var commandText = message.content.split("|",2);
var commandName = message.content.split(" ");
if(commandName[1].charAt(0) == "~")
{
checkExistingCommand(commandText,commandName);
message.channel.sendMessage("Command " + commandName[1] + " has been created");
} else {
message.channel.sendMessage("Command must contain '~'");
}
}
/*
* Checks the commands.txt file to see if anyone posted the command.
* commands.txt is split with semi-colons. For loop to check every single
* command. If there is a match, then it opens up the txt file associate
* with that command. If there are multiple pictures then the user should
* type $random{} and then type in all the pictures in the brackets
* separated by semi-colons. If there is no $random{} then it just sends the
* message.
*/
fs.readFile('./commands/commands.txt','utf8',function(err,f){
var com = f.toString().split(";");
for(i = 0; i < com.length; i++)
{
if(message.content == com[i])
{
if(com[i] == "~commands")
{
message.channel.sendMessage(com);
break;
}
if(com[i] == "~help")
{
message.channel.sendMessage("Kommandoer: ~help, ~commands, ~database, ~Hei, ~memes og ~problem");
break;
}
var command = "./commands/" + com[i] + ".txt";
fs.readFile(command,'utf8', function(err,f){
try{
var com2 = f.toString().split(";");
var num = Math.random() * ((com2.length - 1) - 0) + 0;
message.channel.sendMessage(com2[Math.floor(num)]);
}
catch(err) {
console.error("",err);
}
});
}
}
});
});
function checkExistingCommand(commandText,commandName)
{
var com = commandName[1];
var desc = commandText[1];
var CE = false;
fs.readFile('./commands/commands.txt','utf8',function(err,f){
var findCommands = f.toString().split(";");
for(i = 0; i < findCommands.length; i++)
{
if(com == findCommands[i])
{
CE = true;
}
}
if(CE == true)
{
createCommand(desc,true,com);
} else if (CE == false)
{
createCommand(desc,false,com);
}
});
}
bot.on('message', message => {
var sender = message.author;
var msg = message.content.toUpperCase();
var prefix = '>'
if (sender.id === ' *Censored* ') {
return;
}
if (msg.includes('noob')) {
message.delete();
message.author.send('The word noob is banned, next time YOU can be banned! ')
}
}
// Appends and/or creates the text files.
function createCommand(desc,b,com)
{
var fileName = "./commands/" + com + ".txt";
if(b == true)
{
fs.writeFile(fileName,desc,function(err){
if(err) {
return console.error(err);
}
});
} else if (b == false){
fs.appendFile('./commands/commands.txt',com+';',(err) =>
{
if(err) throw err;
});
fs.writeFile(fileName,desc,function(err){
if(err) {
return console.error(err);
}
});
}
return;
}
bot.login(token);
I see that you need a better text editor.
On Line 115. (At the eventhandler for message recieved for your Client). You were missing your closing line of );.
Also, just in case you did not knew, I realised that you made your msg string variable to upper-case before you compared it to a lower-cased string for commands. Do note that includes() method is case-sensitive.
I am using Visual Studio Code for my text editor. If somehow it does not show you syntax highlighting and stuff, check the bottom right of the editor, it should display Javascript there.
If it does not, change it to Javascript and it should show the syntax highlighting and stuff correctly.

variable is not getting defined even though the code works somwhere else

so i am building a game in three js and trying to make it multiplayer throught socket.io so i am loading all of my characters into an array called players on my server side
and then i pass it to each client when they connect like so
socket.on('addPlayer', function(username) {
players.push(username)
console.log(username + " joined")
console.log("online Users " + players)
socket.broadcast.emit('syncPlayers', players)
socket.emit('syncPlayers', players)
})
and on my client syncPlayers looks like this
socket.on('syncPlayers', function(players) {
players.forEach(function(value) {
if (value == username) {
console.log("not adding " + value + " thats you ")
loadPlayerdata(username)
} else {
console.log("player Online " + value);
newplayer = value;
loadPlayerdata(newplayer)
addPlayer(newplayer)
}
});
})
then it calls this wich sends the server data
function loadPlayerdata(playerName) {
console.log(playerName)
console.log("phase1")
socket.emit('loadPlayerdata', playerName)
}
then this is called and it retrieved the player name and the data of the players location this is were my problem lies
socket.on('loadPlayerdata', function(data, username) {
toMove = threeObjects[username + "Char"]
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
console.log(toMove)
toMove.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
}
i keep getting Uncaught TypeError: Cannot read property 'position' of undefined
even though i can use this
function addPlayer(playerName) {
var charObjectName = playerName + "Char"
var threeObject = models.tent1.mesh.clone();
scene.add(threeObject)
//threeObject.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
// set reference
threeObjects[charObjectName] = threeObject;
}
btw i have an object
var threeObjects = {};
can someone please explain why it wont work and how to fix it
You can read this answer to understand the difference between dot and brackets notation.
You are getting error because, tomove seems to be undefined and dot notation will throw error if any new user joins and if the object is empty.
Check if this helps. This will assign the object key as username and position as an value which will be array like this,
{"usernamechar": {"position": [x,y,z]}}
socket.on('loadPlayerdata', function(data, username) {
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
threeObjects[username + "Char"]["position"] = [world.spawnPointx, world.spawnPointy, world.spawnPointz]
}
}

Categories

Resources