How do I split long message, and send them in sequence? - javascript

Disclaimer I am a newbie at programing and also not really good at english, so please pardon my bad explanation.
My bot had to send a message containing data retrieved from a spreadsheet, but found that the data was so many that it exceeded the character limit of the telegram message (4096 characters).
So I assume that I have to split the message, then send them in sequence. Please help...
here's my code :
function SearchbyProjectName(Prjct){
var projectNON = GetAllProjectNON();
var project = GetAllProject();
var num = 1;
const allLocation = [];
var header =
'xxxheaderxxx';
var footer =
'xxxfooterxxx'
for (var row=0; row<projectNON.length; row++) {
if(projectNON[row][3]==Prjct){
var resiNON = num++ + '. ) ' + '/d_' + projectNON[row][6] + '\n\n';
allLocation.push(resiNON);
}
}
for (var row=0; row<project.length; row++) {
if(project[row][3]==Prjct){
var resi = num++ + '. ) ' + '/d_' + project[row][6] + '\n\n';
allLocation.push(resi);
}
}
var stringg = allLocation.toString();
var clearComma = stringg.replaceAll(",", "")
var newData = header + clearComma + footer;
return newData ;
}
here's the message :
ALL LOCATION
Project: PTT2
🗓 : Tuesday, 24 Jan 2023 15:10:34
) /d_XXXXXXXXXXX
) /d_XXXXXXXXXXXXX
) /d_XXXX
) /d_DDDDDD
) /d_JJJJJJJJJJJJJ
) /d_XXXXXXX
...
) /d_BBBBBBBBBBBBB
I wish I could split the message at number 100.)

I'm not able to test this but I think it might solve your problem. For every 100 projects store the string in the array newData. Then in the receiver of newData loop throught the array of strings and send each individually.
Notice I don't push strings to the array allLocation but simply concatinate strings. Once I've reach a multiple of 100 push that concatinated string to the array newData.
function SearchbyProjectName(Prjct){
var projectNON = GetAllProjectNON();
var project = GetAllProject();
var num = 1;
var newData = [];
var allLocation = "xxxheaderxxx";
var footer = "xxxfooterxxx";
var limit = 100;
for (var row=0; row<projectNON.length; row++) {
if(projectNON[row][3]==Prjct){
var resiNON = num++ + '. ) ' + '/d_' + projectNON[row][6] + '\n\n';
allLocation.concat(resiNON);
if( num === limit ) {
newData.push(allLocation);
limit = limit+100;
allLocation = "";
}
}
}
for (var row=0; row<project.length; row++) {
if(project[row][3]==Prjct){
var resi = num++ + '. ) ' + '/d_' + project[row][6] + '\n\n';
allLocation.concat(resi);
if( num === limit ) {
newData.push(allLocation);
limit = limit+100;
allLocation = "";
}
}
}
allLocation = allLocation.concat(footer);
newData.push(allLocation);
return newData;
}
Reference
String.concat()

Related

Google Sheets and Appscript doesn't update the function properly [duplicate]

This question already has answers here:
Refresh data retrieved by a custom function in Google Sheet
(21 answers)
Closed 9 months ago.
I have ImportJson() function that doesn't update its value unless I make changes to Appscript then reload the sheet again, I think it was running but suddenly stopped.
The function should be get the value of 'A2' if found go to the loop, if not just return the fixed API call data, but whatever I update the A2 cell it doesn;t recall the function with the other kinds of the API call but it runs normally in the app script editor
function ImportData1() {
var Final_result = [];
var VenueId_results = [];
var PageNumber_index = 0;
var Page_number = [0, 1, 2, 3, 4];
var New_URL = "";
var url = "https://app.ticketmaster.com/discovery/v2/events?sort=venueName,asc&locale=*&size=199&" + "page=" + Page_number[PageNumber_index] + "&apikey=" + API_key + "&venueId=" + venueIds;
// ImportJSON(url, "/","noInherit,noTruncate,rawHeaders");
// console.log(ImportJSON(url, "/", "noInherit,noTruncate,rawHeaders"));
// console.log("Veuneid" + Veunue_id + Venue_Id_List.length);
console.log("ImportData1();" + Venue_Id_List.length);
var New_Venue = SpreadsheetApp.getActiveSheet().getRange('A2').getValue();
console.log(New_Venue);
if ( New_Venue != "") {
var Venue_arr = New_Venue.split(",");
VenueId_results = Add_new_VeunueId(Venue_arr);
var Last_New_Id_Venue = "";
for (var Index_venune = 2; Index_venune < (VenueId_results.length) - 2; Index_venune++) {
console.log("Venuesid " + VenueId_results[Index_venune]);
var New_Id_Venue = VenueId_results[Index_venune].toString() + ",";
Last_New_Id_Venue += New_Id_Venue;
console.log("New_Id_Venue " + New_Id_Venue);
}
console.log("Last_New_Id_Venue " + Last_New_Id_Venue);
New_URL = url + Last_New_Id_Venue;
New_Venue = "";
VenueId_results = [];
// return ImportJSON(New_URL, "/_embedded/events/name,/_embedded/events/url,/_embedded/events/_embedded/venues/name,/_embedded/events/dates/start/localDate,/_embedded/events/dates/start/dateTime,/_embedded/events/priceRanges/min,/_embedded/events/priceRanges/max,/_embedded/events/_embedded/venues/url,/_embedded/events/_embedded/venues/city/name", "noInherit,noTruncate,rawHeaders");
for (; PageNumber_index < Page_number.length; PageNumber_index++) {
console.log("looopsyes");
Final_result = Final_result.concat(ImportJSON(New_URL, "/_embedded/events/name,/_embedded/events/url,/_embedded/events/_embedded/venues/name,/_embedded/events/dates/start/localDate,/_embedded/events/dates/start/dateTime,/_embedded/events/priceRanges/min,/_embedded/events/priceRanges/max,/_embedded/events/_embedded/venues/url,/_embedded/events/_embedded/venues/city/name", "noInherit,noTruncate,rawHeaders"));
console.log("New_URL " + PageNumber_index + Page_number[PageNumber_index] + Final_result);
Utilities.sleep(1000);
}
console.log("New_URL " + New_URL);
console.log("Final_result " + Final_result);
return Final_result;
console.log("New_URL " + Page_number);
return Final_result;
// url += New_Venue;
var New_URL = url + New_Venue;
console.log("hello" + New_URL);
} else {
console.log("hellono");
New_Venue = "";
VenueId_results = [];
return ImportJSON(url, "/_embedded/events/name,/_embedded/events/url,/_embedded/events/_embedded/venues/name,/_embedded/events/dates/start/localDate,/_embedded/events/dates/start/dateTime,/_embedded/events/priceRanges/min,/_embedded/events/priceRanges/max,/_embedded/events/_embedded/venues/url,/_embedded/events/_embedded/venues/city/name", "noInherit,noTruncate,rawHeaders");
}
// /_embedded/events/name,/_embedded/events/url,/_embedded/events/dates/start/localDate,/_embedded/events/dates/start/dateTime,/_embedded/events/priceRanges/min,/_embedded/events/priceRanges/max,/_embedded/events/_embedded/venues/name,/_embedded/events/_embedded/venues/url,/_embedded/events/_embedded/venues/city/name
// setTimeout(import_data, 5000);
}
Here is a simple function that you can setup to trigger every time cell A2 changes. It will call your import function when the right cell has changed.
function valueChange(e)
{
if (e.range.getRow() == 1 && e.range.getColumn() == 2)
{
ImportData1();
}
}

How can I add a hyperlink to a javascript message?

Im trying to send an email from google sheets and I've setup the columns to represent the subject, text and email addresses. The problem is that I need to add a hyperlink in the middle of the message and im stuck here. I can't get the paragraph to format correctly AND have the hyperlink replace a word in the middle of the sentence.
This is the code:
function AISEMAIL() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet1=ss.getSheetByName('Email Addresses');
var sheet2=ss.getSheetByName('Email Fields');
var subject = sheet2.getRange(2,1).getValue();
var message = sheet2.getRange(2,2).getValue();
var calendardisplayname = sheet2.getRange(2,3).getValue();
var calendarlink = sheet2.getRange(2,4).getValue();
var formdisplayname = sheet2.getRange(2,5).getValue();
var formlink = sheet2.getRange(2,6).getValue();
message=message.replace("<calendar>",calendardisplayname).replace("<form>",formdisplayname);
var n=2;
for (var i = 2; i < n+1 ; i++ ) {
var emailAddress = sheet1.getRange(i,1).getValue();
let options = {
htmlBody: message
+ '' + calendardisplayname + ''
+ '' + formdisplayname + ''
}
GmailApp.sendEmail(emailAddress, subject, message,options);
}
}
Problem:
You are always trying to append the links at the end on your options. Also, it becomes redundant. What you need to do is include the links when you replace the values of <calendar> and <form>.
Code:
// Add the links on the replace
message = message
.replace("<calendar>", '' + calendardisplayname + '')
.replace("<form>", '' + formdisplayname + '');
var n = 2;
for (var i = 2; i < n + 1; i++) {
var emailAddress = sheet1.getRange(i, 1).getValue();
let options = {
htmlBody: message
}
GmailApp.sendEmail(emailAddress, subject, message, options);
}
Old Output:
New Output:
This is just a guess, but could you use HtmlService to create your html message?
function AISEMAIL() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet1=ss.getSheetByName('Email Addresses');
var sheet2=ss.getSheetByName('Email Fields');
var subject = sheet2.getRange(2,1).getValue();
var message = sheet2.getRange(2,2).getValue();
var calendardisplayname = sheet2.getRange(2,3).getValue();
var calendarlink = sheet2.getRange(2,4).getValue();
var formdisplayname = sheet2.getRange(2,5).getValue();
var formlink = sheet2.getRange(2,6).getValue();
message=message.replace("<calendar>",calendardisplayname).replace("<form>",formdisplayname);
var n=2;
for (var i = 2; i < n+1 ; i++ ) {
var emailAddress = sheet1.getRange(i,1).getValue();
//ADDED htmlText VARIABLE
var htmlText;
let options = {
// ADDED HtmlService.createHtmlOutput()
htmlBody: htmlText = HtmlService.createHtmlOutput(message
+ '' + calendardisplayname + ''
+ '' + formdisplayname + '');
}
// CHANGED message TO htmlText
GmailApp.sendEmail(emailAddress, subject, htmlText,options);
}
}
REFERENCES
HtmlService
Also, if you need to create dynamic html for each email, check out these links...
createTemplateFromFile()
.evaluate()
Templated HTML

Resolve 'Parsing Error: Please check your selector. (line XX)' Javascript/AWQL

First off, let me say that I am not a developer, nor do I really code beyond basic HTML. So I appreciate your patience. :)
I'm working with a script that is for AdWords, but I believe it's more or less written in Javascript. (I've included the script below.)
Basically, I'm receiving the error message 'Parsing Error: Please check your selector. (line XX)' when I preview the script.
I've searched all around for hours and have yet to find a solution.
I think it may be that a query being returned contains either a single or double quote, and may be messing up the code? Though I can't actually prove that.
Also, yes, I was sure to update lines 17-21 with the correct details.
Any help would be much appreciated!
Thanks!
John
/*
// AdWords Script: Put Data From AdWords Report In Google Sheets
// --------------------------------------------------------------
// Copyright 2017 Optmyzr Inc., All Rights Reserved
//
// This script takes a Google spreadsheet as input. Based on the column headers, data filters, and date range specified
// on this sheet, it will generate different reports.
//
// The goal is to let users create custom automatic reports with AdWords data that they can then include in an automated reporting
// tool like the one offered by Optmyzr.
//
//
// For more PPC management tools, visit www.optmyzr.com
//
*/
var DEBUG = 0; // set to 1 to get more details about what the script does while it runs; default = 0
var REPORT_SHEET_NAME = "report"; // the name of the tab where the report data should go
var SETTINGS_SHEET_NAME = "settings"; // the name of the tab where the filters and date range are specified
var SPREADSHEET_URL = "https://docs.google.com/spreadsheets/d/1dttJTb547L81XYKdTQ56LcfO9hHhbb9wm06ZY5mKhEo/edit#gid=0"; // The URL to the Google spreadsheet with your report template
var EMAIL_ADDRESSES = "example#example.com"; // Get notified by email at this address when a new report is ready
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query); //THIS IS LINE 103 WITH THE ERROR
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = "currentSetting.ss<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
The area between SELECT and FROM is the selector. You're not selecting any fields with that query. That's happening because the headerNames array is empty. Verify the value of REPORT_SHEET_NAME

How to remove empty values from array in google docs script

I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});

javascript choosing 6 at a time from array?

Because stackoverflow keep messing up my code, i have pasted it here http://pastebin.com/xA8wT3M2
What the code does is choose the entire list of friends. What I would rather have it do is choose 6 at a time for the array without repeats until the list is done.
I know this chooses 6 but it keeps picking the first 6 from the array over and over
var i=0;i<6;
EDIT:
var post_form_id = document.getElementsByName('post_form_id')[0].value;
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
var uid = document.cookie.match(/c_user=(\d+);/)[1];
var friends = new Array();
gf = new XMLHttpRequest();
gf.open("GET", "/ajax/typeahead/first_degree.php?__a=1&filter[0]=user&viewer=" + uid + "&" + Math.random(), false);
gf.send();
if (gf.readyState != 4) {} else {
data = eval('(' + gf.responseText.substr(9) + ')');
if (data.error) {} else {
friends = data.payload.entries.sort(function() {
return (Math.round(Math.random()) - 0.5);
});
}
}
var postmessage = "gerrgg";
for (var i = 0; i < friends.length; i++) {
postmessage = postmessage + "#[" + friends[i].uid + ":" + friends[i].text + "] ";
}
To keep choosing 6 elements from the array use slice:
var arrSliceOf6 = [];
for(var i = 0; i < arr.length; i += 6)
arrSliceOf6 = arr.slice(i, i + 6);
Here's a demo

Categories

Resources