программно включить заданный c appscript для листов, связанных с контейнером - PullRequest
0 голосов
/ 16 февраля 2020

Я бы хотел программно включить связанный с контейнером скрипт. Я могу создать скрипт приложения через API и прикрепить к листу. проблема в том, что если на листе уже включен другой сценарий приложения, этот сценарий работает вместо моего сценария, если я не укажу его в tools->script editor->select project->enable. Я создал сценарий через API. Могу ли я включить его через API?

пока у меня есть этот код ниже. но нет кода для того, чтобы включить скрипт программно. В качестве примечания, приведенный ниже сценарий будет работать должным образом, если к таблице не будет прикреплен другой сценарий приложения. В противном случае он непредсказуем

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
#https://script.google.com/home/usersettings
    $client = new Google_Client();
    $client->setApplicationName('Google Apps Script API PHP Quickstart');
    $client->setScopes(['https://www.googleapis.com/auth/script.projects','https://www.googleapis.com/auth/script.scriptapp','https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/spreadsheets.readonly','https://www.googleapis.com/auth/script.external_request','https://www.googleapis.com/auth/script.deployments']);
    $client->setAuthConfig('credentials.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 = '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;
}


/**
 * Shows basic usage of the Apps Script API.
 *
 * Call the Apps Script API to create a new script project, upload files to the
 * project, and log the script's URL to the user.
 */
$client = getClient();
$service = new Google_Service_Script($client);

// Create a management request object.
$request = new Google_Service_Script_CreateProjectRequest();
$request->setTitle('spreadsheet_script 40');
$request->setParentId('11111');
$response = $service->projects->create($request);

$scriptId = $response->getScriptId();

$code = <<<EOT
function onEdit(e) {
  var ui = SpreadsheetApp.getUi();
  ui.alert('alert 30091');
}


EOT;
$file1 = new Google_Service_Script_ScriptFile();
$file1->setName('spreadsheet script 56');
$file1->setType('SERVER_JS');
$file1->setSource($code);

$manifest = <<<EOT
{
  "timeZone": "America/New_York",
  "exceptionLogging": "CLOUD",
    "oauthScopes": [
     "https://www.googleapis.com/auth/script.projects",
     "https://www.googleapis.com/auth/script.scriptapp",
     "https://www.googleapis.com/auth/spreadsheets",
     "https://www.googleapis.com/auth/spreadsheets.readonly",
     "https://www.googleapis.com/auth/script.external_request",
     "https://www.googleapis.com/auth/script.deployments"
  ]
}
EOT;
$file2 = new Google_Service_Script_ScriptFile();
$file2->setName('appsscript');
$file2->setType('JSON');
$file2->setSource($manifest);

$request = new Google_Service_Script_Content();
$request->setScriptId($scriptId);
$request->setFiles([$file1, $file2]);

$request1=new Google_Service_Script_Version();
$request1->setScriptId($scriptId);
$request1->setVersionNumber(1);
$service->projects_versions->create($scriptId,$request1);

$request2=new Google_Service_Script_DeploymentConfig();
$request2->setScriptId($scriptId);
$request2->setVersionNumber(1);

$service->projects_deployments->create($scriptId,$request2);

$response = $service->projects->updateContent($scriptId, $request);
echo "https://script.google.com/d/" . $response->getScriptId() . "/edit\n";
.
...