Skip to content

Instantly share code, notes, and snippets.

@jimorell
Forked from iamdaniele/Tweet functions.gs
Last active September 15, 2022 22:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimorell/f0a4ccaa8528775dcc07617facd556bf to your computer and use it in GitHub Desktop.
Save jimorell/f0a4ccaa8528775dcc07617facd556bf to your computer and use it in GitHub Desktop.
// @OnlyCurrentDoc
const BearerTokenKey = 'twitterBearerToken';
function onOpen() {
SpreadsheetApp
.getUi()
.createMenu('Twitter')
.addItem('Set Bearer token', 'helpers.requestBearerToken')
.addItem('Sign out', 'helpers.logout')
.addToUi();
}
const helpers = {};
helpers.bearerToken = () => PropertiesService.getScriptProperties().getProperty(BearerTokenKey);
helpers.tweet = (id) => JSON.parse(PropertiesService.getScriptProperties().getProperty(`tweet-${id}`));
helpers.checkBearerToken = () => {
if (!helpers.bearerToken()) {
throw new Error('You need to set a Bearer token before using this function. Select "Set Bearer Token" from the Twitter menu to set it.');
}
}
helpers.lookupUser = (tweet) => {
const authorId = tweet.data.author_id;
let author = {};
for (const user of tweet.includes.users) {
if (user.id === authorId) {
author = user;
return user;
}
}
return {};
}
helpers.logout = () => PropertiesService.getScriptProperties().deleteAllProperties();
helpers.tweetIdFromURL = (url) => {
const tweetRegex = url.match(/status\/(\d{1,19})/);
if (!tweetRegex) {
throw new Error('Invalid URL');
}
return tweetRegex[1];
}
helpers.requestBearerToken = () => {
// Build the input prompt
const ui = SpreadsheetApp.getUi();
const result = ui.prompt(
'Bearer token',
'A Bearer token is the access token to make requests to the Twitter API.\nYou can find the Bearer token in your Twitter Developer Portal under Keys and Tokens.\n\nPaste the Bearer token here:',
ui.ButtonSet.OK);
// Proceed if the user clicked OK
if (result.getSelectedButton() == ui.Button.OK) {
const bearerToken = result.getResponseText().trim();
// Do nothing if the user clicked OK without specifying a value
// (we can always ask for a token later)
if (bearerToken.length > 0) {
const properties = PropertiesService.getScriptProperties();
properties.setProperty(BearerTokenKey, bearerToken);
}
}
}
helpers.tweet = (tweetId) => {
helpers.checkBearerToken();
const lookupURL = `https://api.twitter.com/2/tweets/${tweetId}?expansions=author_id&user.fields=description`;
const response = UrlFetchApp.fetch(
lookupURL, {
headers: {
'Authorization': `Bearer ${helpers.bearerToken()}`
}
});
const tweet = JSON.parse(response.getContentText());
if (tweet.errors && !tweet.data) {
throw new Error(JSON.stringify(tweet.errors));
}
return tweet;
}
helpers.likes = (tweetId) => {
helpers.checkBearerToken();
const lookupURL = `https://api.twitter.com/2/tweets/${tweetId}/liking_users?user.fields=`;
const response2 = UrlFetchApp.fetch(
lookupURL, {
headers: {
'Authorization': `Bearer ${helpers.bearerToken()}`
}
});
const likes = JSON.parse(response2.getContentText());
if (likes.errors && !likes.data) {
throw new Error(JSON.stringify(likes.errors));
}
return likes;
}
/**
* Return tweet text from tweet url.
*
* @param {String} url The url of a tweet.
* @return The tweet text.
* @customfunction
*/
function TWEET(url) {
const tweetId = helpers.tweetIdFromURL(url);
const tweet = helpers.tweet(tweetId);
return tweet.data.text;
}
/**
* Return the author from tweet url.
*
* @param {String} url The url of a tweet.
* @return The tweet author.
* @customfunction
*/
function TWEET_AUTHOR(tweetURL) {
const tweetId = helpers.tweetIdFromURL(tweetURL);
const tweet = helpers.tweet(tweetId);
const user = helpers.lookupUser(tweet);
return user.username || '';
}
/**
* Return the bio of the author from tweet url.
*
* @param {String} url The url of a tweet.
* @return The tweet author's bio.
* @customfunction
*/
function BIO_OF_TWEET_AUTHOR(tweetURL) {
const tweetId = helpers.tweetIdFromURL(tweetURL);
const tweet = helpers.tweet(tweetId);
const user = helpers.lookupUser(tweet);
return user.description || '';
}
/**
* Return the number of likes from tweet url.
*
* @param {String} url The url of a tweet.
* @return The number of likes.
* @customfunction
*/
function TWEET_LIKES(tweetURL) {
const tweetId = helpers.tweetIdFromURL(tweetURL);
const likes = helpers.likes(tweetId);
return likes.fields;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment