javascript 在Google Apps脚本中修改Bitly API V4以获取所有链接[已关闭]

vltsax25  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(93)

已关闭,此问题需要更focused。它目前不接受回答。
**想改善这个问题吗?**更新问题,使其只关注editing this post的一个问题。

21小时前关门了。
Improve this question
经过一系列迭代后,这在一定程度上可以工作,但只返回50行。在犯了这么多错误之后,我把这个作为基准。如何修改它以从帐户中检索所有链接,但遵守速率限制......例如每秒返回1个请求?

function bitlyStats() {
  var accessToken = 'key'; // Please set your access token here.
  var fetchUrl = 'https://api-ssl.bitly.com/v4/groups?access_token=' + accessToken; // Get the group information from the api.
  var headers = {
    'Authorization': 'Bearer '+ accessToken,
  };
  var params = {
    'method' : 'get',
    'contentType': 'application/json',
    'headers' : headers,
    'muteHttpExceptions' : true
  };
  var response = UrlFetchApp.fetch(fetchUrl, params); // Fetch the response from the api.
  var groupInfo = JSON.parse(response.getContentText()); // Parse the response as JSON object.
  var groupId = groupInfo.groups[0].guid; // Get the group id from the response.
  var fetchUrl2 = 'https://api-ssl.bitly.com/v4/groups/' + groupId + '/bitlinks?access_token=' + accessToken; // Get the bitlinks information from the api using the group id.
  var response2 = UrlFetchApp.fetch(fetchUrl2, params); // Fetch the response from the api.
  var bitlinksInfo = JSON.parse(response2.getContentText()); // Parse the response as JSON object.
  var bitlinks = bitlinksInfo.links; // Get the array of bitlinks from the response.
  var activeSheet = SpreadsheetApp.getActiveSheet(); // Get the active Google Sheet.
  activeSheet.getRange('A1').setValue('ID'); // Write the header for ID column.
  activeSheet.getRange('B1').setValue('Link'); // Write the header for Link column.
  activeSheet.getRange('C1').setValue('Custom Bitlinks'); // Write the header for Custom Bitlinks column.
  activeSheet.getRange('D1').setValue('Long URL'); // Write the header for Long URL column.
  activeSheet.getRange('E1').setValue('Title'); // Write the header for Title column.
  activeSheet.getRange('F1').setValue('Created At'); // Write the header for Created At column.
  for (var i = 0; i < bitlinks.length; i++) { // Loop through the array of bitlinks.
    var bitlink = bitlinks[i]; // Get the current bitlink object.
    var id = bitlink.id; // Get the id of the bitlink.
    var link = bitlink.link; // Get the link of the bitlink.
    var customBitlinks = bitlink.custom_bitlinks; // Get the custom bitlinks of the bitlink.
    var longUrl = bitlink.long_url; // Get the long url of the bitlink.
    var title = bitlink.title; // Get the title of the bitlink.
    var createdAt = bitlink.created_at; // Get the date the bitlink was created.
    activeSheet.getRange('A' + (i + 2)).setValue(id); // Write the id to the Google Sheet.
    activeSheet.getRange('B' + (i + 2)).setValue(link); // Write the link to the Google Sheet.
    activeSheet.getRange('C' + (i + 2)).setValue(customBitlinks); // Write the custom bitlinks to the Google Sheet.
    activeSheet.getRange('D' + (i + 2)).setValue(longUrl); // Write the long url to the Google Sheet.
    activeSheet.getRange('E' + (i + 2)).setValue(title); // Write the title to the Google Sheet.
    activeSheet.getRange('F' + (i + 2)).setValue(createdAt); // Write the date the bitlink was created to the Google Sheet.
  }
  return bitlinks; // Return the array of bitlinks.
}
gijlo24d

gijlo24d1#

**这个工作!**用于生产。

function bitlyStats() {
  var accessToken = 'YOUR_API_KEY'; // Please set your access token here.
  var fetchUrl = 'https://api-ssl.bitly.com/v4/groups?access_token=' + accessToken; // Get the group information from the api.
  var headers = {
    'Authorization': 'Bearer '+ accessToken,
  };
  var params = {
    'method' : 'get',
    'contentType': 'application/json',
    'headers' : headers,
    'muteHttpExceptions' : true
  };
  var response = UrlFetchApp.fetch(fetchUrl, params); // Fetch the response from the api.
  var groupInfo = JSON.parse(response.getContentText()); // Parse the response as JSON object.
  var groupId = groupInfo.groups[0].guid; // Get the group id from the response.
  var fetchUrl2 = 'https://api-ssl.bitly.com/v4/groups/' + groupId + '/bitlinks?access_token=' + accessToken; // Get the bitlinks information from the api using the group id.
  var response2 = UrlFetchApp.fetch(fetchUrl2, params); // Fetch the first page of the response from the api.
  var bitlinksInfo = JSON.parse(response2.getContentText()); // Parse the response as JSON object.
  var bitlinks = bitlinksInfo.links; // Get the array of bitlinks from the response.
  var activeSheet = SpreadsheetApp.getActiveSheet(); // Get the active Google Sheet.
  activeSheet.getRange('A1').setValue('ID'); // Write the header for ID column.
  activeSheet.getRange('B1').setValue('Link'); // Write the header for Link column.
  activeSheet.getRange('C1').setValue('Custom Bitlinks'); // Write the header for Custom Bitlinks column.
  activeSheet.getRange('D1').setValue('Long URL'); // Write the header for Long URL column.
  activeSheet.getRange('E1').setValue('Title'); // Write the header for Title column.
  activeSheet.getRange('F1').setValue('Created At'); // Write the header for Created At column.
  var row = 2; // Initialize the row number to write to the Google Sheet.
  while (bitlinksInfo.pagination.next) { // Loop until there is no next page.
    for (var i = 0; i < bitlinks.length; i++) { // Loop through the array of bitlinks.
      var bitlink = bitlinks[i]; // Get the current bitlink object.
      var id = bitlink.id; // Get the id of the bitlink.
      var link = bitlink.link; // Get the link of the bitlink.
      var customBitlinks = bitlink.custom_bitlinks; // Get the custom bitlinks of the bitlink.
      var longUrl = bitlink.long_url; // Get the long url of the bitlink.
      var title = bitlink.title; // Get the title of the bitlink.
      var createdAt = bitlink.created_at; // Get the date the bitlink was created.
      activeSheet.getRange('A' + row).setValue(id); // Write the id to the Google Sheet.
      activeSheet.getRange('B' + row).setValue(link); // Write the link to the Google Sheet.
      activeSheet.getRange('C' + row).setValue(customBitlinks); // Write the custom bitlinks to the Google Sheet.
      activeSheet.getRange('D' + row).setValue(longUrl); // Write the long url to the Google Sheet.
      activeSheet.getRange('E' + row).setValue(title); // Write the title to the Google Sheet.
      activeSheet.getRange('F' + row).setValue(createdAt); // Write the date the bitlink was created to the Google Sheet.
      row++; // Increment the row number.
    }
    var fetchUrl3 = bitlinksInfo.pagination.next; // Get the next page url from the response.
    var response3 = UrlFetchApp.fetch(fetchUrl3, params); // Fetch the next page of the response from the api.
    bitlinksInfo = JSON.parse(response3.getContentText()); // Parse the response as JSON object.
    bitlinks = bitlinksInfo.links; // Get the array of bitlinks from the response.
    var fetchUrl4 = 'https://api-ssl.bitly.com/v4/user/platform_limits?access_token=' + accessToken; // Get the platform limits information from the api.
    var response4 = UrlFetchApp.fetch(fetchUrl4, params); // Fetch the response from the api.
    var platformLimitsInfo = JSON.parse(response4.getContentText()); // Parse the response as JSON object.
    var rateLimit = platformLimitsInfo.rate_limit; // Get the current rate limit from the response.
    var remaining = platformLimitsInfo.remaining; // Get the remaining number of requests from the response.
    var reset = platformLimitsInfo.reset; // Get the time until the limit resets from the response.
    if (remaining == 0) { // Check if the remaining number of requests is zero.
      var currentTime = new Date().getTime(); // Get the current time in milliseconds.
      var resetTime = new Date(reset).getTime(); // Get the reset time in milliseconds.
      if (currentTime < resetTime) { // Check if the current time is before the reset time.
        var waitTime = resetTime - currentTime; // Calculate the wait time in milliseconds.
        Utilities.sleep(waitTime); // Pause the execution for the wait time.
      }
    } else if (remaining < rateLimit / 10) { // Check if the remaining number of requests is less than 10% of the rate limit.
      var fetchUrl5 = 'https://api-ssl.bitly.com/v4/user/plan_limits?access_token=' + accessToken; // Get the plan limits information from the api.
      var response5 = UrlFetchApp.fetch(fetchUrl5, params); // Fetch the response from the api.
      var planLimitsInfo = JSON.parse(response5.getContentText()); // Parse the response as JSON object.
      var maxPageSize = planLimitsInfo.max_page_size; // Get the maximum page size from the response.
      var size = Math.floor(maxPageSize / 2); // Reduce the size by half.
      fetchUrl3 = fetchUrl3 + '&size=' + size; // Add the size parameter to the next page url.
      response3 = UrlFetchApp.fetch(fetchUrl3, params); // Fetch the next page of the response from the api with the reduced size.
      bitlinksInfo = JSON.parse(response3.getContentText()); // Parse the response as JSON object.
      bitlinks = bitlinksInfo.links; // Get the array of bitlinks from the response with the reduced size.
    }
  }
  return bitlinks; // Return the array of bitlinks.
}
qmelpv7a

qmelpv7a2#

建议:调整API调用的参数

查看Bitly的API文档,按组检索Bitlinks的默认大小为50个项目。我建议修改你的fetchUrl2变量,以包含要返回的结果的大小。

编辑:

在运行进一步的测试后,似乎有一个大小限制为100。我不确定是否有一个更高的限制,这取决于Bitly订阅,但我已经修改了您的代码,如果它超过100,它将通过API返回的所有链接运行。
试试这个:

function bitlyStats() {
  var accessToken = 'key'; // Please set your access token here.
  var fetchUrl = 'https://api-ssl.bitly.com/v4/groups?access_token=' + accessToken; // Get the group information from the api.
  var headers = {
    'Authorization': 'Bearer ' + accessToken,
  };
  var params = {
    'method': 'get',
    'contentType': 'application/json',
    'headers': headers,
    'muteHttpExceptions': true,
  };

  var response = UrlFetchApp.fetch(fetchUrl, params); // Fetch the response from the api.
  var groupInfo = JSON.parse(response.getContentText()); // Parse the response as JSON object.
  var groupId = groupInfo.groups[0].guid; // Get the group id from the response.
  var fetchUrl2 = `https://api-ssl.bitly.com/v4/groups/${groupId}/bitlinks?size=100&access_token=${accessToken}`; //Gets the 1st page of the results
  var activeSheet = SpreadsheetApp.getActiveSheet(); // Get the active Google Sheet.
  activeSheet.getRange('A1:F1').setValues([['ID', 'Link', 'Custom Bitlinks', 'Long URL', 'Title', 'Created At']]); //Writes the header column
  do {
    var response2 = UrlFetchApp.fetch(fetchUrl2, params); // Fetch the response from the api.
    var bitlinksInfo = JSON.parse(response2.getContentText()); // Parse the response as JSON object.
    var bitlinks = bitlinksInfo.links; // Get the array of bitlinks from the response.
    for (var i = 0; i < bitlinks.length; i++) { // Loop through the array of bitlinks.
      var bitlink = bitlinks[i]; // Get the current bitlink object.
      var id = bitlink.id; // Get the id of the bitlink.
      var link = bitlink.link; // Get the link of the bitlink.
      var customBitlinks = bitlink.custom_bitlinks; // Get the custom bitlinks of the bitlink.
      var longUrl = bitlink.long_url; // Get the long url of the bitlink.
      var title = bitlink.title; // Get the title of the bitlink.
      var createdAt = bitlink.created_at; // Get the date the bitlink was created.
      activeSheet.getRange(activeSheet.getLastRow()+1,1,1,6).setValues([[id,link,customBitlinks,longUrl,title,createdAt]]); // Writes the data to the sheet
    }
    var toSearch = bitlinksInfo.pagination.search_after; // Gets the search key for the next page
    var fetchUrl2 = `https://api-ssl.bitly.com/v4/groups/${groupId}/bitlinks?size=100&search_after=${toSearch}&access_token=${accessToken}`; // Gets the bitlinks information of the succeeding pages.
  } while (toSearch != ''); //Loop will run as long as there's a next page of results.

  return bitlinks; // Return the array of bitlinks.
}

参考:

  • 按组检索位链接

相关问题