As part of the latest release of TAGS (Twitter Archiving Google Sheet) I moved a lot of the code into a Google Apps Script Library. Libraries are a great way to bundle and release code allowing you to write your own classes and methods. To see some of the functionality already being developed by the Apps Script community you should have a look at the Google Apps Script Samples site and the excellent work Bruce McPherson has done which includes a EzyOauth2 library.
One of the things you can do with libraries is wrap one library into another. When rewriting TAGS it made sense to strip out a separate Twitter client library that I and others could use in different projects. Based on the work by Arun Nagarajan at Google, TwtrService provides access to Twitter’s REST API. The work I’ve done is to add some UI and configuration methods to try to streamline the authentication flow. As part of this developers can offer authentication routes using their own Twitter application or use an application created by users. This particular angle is a result of one of the design principles for TAGS, that every copy of the template should use a Twitter application owned by the user. The reason behind this is to distribute the risk. If Twitter were to suspend my data access because a TAGS user abused their API it would suspend access for all TAGS users. By requiring TAGS users to register their own application with Twitter the responsibility to abide by Twitter’s terms of service lies with them. So in TAGS the auth flow looks like this
The result is hopefully a flexible library that developers can integrate into their own projects or by getting users to register their own.
Over the next couple of weeks I’ll be sharing some examples applications we’ve developed at ALT. In the meantime this post serves as a basic introduction to TwtrService and covers:
Contents
Overview of TwtrService
The TwtrService library for Google Apps Script centrally stores your Twitter access details allowing them to accessed from multiple script projects without the need for re-authentication. TwtrService is designed to allow you to directly use the Twitter’s v1.1 REST API GET and POST methods. For example to return Twitter search results for the search ‘Google Apps Script’ you would use:
var data = TwtrService.get('https://api.twitter.com/1.1/search/tweets.json', {q: 'Google Apps Script'});
The url string can also be abbreviated to:
var data = TwtrService.get('search/tweets', {q: 'Google Apps Script'});
Additional options can be passed in the parameters array. For example to return 100 results for the same search you would use:
var data = TwtrService.get('search/tweets', {q: 'Google Apps Script', count: 100});
The project key for this library is MarIlVOhstkJA6QjPgCWAHIq9hSqx7jwh
and the TwtrService methods are documented here.
To use the Twitter REST methods TwtrService first needs authenticated access. TwtrService has some built-in methods to do this detailed below. Once a user has authenticated access the TwtrService library stores these as User Properties. This means when a user has authenticated once with TwtrService using the library in another container-bound or standalone Apps Script immediately gives them access to Twitter API results using the get/post methods. In terms of security User Properties are limited to the effective user of the current script.
Usage
Quick start: Personal access
If you would just like to use TwtrService for your Apps Script projects the easiest way to get started is to register a Twitter application and enter it’s details on this page (if you are interested here is the source code for the interface).
Note: If you are already a user of TAGS you’ll already be able to use TwtrService without the step above.
In your Apps Script project you’d like to use the Twitter API in the Script Editor window use Resources > Libraries and add the service using the project key MarIlVOhstkJA6QjPgCWAHIq9hSqx7jwh
.
In your project you can now use the TwtrService.get()
and TwtrService.post()
methods. The documentation for get() is detailed below (post is the same but uses HTTP POST):
get(string url, Object parameters)
GET wrapper for request to the Twitter REST API. For full documentation of API method endpoints and parameters see https://dev.twitter.com/rest/public. For example to get last 100 tweets containing ‘Google Apps Script’: var data = TwtrService.get(‘search/tweets’, {q: ‘Google Apps Script’, count: 100});
Arguments:
Name | Type | Description |
---|---|---|
url | string |
Twitter REST API resource url. This can be either long form e.g. https://api.twitter.com/1.1/search/tweets.json or abbreviated e.g. search/tweets |
parameters | Object |
additional API parameters as detailed in the Twitter REST API documentation e.g. for search results a search string and count is specified by {q: ‘Google Apps Script’, count: 100}. |
Return Values:
Type | Description |
---|---|
Object |
API response in JSON format. |
upload(string url, Object parameters)
The upload method for adding media to Twitter. For full documentation of media upload see https://dev.twitter.com/rest/reference/post/media/upload.
Arguments:
Name | Type | Description |
---|---|---|
url | string |
Twitter REST API upload url. Currently the required string is ‘media/upload’ |
parameters | Object |
additional API parameters as detailed in the Twitter REST API media upload documentation. Current valid parameters are media and media_data |
Return Values:
Type | Description |
---|---|
Object |
API response in JSON format. |
Example
var picture = DriveApp.getFileById('ID_OF_PICTURE_IN_DRIVE').getBlob(); var picture_data = Utilities.base64Encode(picture.getBytes()); var parameters = { "media" : picture_data }; var res = TwtrService.upload('media/upload', parameters);
Quick start: Personal access in Sheets and Documents
If you would like to replicate the TAGS authentication flow where users enter their Twitter application key/secret TwtrService comes with a number of UI methods. For TAGS the following code is used:
/** * Launches key/secret and auth flow */ function setup() { if (TwtrService.isUserConnectedToTwitter()){ var result = Browser.msgBox("Twitter Authorisation", "You appear to already be connected to Twitter.\\n\\nWould you like to run the setup again?", Browser.Buttons.YES_NO); // Process the user's response. if (result == 'yes') { // User clicked "Yes". TwtrService.showTwitterKeySecret(SpreadsheetApp); } } else { TwtrService.showTwitterKeySecret(SpreadsheetApp); } } /** * Used as part of setup() to process form data */ function processForm(formObject) { TwtrService.setUserKeySecret(formObject); TwtrService.showTwitterLogin(SpreadsheetApp); }
The earlier examples have assumed the user registers their own Twitter application. For scenarios where you would like to have the option for users to have authenticated access using a dedicated Twitter API key/secret it is possible to initialize these values. An example application code can be found here which is also deployed here.
Similar to earlier examples once a user authenticates access with your key/secret as long as these values are also initialized in other script projects the user will have access to the Twitter API via TwtrService.
Instructions for creating a Twitter Application to use with TwtrService
TwtrService requires you to have a registered Twitter application. If you are If you haven’t already done this here are some steps you need to get started:
- Register for an API key with Twitter at https://dev.twitter.com/apps/new (if you’ve already registered for a TAGS sheet you can reuse your existing API Key and Secret).
- Name, description and website can be anything you like
- Important Include the Callback URL https://script.google.com/macros/
- Read the ‘Developer Rules of the Road’ before clicking ‘Create your Twitter application’
On the Twitter site your application should include a ‘Keys and Access Tokens’ tab which includes the Consumer Key (API Key) and Consumer Secret (API Secret) you’ll need.