Google Scripts - getFrom() is not a function error - javascript

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

Related

Why the Code After Array.foreach doesn't execute?

I am trying to get value of a global variable (screenDisplay) after completing the for each portion.
But it seems whenever the 2nd Part is put before the 1st Part, the value that i am supposed to get from screenDisplay comes undefined and the console throws an error.
*error
TypeError: Cannot read properties of undefined (reading 'toFixed')
Why does the screenDisplay's value gets affected when part 2 is kept after part 1?
To find the error directly input values to the screen without using calculator key. ex. (2+3)
Live Link Here
const screenDisplay = document.getElementById("screen-input-selector");
const result = () => {
focusInitiate();
try {
**//1st Part**
// * auto multiplication feature
displaylocalStorageDATA();
const screenItems = [...screenDisplay.value];
let screenPosition = screenDisplay.selectionStart;
screenItems.forEach((item, index) => {
let indexno = index + 1;
if (
screenItems.length != indexno &&
![")", "+", "-", "*", "/"].includes(screenItems[index + 1]) &&
item == ")"
) {
let remainingDataFirstPortion = screenItems.slice(0, index + 1); //selects and stores the rest of the portion of the text after cursor
let remainingDataLastPortion = screenItems.slice(
index + 1,
screenItems.length
);
const clearedArray = remainingDataFirstPortion.concat("*");
const clearedArray1 = clearedArray.concat(remainingDataLastPortion);
screenDisplay.value = clearedArray1.join("");
displaylocalStorageSTORE();
screenDisplay.setSelectionRange(screenPosition, screenPosition);
}
});
//2nd Part
const inputData = localStorage.getItem("display");
if (inputData != null) {
//when inputdata and screendisplay value are same
if (inputData == screenDisplay.value) {
//when local storage has some value
displaylocalStorageREMOVE();
// screenDisplay.value = eval(localStorage.getItem("display"));
screenDisplay.value = Function("return " + inputData)().toFixed(4); //using function constructor instead of EVAL function cause EVAL() executes the code it's passed with the privileges of the caller
displaylocalStorageSTORE();
} else {
//when inputdata and screendisplay value are not same
displaylocalStorageREMOVE();
screenDisplay.value = Function(
"return " + screenDisplay.value
)().toFixed(4);
displaylocalStorageSTORE();
}
} else {
//when local storage is empty
screenDisplay.value = Function("return " + screenDisplay.value)().toFixed(
4
);
displaylocalStorageSTORE();
}
} catch (error) {
console.log(error);
};
Problem Resolved.
displaylocalStorageDATA() (which reassigns locally saved data to the global variable) of Part 1 was causing the problem. It was redefining the screenDisplay.value.
Removing that line has solved the problem.
Thanks, Everyone.

querySelector returns 'Failed to execute div is not a valid selector' when it exists in the DOM

I'm running into an issue where the 'div ID' isn't valid when I run it from the code.
However, when I document.querySelector('#div-gpt-ad\\/1594654184865-0>div') it returns the correct div ID.
Screenshot of error: https://gyazo.com/a7f1898f246bd84f28e85c2052ac60eb
The div id exists on page before executing the code, the console.log in the renderDiv function returns
Here is the code I'm trying to execute:
var slots = window.top.googletag.pubads().getSlots();
init(slots);
function init(slots) {
for (let i = 0; i < slots.length; i++) {
renderDiv(slots[i]);
}
}
function getSelectors(slot) {
var escapeCheck = slot.getSlotElementId();
if(escapeCheck.includes('/')){
let placeHold = escapeCheck.replace(/\//g, '\\\\/');
return "#" + placeHold + ">div" ;
} else{
return "#" + escapeCheck + ">div";
}
}
function renderDiv(slot) {
let selector = getSelectors(slot);
console.log("Selector:" + selector)
document.querySelector(selector)
}
Fixed!
Changed let placeHold = escapeCheck.replace(/\//g, '\\\\/'); to
let placeHold =escapeCheck.replace(/\//g, "\\/").replace(/\./g, "\\.");
Something I quite don't understand yet is why the first one did not work as the string was correct that was passing through

JavaScript How to create a new object in a function?

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.

Raffle thing not working

Coding problem for raffle won't work!
var i = 0;
var count;
var names = [
"Stefon",
"Garret",
"Brandon"
];
function GetRandomInt(){
return Math.floor(Math.random()*i+1);
}
function CallWinner(){
var ID = GetRandomInt();
document.write("<hr>"+names[ID]+" has won with the ID of "+id+"!");
}
do {
i++;
for(count=0;i<=names.length;){
count++;
document.write(names[count]+" has been assigned to the raffle ID, "+count+"<br>");
}
} while (i<=names.length);
For some reason this isn't working, it acts like an infinite loop or maybe it crashes the tab, it works but then it crashes the tab. Please help.
document.write is document.wrong. Please use something more modern and less prone to doing confusing things. This function tries to write to the current document. If the document has already been processed, the document will be replaced with a blank one with your argument. You don't want that; use the proper DOM methods instead.
Your GetRandomInt function is broken; it should return a random accessible index in the array, not a static number.
Try something like this instead:
const names = [
"Stefon",
"Garret",
"Brandon"
];
function GetRandomIndex() {
return Math.floor(Math.random() * names.length);
}
function CallWinner() {
const index = GetRandomIndex();
const hr = document.body.appendChild(document.createElement('hr'));
hr.textContent = names[index] + " has won with the ID of " + index + "!";
}
names.forEach((name, count) => {
const div = document.body.appendChild(document.createElement('hr'));
div.textContent = name + " has been assigned to the raffle ID, " + count;
});
CallWinner();

Protractor - Error: Index out of bound exception while using the same function for the second time

I have the following function which selects a category from a list of available categories. This function works fine in my first test. But the same function with a different valid category name in my second test fails with the following error.
Error: Index out of bound. Trying to access element at index: 0, but there are only 0 elements that match locator By.cssSelector(".grid-view-builder__category")
this.categoryElements = element.all(by.css('.grid-view-builder__category'));
this.selectCategory = function (categoryName) {
var filteredCategories = this.categoryElements.filter(function (category) {
return category.getText().then(function (text) {
log.info(text);
return text === categoryName;
})
})
filteredCategories.first().click().then(function () {
log.info("Select Category: " + categoryName);
}).then(null, function (err) {
log.error("Category: " + categoryName + " Not Found !!" + err);
});
}
Spec File
var columnSelect = require('pages/grid/columns/columnselector-page')()
it('Add Publisher ID Column to the Grid & Verify', function () {
var columnCountBefore = columnSelect.getColumnCount();
columnSelect.openColumnSelector();
columnSelect.selectCategory('Advanced');
columnSelect.selectColumn('Publisher ID');
columnSelect.apply();
var columnCountAfter = columnSelect.getColumnCount();
expect(columnCountAfter).toBeGreaterThan(columnCountBefore);
});
The problem might be in the way you are defining and using Page Objects. Here is a quick solution to try - if this would help, we'll discuss on why that is happening.
Make the categoryElements a function instead of being a property:
this.getCategoryElements = function () {
return element.all(by.css('.grid-view-builder__category'));
};
this.selectCategory = function (categoryName) {
var filteredCategories = this.getCategoryElements().filter(function (category) {
return category.getText().then(function (text) {
log.info(text);
return text === categoryName;
})
})
filteredCategories.first().click().then(function () {
log.info("Select Category: " + categoryName);
}).then(null, function (err) {
log.error("Category: " + categoryName + " Not Found !!" + err);
});
}
Or, this could be a "timing issue" - let's add an Explicit Wait via browser.wait() to wait for at least a single category to be present:
var EC = protractor.ExpectedConditions;
var category = element(by.css('.grid-view-builder__category'));
browser.wait(EC.presenceOf(category), 5000);
It looks like this has nothing to do with the code posted here, only that the css selector you're using is not finding any elements

Categories

Resources