Last active
April 1, 2016 00:10
-
-
Save chipoglesby/fd4cd8e77133c5339899a1c4ee71d4ec to your computer and use it in GitHub Desktop.
An example of a Google Apps Scripts that calls the Youtube API and writes results to BigQuery.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function youTubeAnalytics() { | |
| projectId = "xxx"; | |
| datasetId = "xxx"; | |
| tableId = 'xxx'; | |
| myChannels = YouTube.Channels.list('id', {mine: true}); | |
| channel = myChannels.items[0]; | |
| channelId = channel.id; | |
| yesterday = new Date(); | |
| yesterday.setDate(yesterday.getDate() - 2); // I'm setting it back two days because that's the most recent date for the API. | |
| yesterday = Utilities.formatDate(yesterday, 'UTC', 'yyyy-MM-dd'); | |
| bigQueryDate = Utilities.formatDate(yesterday, "UTC", "yyyy-MM-dd'T'HH:mm:ss'Z'"); | |
| data = []; | |
| analyticsResponse = YouTubeAnalytics.Reports.query( | |
| 'channel==' + channelId, | |
| yesterday, | |
| yesterday, | |
| 'estimatedMinutesWatched,views,likes,subscribersGained', | |
| {dimensions: 'video','max-results': '200',sort: '-views'}); | |
| for (i=0; i < analyticsResponse.rows.length; i++){ | |
| vid = analyticsResponse.rows[i][0]; | |
| estimatedMinutesWatched = analyticsResponse.rows[i][1]; | |
| views = analyticsResponse.rows[i][2]; | |
| likes = analyticsResponse.rows[i][3]; | |
| subscribersGained = analyticsResponse.rows[i][4]; | |
| if(vid){ | |
| videoResponse = YouTube.Videos.list('snippet',{id: vid}); | |
| title = videoResponse.items[0].snippet.title; | |
| data.push(JSON.stringify({ | |
| 'title':title, | |
| 'estimatedMinutesWatched':estimatedMinutesWatched, | |
| 'views':views, | |
| 'likes':likes, | |
| 'subscribersGained':subscribersGained, | |
| 'date': bigQueryDate})); | |
| } | |
| } | |
| data = data.join('\n'); | |
| blobData = Utilities.newBlob(data, "application/octet-stream"); | |
| job = { | |
| configuration: { | |
| load: { | |
| destinationTable: { | |
| projectId: projectId, | |
| datasetId: datasetId, | |
| tableId: tableId | |
| }, | |
| sourceFormat: "NEWLINE_DELIMITED_JSON" | |
| } | |
| } | |
| } | |
| job = BigQuery.Jobs.insert(job, projectId, blobData); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment