Get Twitter Followers/Following Count with Twitter API and Add to Google Sheets Sample Code - Google Apps Script (GAS) Edition
I’ll introduce Google Apps Script (GAS) sample code to get followers/following counts with Twitter API and add them to Google Sheets.
I used SocialDog for about a month, but since I was only using some features, I canceled the paid plan.
For my use case, being able to track daily trends of Twitter account followers and following counts was sufficient, so I implemented my own process to add data to Google Sheets using Twitter API + GAS.
Uses Twitter API GET /2/users/by/username/:username.
const TWITTER_USERNAME = PropertiesService.getScriptProperties().getProperty('TWITTER_USERNAME');
const TWITTER_API_BEARER_TOKEN = PropertiesService.getScriptProperties().getProperty('TWITTER_API_BEARER_TOKEN');
const GOOGLE_SHEET_ID = PropertiesService.getScriptProperties().getProperty('GOOGLE_SHEET_ID');
function getTwitterPublicMetrics(){
const url = `https://api.twitter.com/2/users/by/username/${TWITTER_USERNAME}?user.fields=public_metrics`;
const options = {
method: 'get',
headers: {
authorization: `Bearer ${TWITTER_API_BEARER_TOKEN}`
}
};
const response = JSON.parse(UrlFetchApp.fetch(url, options));
const row = Object.values(response["data"]["public_metrics"]);
const today = Utilities.formatDate(new Date(), 'JST', 'yyyy-MM-dd');
row.unshift(today);
const sheetName = 'シート1';
const sheet = SpreadsheetApp.openById(GOOGLE_SHEET_ID).getSheetByName(sheetName);
sheet.appendRow(row);
}
Add the following to row 1:
From the spreadsheet menu [Extensions] - [Apps Script], create new and paste the sample code above.
Add a trigger to run once daily between 11 PM and midnight.
That’s all from the Gemba, where I used Twitter API + Google Apps Script to get followers/following counts and add them to Google Sheets.