Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fetch trends and popular tweets in twitter and display them on Google Spreadsheets
/**********
MIT License
Copyright (c) 2018 snakazawa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********/
/**********
Twitter Trend Spreadsheet
require libraries:
- googlesamples/apps-script-oauth1 v15, https://github.com/googlesamples/apps-script-oauth1, Apache License 2.0
You must create 'config' sheet and set twitter api variables (i.e., API_KEY, API_SECRET, ACCESS_TOKEN and ACCESS_TOKEN_SECRET) and other config variables (see CONFIG_CELL_POS variable).
**********/
var SHEET_NAMES = {
CONFIG: 'config',
LIST: 'list',
TWEETS: 'tweets'
};
var CONFIG_CELL_POS = {
API_KEY: [2, 2],
API_SECRET: [3, 2],
ACCESS_TOKEN: [4, 2],
ACCESS_TOKEN_SECRET: [5, 2],
TREND_LIMIT: [6, 2],
TWEET_LIMIT: [7, 2],
WOEID: [8, 2],
IMAGE_HEIGTH: [11, 2],
IMAGE_WIDTH: [12, 2]
};
function main() {
var ss = getActiveSpreadsheet();
// fetch and update trend list
var listSheet = findOrCreateSheetByName(ss, SHEET_NAMES.LIST);
var trends = fetchTrend();
updateTrendList(listSheet, trends);
// fetch and update several popular tweets
var allTweets = [];
trends.forEach(function (trend) {
var tweets = fetchPopularTweetList(trend.name);
tweets.forEach(function (tweet) {
tweet.score = tweet.retweet_count + tweet.favorite_count;
tweet.keyword = trend.name;
allTweets.push(tweet);
});
});
// desc order
allTweets.sort(function (a, b) { return b.score - a.score; });
var tweetsSheet = findOrCreateSheetByName(ss, SHEET_NAMES.TWEETS);
updateTweetList(tweetsSheet, allTweets);
}
function clearSheets() {
clearSheetsByNames([SHEET_NAMES.LIST, SHEET_NAMES.TWEETS]);
}
function updateTrendList(sheet, trends) {
var header = ['name', 'volume', 'url'];
var body = trends.map(function (trend) {
return [
trend.name,
trend.tweet_volume,
trend.url
];
});
writeTable(sheet, header, body);
}
function updateTweetList(sheet, tweets) {
var header = ['keyword', 'photo', 'user', 'retweets', 'favorites', 'text', 'url'];
var body = tweets.map(function (tweet) {
var mediaUrl = getFirstMediaUrl(tweet);
return [
tweet.keyword,
mediaUrl ? '=IMAGE("' + mediaUrl + '")' : null,
tweet.user.name + '(@' + tweet.user.screen_name + ')',
tweet.retweet_count,
tweet.favorite_count,
tweet.text,
'https://twitter.com/' + tweet.user.screen_name + '/status/' + tweet.id_str
];
});
writeTable(sheet, header, body);
// resize image
sheet.setColumnWidth(header.indexOf('photo') + 1, getConfig('IMAGE_WIDTH'));
tweets.forEach(function (tweet, i) {
if (getFirstMediaUrl(tweet)) {
sheet.setRowHeight(i + 2, getConfig('IMAGE_HEIGTH'));
}
});
}
/*** Twitter ***/
function getService() {
return OAuth1.createService('Twitter')
.setConsumerKey(getConfig('API_KEY'))
.setConsumerSecret(getConfig('API_SECRET'))
.setAccessToken(getConfig('ACCESS_TOKEN'), getConfig('ACCESS_TOKEN_SECRET'));
}
function fetchTrend() {
var service = getService();
var url = 'https://api.twitter.com/1.1/trends/place.json?id=' + getConfig('WOEID');
var response = service.fetch(url);
var result = JSON.parse(response.getContentText());
return result[0].trends.slice(0, getConfig('TREND_LIMIT'));
}
function fetchPopularTweetList(keyword) {
var service = getService();
var url = 'https://api.twitter.com/1.1/search/tweets.json?q=' + encodeURIComponent(keyword) + '&result_type=popular&count=' + getConfig('TWEET_LIMIT');
var response = service.fetch(url);
var result = JSON.parse(response.getContentText());
return result.statuses;
}
function getFirstMediaUrl(tweet) {
if (!tweet.entities.media || !tweet.entities.media.length) { return null; }
var media = tweet.entities.media[0];
return media.media_url_https || media.media_url;
}
/*** utilities ***/
var _memoSpreadSheet = null;
function getActiveSpreadsheet() {
return _memoSpreadSheet = _memoSpreadSheet || SpreadsheetApp.getActiveSpreadsheet();
}
var _memoConfigSheet = null;
function getConfigSheet() {
return _memoConfigSheet = _memoConfigSheet || getActiveSpreadsheet().getSheetByName(SHEET_NAMES.CONFIG);
}
function getConfig(key) {
var sheet = getConfigSheet();
var pos = CONFIG_CELL_POS[key];
return sheet.getRange(pos[0], pos[1]).getValue();
}
function clearSheetsByNames(sheetNames) {
var ss = getActiveSpreadsheet();
sheetNames
.map(function (name) { return ss.getSheetByName(name); })
.filter(function (sheet) { return sheet; })
.forEach(function (sheet) { ss.deleteSheet(sheet); });
}
function writeTable(sheet, header, body) {
var cnum = header.length;
var rnum = body.length;
var ary = [header].concat(body);
sheet.getRange(1, 1, rnum + 1, cnum).setValues(ary);
// resize columns
for (var i = 0; i < cnum; ++i) {
sheet.autoResizeColumn(i + 1);
}
}
function findOrCreateSheetByName(ss, name) {
return ss.getSheetByName(name) || ss.insertSheet(name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment