API call to directory.members.insert failed with error: Resource Not Found: groupKey

API call to directory.members.insert failed with error: Resource Not Found: groupKey

我正在为 Google 工作表编写脚本,使用在数据中找到的电子邮件将成员添加到特定的 Google 组。似乎找到了 Google 组,并且正确返回了 Google 组的 email/groupKey。会话 (me) 中的 currentUser 是组 (owner) 的成员。我启用了管理目录 API。在一次测试中,我什至调用了 group.getUsers() 并正确返回了该组的所有成员。日志记录中的所有值都符合预期。

为什么插入调用仍然失败? google 群里没有加入的成员是什么?

我已经包含了代码和日志。

代码

function addMembersFromSheet() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MySheet");
  var emails = sheet.getRange(2,3,sheet.getLastRow()-1,1).getValues();
  Logger.log(emails);
  
  var currentUser = Session.getActiveUser();
  Logger.log(currentUser);
 
  var group = GroupsApp.getGroupByEmail("<mygroup>@googlegroups.com");
    
  if (group.hasUser(currentUser)) {
    Logger.log("You are a member of this group. group is: ");
    Logger.log(group.getEmail()); //correctly finds the group
  
  }
  else {
    Logger.log("You are not a member of this group.");
  }

  for(i = 0; i < emails.length; i++) {
    try {
      addMember(emails[i][0], group);
    }
    catch(e) {
      console.error(e);
      Logger.log(e);
      continue;
    }   
  }
}

function addMember(email, group) {
  
  var hasMember = group.hasUser(email);
  Logger.log(hasMember);
  Utilities.sleep(1000);
  
  if(!hasMember) {
    var newMember = {email: email, 
                     role: "MEMBER",
                     delivery_settings: "NONE"};
    Logger.log(newMember);
    Logger.log(group.getEmail())
    AdminDirectory.Members.insert(newMember, group.getEmail());
  }
}

日志输出(对私人详细信息进行了一些更改):

Jul 26, 2020, 3:22:09 PM    Info    [[<testmember>@gmail.com]]
Jul 26, 2020, 3:22:09 PM    Info    <currentUser>@gmail.com
Jul 26, 2020, 3:22:10 PM    Info    You are a member of this group. group is: 
Jul 26, 2020, 3:22:10 PM    Info    <mygroup>@googlegroups.com
Jul 26, 2020, 3:22:10 PM    Info    false
Jul 26, 2020, 3:22:11 PM    Info    {delivery_settings=NONE, role=MEMBER, email=<testmember>@gmail.com}
Jul 26, 2020, 3:22:11 PM    Info    <mygroup>@googlegroups.com
Jul 26, 2020, 3:22:11 PM    Error   { [GoogleJsonResponseException: API call to directory.members.insert failed with error: Resource Not Found: groupKey]
  details: 
   { code: 404,
     message: 'Resource Not Found: groupKey',
     errors: [ [Object] ] },
  name: 'GoogleJsonResponseException' }
Jul 26, 2020, 3:22:11 PM    Info    GoogleJsonResponseException: API call to directory.members.insert failed with error: Resource Not Found: groupKey

您正在检索一组消费者帐户并尝试对其执行 GSuite 管理员的方法

  • 从你的群组名称(以 googlegroups.com 结尾)我可以假设你有一个消费者帐户(免费 Gmail 帐户)
  • 但是,class AdminDirectory 的方法仅适用于 GSsuite 帐户的管理员。 documentation 指定:

This API gives administrators of G Suite domains (including resellers) the ability to manage devices, groups, users, and other entities in their domains.

  • 因此,不幸的是,对于消费者帐户,您不能使用 AdminDirectory 以编程方式插入用户。
  • 您可以使用 GroupsApp,但此服务没有插入用户的方法。