使用Apps脚本将播放列表添加到YouTube频道

时间:2015-08-21 11:26:22

标签: google-apps-script youtube-api

我正在构建一个应该执行以下操作的脚本:

  1. 从电子表格中解析音乐数据(艺术家跟踪为字符串)
  2. 使用数据API的.Search类
  3. 搜索YT上的每个曲目
  4. 获取搜索到的每首曲目的最佳(大多数"相关")结果的视频ID,并将其存储在电子表格列中
  5. 在我的频道中创建播放列表
  6. 将搜索中的每个视频添加到播放列表
  7. 我遇到了第5步的问题。

    我只掌握JS和Google Apps脚本库的中级知识。

    这是我的功能:

    // GLOBAL VARIABLES
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var source = ss.getSheets()[0];
    var sourceDataRange = source.getDataRange();
    var sourceValues = sourceDataRange.getValues();
    var sourceRows = sourceDataRange.getNumRows();
    var sourceColumns = sourceDataRange.getNumColumns();
    var now = new Date();
        var nowYear = now.getYear();
        var nowMonth = now.getMonth() + 1;
        var nowDay = now.getDate();
    var templateURL = 'https://www.youtube.com/watch?v=';
    var vidId = [];
    
    // FUNCTION DEFINITION
    
    function youtubeSearchAndCreate() {
      youtubeSearch();
      createAndInsert();
    }
    
    function youtubeSearch() {
    
      // create new sheet from import copy
      var newSheetName = 'log_' + nowYear + '_' + nowMonth + '_' + nowDay; // names new sheet dynamically with today's date
      var newSheet = ss.insertSheet(newSheetName, 1);
    
      ss.getDataRange().offset(0, 0, sourceRows, sourceColumns).setValues(sourceValues);
    
      var artistsCol = 3;
      var artists = newSheet.getRange(2, artistsCol, sourceRows).getValues();
      var tracksCol = 4;
      var tracks = newSheet.getRange(2, tracksCol, sourceRows).getValues();
      var resultsCol = 1 + sourceColumns;
    
      newSheet.getRange(1, resultsCol).setValue('video_URL'); // set new search results column title
    
      var searchQueries = []; // search queries container array
      // var vidId = []; 
      var resultItems = [];
    
      for (var i=0; i<=sourceRows-2; i++) {
    
        searchQueries[i] = artists[i] + " - " + tracks[i]; // search query array generation
    
        var results = YouTube.Search.list('id', {q: searchQueries[i], maxResults: 1, type: 'video'}); // YouTube API searching for the most relevant video
        resultItems.push(results.items[0]);
        vidId.push(resultItems[i].id.videoId);
        newSheet.getRange(i+2, resultsCol).setValue(templateURL + vidId[i]); // insert each video URL into search results column
      }
    }
    
    function createAndInsert() {
      // create a new playlist and name it accordingly
      var newPlaylist = YouTube.Playlists.insert(
        {
          snippet: {
            title: nowYear + '-' + nowMonth + '-' + nowDay + ' TripleJ Hitlist',
            description: 'A playlist created with the YouTube API from ' + sourceRows - 1 + ' songs in the TripleJ Hitlist.'
          },
          status: {
            privacyStatus: 'private'
          }
        },
        'snippet,status'
      );
    
      // insert videos in the playlist
      var videosInserted = [];
      for (var i=0; i<vidId.length; i++) {
        // insert videos in the playlist according to their video ID gathered by the search script
        var insertVideo = YouTube.PlaylistItems.insert(
          {
            snippet: {
              playlistId: newPlaylist.id,
              resourceId: vidId[i]
            }
          },
          'snippet'
        );
        videosInserted.push(insertVideo.snippet);
      }
      Logger.log(videosInserted);
    }
    

    最后一个for循环似乎是问题:我得到一个错误,只是说&#34;必需&#34;没有任何其他信息...

    非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您只需要为PlaylistItem提供正确的格式。检查此示例:

Sub ReplaceInWord()

    Dim wdApp As New Word.Application, wdDoc As Word.Document, c As Range

    wdApp.Visible = True

    Set wdDoc = wdApp.Documents.Open("C:\Users\twilliams\Desktop\test.docx")
    For Each c In ActiveSheet.Range("C3:C64")
        If c.Value <> "" Then
            FindReplaceAnywhere wdDoc, c.Value, c.Offset(0, -1).Value
        End If
    Next c

    wdDoc.Close True

End Sub

Public Sub FindReplaceAnywhere(doc As Word.Document, pFindTxt As String, pReplaceTxt As String)
  Dim rngStory As Word.Range
  Dim lngJunk As Long
  Dim oShp As Shape

  'Fix the skipped blank Header/Footer problem
  lngJunk = doc.Sections(1).Headers(1).Range.StoryType
  'Iterate through all story types in the current document
  For Each rngStory In doc.StoryRanges
    'Iterate through all linked stories
    Do
      SearchAndReplaceInStory rngStory, pFindTxt, pReplaceTxt
      On Error Resume Next
      Select Case rngStory.StoryType
      Case 6, 7, 8, 9, 10, 11
        If rngStory.ShapeRange.Count > 0 Then
          For Each oShp In rngStory.ShapeRange
            If oShp.TextFrame.HasText Then
              SearchAndReplaceInStory oShp.TextFrame.TextRange, _
                  pFindTxt, pReplaceTxt
            End If
          Next
        End If
      Case Else
        'Do Nothing
      End Select
      On Error GoTo 0
      'Get next linked story (if any)
      Set rngStory = rngStory.NextStoryRange
    Loop Until rngStory Is Nothing
  Next
End Sub
Public Sub SearchAndReplaceInStory(ByVal rngStory As Word.Range, _
    ByVal strSearch As String, ByVal strReplace As String)
  With rngStory.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = strSearch
    .Replacement.Text = strReplace
    .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
  End With
End Sub

检查这是否适合您。