kurokirasama
kurokirasama

Reputation: 777

How to create a google app script that delete temporary contacts after a while?

i'm looking to create an script that does the following:

Surely you have save a phone number you are only going to use once, so this would help to delete that contact of we forgot about it.

Upvotes: 0

Views: 88

Answers (1)

kurokirasama
kurokirasama

Reputation: 777

Ok, i'm answering my own question for if someone is interested.

First, you have to create a contact group in wich you are going to categorize this contacts (in the code is "Tiny", but you can named as you whish). Second, when creating a contact, you should add a note like; "2 month" if you want the contact to get erased after 2 months, or "1 year", etc. The code is implemented only for months and year, but is easily modifiable if you want another time period, like days or weeks.

Here's the code:

function deleteTinyContacts() {
var group = ContactsApp.getContactGroup("Tiny");
var contacts = ContactsApp.getContactsByGroup(group)
var hoy = new Date();
Logger.log("today is " + hoy);
Logger.log("total contacts to delete: " + contacts.length);

for (var i = 0; i < contacts.length; i++) {
 var date = contacts[i].getLastUpdated();
 Logger.log(contacts[i].getFullName() + " was updated last in " + date);

var datediff = DateDiff.inMonths(date,hoy);
Logger.log("contact updated " + datediff + " months ago");

var note = contacts[i].getNotes();
var res = note.split(" ");
var Tmonths = calcMonths(res[1]);
var todelete = res[0]*Tmonths;
Logger.log("contact must be deleted after " + todelete + " months");

if (datediff>=todelete){
 group.removeContact(contacts[i]);      
}
}
}

var DateDiff = {    
inDays: function(d1, d2) {
    var t2 = d2.getTime();
    var t1 = d1.getTime();

    return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
    var t2 = d2.getTime();
    var t1 = d1.getTime();

    return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
    var d1Y = d1.getFullYear();
    var d2Y = d2.getFullYear();
    var d1M = d1.getMonth();
    var d2M = d2.getMonth();

    return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
    return d2.getFullYear()-d1.getFullYear();
}
}
function calcMonths(str){
if(str=="año"){return 12;}
else if(str=="mes"){return 1;}  
}

Upvotes: 2

Related Questions