G Suite のAPIを使って作成済みのグループの設定をする
問題
G SuiteのGoogleグループで、APIを利用して、一括でグループの設定をしたいです。

答え
google/apiclient を使う例。
1.場所を作る
$ mkdir xxx
$ cd xxx
2.google/apiclient をcomposerで持ってくる
$ composer require google/apiclient
3.Googleグループを作るphpスクリプトを書く
以下は、いくつかのグループに同じ設定を適用する例です。
$ vi patch.php
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
// Googleの公式のサンプルのまね
function getClient()
{
$client = new Google_Client();
$client->setApplicationName("sample application");
$client->setScopes(implode(' ', array(
'https://www.googleapis.com/auth/apps.groups.settings',
)));
$client->setAuthConfigFile(__DIR__ . '/client_secret_000000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = __DIR__ . '/token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// 設定対象のグループの一覧
$entries = array(
'test001@example.com',
'test002@example.com',
'test003@example.com'
);
$client = getClient();
$service = new Google_Service_Groupssettings($client);
foreach ($entries as $entry) {
try {
// 設定値をセット
$data = new Google_Service_Groupssettings_Groups();
$data->isArchived = true;
$data->primaryLanguage = 'ja';
$data->replyTo = "REPLY_TO_LIST";
$data->spamModerationLevel = "ALLOW";
$data->whoCanAdd = "ALL_MEMBERS_CAN_ADD";
$data->whoCanContactOwner = "ANYONE_CAN_CONTACT";
$data->whoCanInvite = "ALL_MEMBERS_CAN_INVITE";
$data->whoCanJoin = "ALL_IN_DOMAIN_CAN_JOIN";
$data->whoCanPostMessage = "ALL_IN_DOMAIN_CAN_POST";
$data->whoCanViewGroup = "ALL_IN_DOMAIN_CAN_VIEW";
$data->whoCanViewMembership = "ALL_MEMBERS_CAN_VIEW";
$data->whoCanAssignTopics ="ALL_MEMBERS";
$data->whoCanUnassignTopic = "ALL_MEMBERS";
$data->whoCanTakeTopics = "ALL_MEMBERS";
$data->whoCanMarkDuplicate = "ALL_MEMBERS";
$data->whoCanMarkNoResponseNeeded = "ALL_MEMBERS";
$data->whoCanMarkFavoriteReplyOnOwnTopic = "ALL_MEMBERS";
$data->whoCanMarkFavoriteReplyOnAnyTopic = "ALL_MEMBERS";
$data->whoCanUnmarkFavoriteReplyOnAnyTopic = "ALL_MEMBERS";
$data->whoCanEnterFreeFormTags = "ALL_MEMBERS";
$data->whoCanModifyTagsAndCategories = "ALL_MEMBERS";
$data->whoCanApproveMembers = "ALL_MEMBERS_CAN_APPROVE";
$data->whoCanBanUsers = "ALL_MEMBERS";
$data->whoCanModifyMembers = "ALL_MEMBERS";
$data->whoCanHideAbuse = "ALL_MEMBERS";
$data->whoCanMakeTopicsSticky = "ALL_MEMBERS";
$data->whoCanModerateMembers = "ALL_MEMBERS";
$data->whoCanAssistContent = "ALL_MEMBERS";
$data->enableCollaborativeInbox = true;
// 適用
$service->groups->patch($entry, $data, ["alt" => "json"]);
} catch (Google_Service_Exception $e) {
// @todo エラー時の対応
throw $e;
}
}
グループの項目と設定内容はこちらを参照。
https://developers.google.com/admin-sdk/groups-settings/v1/reference/groups
4.OAuth 2.0 クライアント IDを作成
※すでに作成済み、認証情報取得済みなら不要です
https://console.developers.google.com/apis/credentials
JSON形式の認証情報をダウンロードして保存する。
3のphpのプログラム中の client_secret_000000000000-xxxxxxxxxxxxx.json のファイル名はダウンロードしたものにする。
5.コマンドラインで実行する
$ php patch.php
数十、数百など多数のグループがあるとき、管理画面でポチポチしなくても、まとめて同じ設定にすることができます。
なお、いくつかの項目はAPIで操作できないようなので、これだけは管理画面で設定せざるを得ないようです。
例)
設定 → メールオプション → 件名のプレフィックス
権限 → 基本的な権限 → この組織外のメンバーを許可する
権限 → 管理権限 → 自分の投稿を編集
権限 → 投稿権限 → 投稿者に返信

G Suite への移行作業が大変なときはご相談ください
- 既存のメーリングリストをGoogleグループに移したい
- 既存のメーリングリストの過去ログをGoogleグループに入れたい
- 多数のGoogleグループの設定を管理したい
- 既存のメールアドレスで G Suite(Gmail)に移行したい
内容に応じてお見積りします。
➡ お問い合わせはこちらまで rs@softel.jp