Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Forked from iamdaniele/Tweet functions.gs
Last active September 15, 2022 22:34
Show Gist options
  • Save mhawksey/ba40a2321a5f984998a01360363d5983 to your computer and use it in GitHub Desktop.
Save mhawksey/ba40a2321a5f984998a01360363d5983 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;
}
/**
* 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 || '';
}
@CarlosDuro
Copy link

CarlosDuro commented Mar 20, 2021

@mhawksey how can you add to the code the capability to retrieve media_url? Thank you a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment