App Script Google Error Token Delete Gmail - email

I'm trying to create a script to delete emails and I'm getting a failure in the token, I don't know if I'm using a wrong token or I have another bug.
I have created a project with a key and this is the key I have used in the script as token.
function deleteEMail() {
var mymail = Session.getActiveUser().getEmail();
var mylabel = "mytest";
var permanentlyRemoveMyLabel = true;
var pageToken ="*****************************************";
do {
var threadList = Gmail.Users.Threads.list('me', {
q: 'subject:' + mylabel,
pageToken: pageToken
});
if (threadList.threads && threadList.threads.length > 0) {
threadList.threads.forEach(function(thread) {
Logger.log('id: %s snippet: %s', thread.id, thread.snippet);
if (permanentlyRemoveMyLabel) {
Gmail.Users.Threads.remove(mymail, thread.id);
Logger.log('id: %s snippet: %s REMOVED', thread.id, thread.snippet);
}
});
}
pageToken = threadList.nextPageToken;
} while (pageToken);
}

Related

Email multiple cells to recipient instead of one email per cell using Apps Script

Currently I'm working on a script that checks values of one column and based on that send email containing information from another column. Everything works perfectly except one thing - it send one email per value and I'd like to send all the values in one email. Can someone please help with the issue ?
const helpsheet = SpreadsheetApp.openById("ID").getSheetByName('Sheet');
const date = helpsheet.getRange(1,10).getValue();
const ss = SpreadsheetApp.openById("ID2");
const sh = ss.getSheetByName('Sheet2');
const data = sh.getRange('A2:c'+sh.getLastRow()).getValues();
var recipients = 'EMAIL#EMAIL';
var subject = 'SUBJECT';
data.forEach(r=>{
let overdueValue = r[2];
if (overdueValue > date)
{
let path = r[0];
MailApp.sendEmail({
to: recipients,
subject: subject,
htmlBody: 'Hi guys ' + path +'!<br><br>Best regards,'
});
}
});
} ```
Of course I can't test this because 1st I don't want a bunch of emails to myself and 2nd I don't have a data set that matches your data, but I'm pretty sure this will do what you want. What I do is build an array of rows that pass the sniff test using the Array push method below. Then when I have all the rows that pass I send one email.
I have edited this post to include functions to create an html table.
function test() {
try {
const helpsheet = SpreadsheetApp.openById("ID").getSheetByName('Sheet');
const date = helpsheet.getRange(1,10).getValue();
const ss = SpreadsheetApp.openById("ID2");
const sh = ss.getSheetByName('Sheet2');
const data = sh.getRange('A2:c'+sh.getLastRow()).getValues();
var pre = "Hello";
var post = "Best regards";
var recipients = 'EMAIL#EMAIL';
var subject = 'SUBJECT';
var passed = [];
data.forEach( r => {
let overdueValue = r[2];
if (overdueValue > date) {
passed.push(r);
}
});
if( passed.length > 0 ) { // maybe nothing passed the test
var html = createHTMLfile(true);
html = html.concat("<p>"+pre+"</p>");
html = html.concat(createTable(passed));
html = html.concat(createHTMLfile());
html = html.concat("<p>"+post+"</p>");
MailApp.sendEmail( {
to: email,
subject: subject,
htmlBody: html });
};
}
}
catch(err) {
console.log(err);
}
}
I have added the additional functions to create the table. You are welcome to play with the <style>s.
function createHTMLfile(pre) {
if( pre ) {
return "<html><head><style>table, td { border: thin solid black; border-collapse:collapse; text-align:center }</style></head><body>";
}
else {
return "</body></html>";
}
}
function createTable(data) {
try {
var width = 600/data[0].length;
var table = "<table>";
function addCell(value) {
table = table.concat("<td style=width:"+width+"px>");
table = table.concat(value.toString());
table = table.concat("</td>");
}
function addRow(row) {
table = table.concat("<tr>");
row.forEach( addCell );
table = table.concat("</tr>");
}
data.forEach( addRow )
table = table.concat("</table>");
return table;
}
catch(err) {
console.log(err);
}
}

PayPal IPN returns INVALID on Sandbox with Google Script

This standalone Google Script web-service always returns INVALID from PayPal (resp = INVALID). The PayPal IPN simulator shows a message that the handshake was successful.
What am I missing?
function doPost(e) {
var isProduction = false;
//if(typeof e == 'undefined')
//return ContentService.createTextOutput(JSON.stringify(e.parameter));
var strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr"
var strLive = "https://www.paypal.com/cgi-bin/webscr"
var paypalURL = strSandbox
if (isProduction) paypalURL = strLive;
var payload = "cmd=_notify-validate&" + e.postData.contents;
var options =
{
"method" : "post",
"payload" : payload
};
var resp = UrlFetchApp.fetch(paypalURL, options);
}
After getting everything to work, I'm offering here my working implementation skeleton:
function doPost(e) {
var isProduction = false;
//if(typeof e == 'undefined')
//return ContentService.createTextOutput(JSON.stringify(e.parameter));
var strSimulator = "https://www.sandbox.paypal.com/cgi-bin/webscr"
var strLive = "https://www.paypal.com/cgi-bin/webscr"
var paypalURL = strSimulator
if (isProduction) paypalURL = strLive;
var payload = "cmd=_notify-validate&" + e.postData.contents;
payload = payload.replace("+", "%2B");
var options =
{
"method" : "post",
"payload" : payload,
};
var resp = UrlFetchApp.fetch(paypalURL, options); //Handshake with PayPal - send acknowledgement and get VERIFIED or INVALID response
if (resp == 'VERIFIED') {
if (e.parameter.payment_status == 'Completed') {
if (e.parameter.receiver_email == 'receiver#email.com') {
//Convert to reference currency (USD) if paid in any other currency
var exchangeRate = 1;
if ((e.parameter.exchange_rate)) {
exchangeRate = parseFloat(e.parameter.exchange_rate);
}
var paidUSD = isPaymentValid(parseFloat(e.parameter.mc_gross), e.parameter.mc_currency, exchangeRate); //Convert paid amound to reference currency (USD)
if (paidUSD == 0.0) {
//My function returns 0.0 if product cost not found in my DB. I raise some notification here to check it out
return false;
}
if (paidUSD > 0.0) {
//All validated - can process the payment
var processSuccess = processDownloadRequest(e);
if (!(processSuccess)) {
//Process of payment failed - raise notification to check it out
}
} else {
//Payment does not equal expected purchase value
}
} else {
//Request did not originate from my PayPal account
}
} else {
//Payment status not Completed
}
} else
{
//PayPal response INVALID
}
}

how to collect data from user with the facebook messenger bot api in node js

I am building a messenger bot in node. I want it to collect user input data and have a conversation or ask questions, but the code I have doesn't work. the part that does not work is it only continues to the next else if block if i type the same code. and second the array is not capturing the text after the first if statement. Is there a better way to do it? Could someone provide code?
My code is below. what i want is like in this iimage:
var currentbot = 0;
var awnswers = [];
app.post('/webhook', function(req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
var text = event.message.text;
if (text == "hi") {
start(event.message.text, event.sender.id);
}
}
}
res.sendStatus(200);
});
var awnswers = [];
function start(text, id) {
if (count == 0) {
sendTextMessage('hello lets order!', id);
arr.push(text);
console.log(awnswers);
count = 1;
} else if (count == 1) {
sendTextMessage('what size do you want?', id);
arr.push(text);
console.log(awnswers);
count = 2;
} else if (count == 2) {
sendTextMessage('its on its way!', id);
arr.push(text);
console.log(awnswers);
count = 0;
}
}
function sendTextMessage(messageText, recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: process.env.access_token
},
method: 'POST',
json: messageData
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
The main issues I think I see are:
Start() is only called when text == hi
Count is not defined
You're pushing to the array 'arr' not, awnswers
You can fix these by:
Calling start() on every message
Defining count like var count = 0; at the top of your file, next to var currentbot
awnswers.push(text);

Writing to sockets

I have trouble understanding the reason for the error I get when the user tries to write anything to the server:
TypeError: Object #<identifyClient> has no method 'write'
at writeToAll (/root/node/mud/server.js:13:15)
Why does identifyClient() complaints about the write(), while it happens in the writeToAll() (line 15 has comment next to it)? identifyClient() really only sets the name for the client, and should not be concerned what happens in the writeToAll().
var net = require("net");
var clients = [];
function identifyClient(client) {
this.name = null;
this.client = client;
}
function writeToAll(data, client) {
for (var i = 0; i < clients.length; i++) {
if (clients[i] != client) {
clients[i].write(data); // This is line 15
}
}
}
var server = net.createServer(function(client) {
var clientID = new identifyClient(client);
clients.push(clientID);
client.on("data", function(data) {
writeToAll(data, client);
});
});
server.listen(4444);
Replace clients[i] with clients[i].client
also you have to remove the client from the clients array once it disconnects.

import private google fusion table to google docs spreadsheet

I want to build a chart to google fusion table. I know there is an option to do it with fusion table but I need to do that using google spreadsheet.
How do I import a private fusion table to a spreadsheet?
function getdata(authToken) {
query = encodeURIComponent("SELECT * FROM tableid");
var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
var response = UrlFetchApp.fetch(URL, {
method: "get",
headers: {
"Authorization": "GoogleLogin auth=" + authToken,
}
});
return response.getContentText();
}
The code above gives me the table headers only.
Don't set each cell individually as in the example below unless you need to process each bit of data. Using this is about 10x faster:
var rows = o.length;
var columns = o[0].length;
cell.offset(<startrow>, <startcolumn>, rows, columns).setValues(o);
After a deep research, finally i figured it out after a deep search and reading here.
This is how it looks for the code google docs spreadsheet app script:
function onOpen()
{
var tableID = '00000' // Add the table ID of the fusion table here
var email = UserProperties.getProperty('email');
var password = UserProperties.getProperty('password');
if (email === null || password === null) {
email = Browser.inputBox('Enter email');
password = Browser.inputBox('Enter password');
UserProperties.setProperty('email',email);
UserProperties.setProperty('password', password);
} else {
email = UserProperties.getProperty('email');
password = UserProperties.getProperty('password');
}
var authToken = getGAauthenticationToken(email,password);
query = encodeURIComponent("SELECT * FROM tableID");
var URL = "http://www.google.com/fusiontables/api/query?sql=" + query;
var response = UrlFetchApp.fetch(URL, {
method: "get",
headers: {
"Authorization": "GoogleLogin auth=" + authToken,
}
});
var tableData = response.getContentText();
var o = Utilities.parseCsv(response.getContentText());
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('a1');
var index = 0;
for (var i in o) {
var row = o[i];
var col = 0;
for (var j in row) {
cell.offset(index, col).setValue(row[j]);
col++;
}
index++;
}
}
function getGAauthenticationToken(email, password) {
password = encodeURIComponent(password);
var response = UrlFetchApp.fetch("https://www.google.com/accounts/ClientLogin", {
method: "post",
payload: "accountType=GOOGLE&Email=" + email + "&Passwd=" + password + "&service=fusiontables&Source=testing"
});
var responseStr = response.getContentText();
responseStr = responseStr.slice(responseStr.search("Auth=") + 5, responseStr.length);
responseStr = responseStr.replace(/\n/g, "");
return responseStr;
}
After that you can do whatever you want in the spreadsheet.
BTW, I still think there is a simple way to import a private table into a spreadsheet automaticly.