add a created contact to a group by people api using google apps script

1.3k views Asked by At

I need to create a new group "Carpenters" (if the group doesn't exist) and add the created contact to "Carpenters" group

I have tried with

function doGet(e) {
  var id = People.People.createContact(
  {
        "names": [
          {
            "displayNameLastFirst": "Smith Jefferson Jones",
            "familyName": "Jones",
          }
        ],
       /* "phoneNumbers": [
            {
                'value': "+12345679962"
            }
        ],
        "emailAddresses": [
            {
                'value': ' '
            }
        ]*/
    }
  ).metadata.sources[0].id;
  
 return ContentService.createTextOutput("Success");
}
1

There are 1 answers

1
Iamblichus On BEST ANSWER

You could do the following:

  1. Retrieve the resourceName of the created contact (to be used on step 4).
  2. Check if the group exists by listing all contactGroups and looking for a group whose name is Carpenters (using find()).
  3. Create a contactGroup called Carpenters if it doesn't exist, using contactGroups.create.
  4. Use contactGroups.members.modify to add the created contact to the group.

Code sample:

function doGet(e) {
  // 1. CREATE CONTACT:
  var contactResource = {
    "names": [{
      "displayNameLastFirst": "Smith Jefferson Jones",
      "familyName": "Jones",
    }],
    /* "phoneNumbers": [{
      'value': "+12345679962"
    }],
    "emailAddresses": [{
      'value': ' '
    }]*/
  }
  var contactResourceName = People.People.createContact(contactResource)["resourceName"];
  // 2. CHECK IF GROUP EXISTS:
  var groupName = "Carpenters";
  var groups = People.ContactGroups.list()["contactGroups"];
  var group = groups.find(group => group["name"] === groupName);
  // 3. CREATE GROUP IF DOESN'T EXIST:
  if (!group) {
    var groupResource = {
      contactGroup: {
        name: groupName
      }
    }
    group = People.ContactGroups.create(groupResource);
  }
  var groupResourceName = group["resourceName"];
  // 4. ADD CONTACT TO GROUP:
  var membersResource = {
    "resourceNamesToAdd": [
      contactResourceName
    ]
  }
  People.ContactGroups.Members.modify(membersResource, groupResourceName);  
  return ContentService.createTextOutput("Success");
}

Reference: