完成本頁其餘步驟,您將在短短幾分鐘內建立簡單的 Google Apps Script,以便向 YouTube Data API 發出要求。
範例應用程式示範如何將 YouTube 頻道資料新增至試算表。
必要條件
如要執行本快速入門導覽課程,您必須符合以下條件:
- 網際網路和網路瀏覽器存取。
- Google 帳戶。
- 存取 Google 雲端硬碟。
步驟 1:建立指令碼
- 在網路瀏覽器中開啟 Google 雲端硬碟。
- 依序點選 [新增] > [Google 試算表]。
- 在新試算表中,依序按一下 [擴充功能] > [Apps Script]。
- 將指令碼編輯器的內容替換為以下程式碼:
// Note: Apps Script automatically requests authorization
// based on the API's used in the code.
function channelsListByUsername(part, params) {
var response = YouTube.Channels.list(part,
params);
var channel = response.items[0];
var dataRow = [channel.id, channel.snippet.title, channel.statistics.viewCount];
SpreadsheetApp.getActiveSpreadsheet().appendRow(dataRow);
}
function getChannel() {
var ui = SpreadsheetApp.getUi();
var channelName = ui.prompt("Enter the channel name: ").getResponseText();
channelsListByUsername('snippet,contentDetails,statistics',
{'forUsername': channelName});
}
function getGoogleDevelopersChannel() {
channelsListByUsername('snippet,contentDetails,statistics',
{'forUsername': 'GoogleDevelopers'});
}
function onOpen() {
var firstCell = SpreadsheetApp.getActiveSheet().getRange(1, 1).getValue();
if (firstCell != 'ID') {
var headerRow = ["ID", "Title", "View count"];
SpreadsheetApp.getActiveSpreadsheet().appendRow(headerRow);
}
var ui = SpreadsheetApp.getUi();
ui.createMenu('YouTube Data')
.addItem('Add channel data', 'getChannel')
.addSeparator()
.addItem('Add GoogleDevelopers data', 'getGoogleDevelopersChannel')
.addToUi();
} - 按一下「儲存」圖示
。
- 按一下左上角的 [Untitled project],輸入「Quickstart」,然後按一下 [Rename]。
步驟 2:啟用 YouTube Data API
- 按一下左側的「編輯器」圖示 。
- 在左側的「服務」旁邊,按一下「新增服務」圖示 。
- 按一下 [YouTube Data API],然後按一下 [新增]。
步驟 3:執行範例
- 重新載入試算表。如果這是您加入程式碼後第一次載入試算表,第一列應填入 ID、Title 與 View count 標頭。
在選單列中,依序按一下 [YouTube Data] (YouTube 資料) > [Add GoogleDevelopers data] (新增 GoogleDevelopers 資料),即可在試算表中加入 GoogleDevelopers 管道相關資訊。(YouTube 資料選單會顯示在標準選單旁,例如「檔案」、「編輯」、「檢視」等)。
首次執行範例時,系統會提示您授予存取權。- 按一下 [檢閱權限]。
- 選擇所需帳戶。
- 按一下 [允許]。
在選單列中,依序按一下 [YouTube 資料] > [新增頻道資料],即可新增所選頻道的資料。按照系統提示輸入頻道名稱 (例如「GoogleDevelopers」或「SaturdayNightLive」) 並按一下 [確定]。指令碼會擷取該頻道的資料,並將其新增至試算表。
延伸閱讀
疑難排解
參考錯誤:未定義「[API 名稱]」
如果在 Apps Script 程式碼編輯器中未開啟 API,就會發生這個錯誤。重新執行步驟 2.b 並確認對應的開關已設為 [開啟]。