Post an Update to Twitter with Google Apps Script

You can use Google Apps Script to post status updates (tweets) to Twitter.

This example generates an OAuth 1.0a HMAC-SHA1 signature that is converted to base64 and is passed to the Twitter API via an HTTP POST request. You can use it to send tweets from Google Addons, Google Sheets and standalone web apps.

/*
 * Post to Twitter from Google Apps Script
 * Code by @rcknr
 */

function postTweet(message) {
  var method = 'POST';
  var baseUrl = 'https://api.twitter.com/1.1/statuses/update.json';
  var props = PropertiesService.getScriptProperties();

  var oauthParameters = {
    oauth_consumer_key: props.getProperty('CONSUMER_KEY'),
    oauth_token: props.getProperty('ACCESS_TOKEN'),
    oauth_timestamp: Math.floor(new Date().getTime() / 1000).toString(),
    oauth_signature_method: 'HMAC-SHA1',
    oauth_version: '1.0',
  };

  oauthParameters.oauth_nonce = oauthParameters.oauth_timestamp + Math.floor(Math.random() * 100000000);

  var payload = {
    status: message,
  };

  var queryKeys = Object.keys(oauthParameters).concat(Object.keys(payload)).sort();

  var baseString = queryKeys.reduce(function (acc, key, idx) {
    if (idx) acc += encodeURIComponent('&');
    if (oauthParameters.hasOwnProperty(key)) acc += encode(key + '=' + oauthParameters[key]);
    else if (payload.hasOwnProperty(key)) acc += encode(key + '=' + encode(payload[key]));
    return acc;
  }, method.toUpperCase() + '&' + encode(baseUrl) + '&');

  oauthParameters.oauth_signature = Utilities.base64Encode(
    Utilities.computeHmacSignature(
      Utilities.MacAlgorithm.HMAC_SHA_1,
      baseString,
      props.getProperty('CONSUMER_SECRET') + '&' + props.getProperty('ACCESS_SECRET')
    )
  );

  var options = {
    method: method,
    headers: {
      authorization:
        'OAuth ' +
        Object.keys(oauthParameters)
          .sort()
          .reduce(function (acc, key) {
            acc.push(key + '="' + encode(oauthParameters[key]) + '"');
            return acc;
          }, [])
          .join(', '),
    },
    payload: Object.keys(payload)
      .reduce(function (acc, key) {
        acc.push(key + '=' + encode(payload[key]));
        return acc;
      }, [])
      .join('&'),
    muteHttpExceptions: true,
  };

  var response = UrlFetchApp.fetch(baseUrl, options);
  var responseHeader = response.getHeaders();
  var responseText = response.getContentText();
  Logger.log(responseText);
}

function encode(string) {
  return encodeURIComponent(string)
    .replace('!', '%21')
    .replace('*', '%2A')
    .replace('(', '%28')
    .replace(')', '%29')
    .replace("'", '%27');
}

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻