Я пытаюсь сгенерировать Google Презентации из Google Таблиц; использовали сценарий Sheets без проблем, но когда я пытаюсь включить Google Slides, после проверки подлинности и получения запроса разрешения Oauth, я получаю эту ошибку, с которой я не могу найти ссылку; Я убедился, что API Google Презентаций и Drive API включены в Консоли разработчиков.403 ошибка с сообщением «API Google слайдов не использовался в проекте ... раньше или он отключен»
Запрос не удался для https://slides.googleapis.com/v1/presentations/ ... Обратный код: 403. Усеченный ответ сервера: {"error": {"code": 403, "message": "Google Slides API не был использован в проекте project-id- ... до или это disab ... (используйте параметр muteHttpExceptions для проверки полного ответа) (строка 93, файл «Код») «
Ошибка кода в следующем порядке: функция, которая сбой, была скопирована с How to download Google Slides as images? . ID клиента и секрет определены, пропущены только для безопасности
// from https://mashe.hawksey.info/2015/10/setting-up-oauth2-access-with-google-apps-script-blogger-api-example/
function getService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('slidesOauth')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
// this is blogger read only scope for write access is:
// https://www.googleapis.com/auth/blogger
.setScope('https://www.googleapis.com/auth/blogger.readonly')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', Session.getActiveUser().getEmail())
// Requests offline access.
.setParam('access_type', 'offline')
// Forces the approval prompt every time. This is useful for testing,
// but not desirable in a production application.
.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var oauthService = getService();
var isAuthorized = oauthService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
// from https://stackoverflow.com/questions/31662455/how-to-download-google-slides-as-images/40678925#40678925
function downloadPresentation(id) {
var slideIds = getSlideIds(id);
for (var i = 0, slideId; slideId = slideIds[i]; i++) {
downloadSlide('Slide ' + (i + 1), id, slideId);
}
}
function downloadSlide(name, presentationId, slideId) {
var url = 'https://docs.google.com/presentation/d/' + presentationId +
'/export/png?id=' + presentationId + '&pageid=' + slideId;
var options = {
headers: {
Authorization: 'Bearer ' + getService().getAccessToken()
}
};
var response = UrlFetchApp.fetch(url, options); // This is the failing line 93
var image = response.getAs(MimeType.PNG);
image.setName(name);
DriveApp.createFile(image);
}
Включены ли API для правильного идентификатора проекта? Выберите из раскрывающегося списка проекта в консоли разработчика? (Я упоминаю об этом, так как раньше у меня была эта ошибка, чтобы включить API в неправильный проект) – Bardy
Да, это единственный проект в этой учетной записи и потребовалось некоторое время, чтобы выяснить, как включить API для проекта. Но спасибо за предложение –