Sponsored by

  • Intel
  • HP

JavaScriptTutorial

Create a data driven Twitter avatar

Matthew Knight explains why you don’t need to be a genius to make simple digital toys – just build upon the genius of others and make use of Google Apps Script

First of all, a disclaimer: I’m not a coder, just someone who uses code to make things.

Fortunately, for people like me, and those who want to plug together various chunks of the internet, there are an increasing number of platforms and APIs that interoperate, making many projects a case of understanding what platforms can do, and then connecting the blue wire and green wire (but never the red wire!).

One of these platforms is Google Apps Script, a cloud-based scripting language that exposes an API to many of Google’s apps, for example Spreadsheets, Maps, Mail and Calendar. If you use Google Apps, such as Gmail or Google Docs, you now have access via these APIs to your data. It uses simple JavaScript-like syntax, so if you’ve done a bit of frontend scripting before, you’ll find your way around Google Apps Script in no time.

These sorts of tools make it really simple, quick and easy to demonstrate an idea, often with very little code. Here’s an example of a recent toy I built, a data driven Twitter avatar.

Advertisement

What I built

If you have a look at my Twitter account, you’ll see my avatar is a coloured block with a number. That’s the approximate number of emails in my inbox, and it updates every 30 minutes. It took me about 30 minutes to hack together because of the simplicity of Google Apps Script.

The idea

A few years ago, I read Everyware by Adam Greenfield, a wonderful introduction to the concepts of ubiquitous computing. It suggested a world where the art hung on our walls would offer more than a pretty picture to view, but also embedded ambient information. Perhaps the picture displayed a calm sea when the weather was nice, or rough choppy waters and a storm when your credit card was in arrears. Much more subtle than a blinking icon or pinging alarm.

Not an uncommon sight in my inbox
Not an uncommon sight in my inbox

Several years later, I had a free morning to make something similar. Generally, the number of emails in my inbox is a good measure of how many things I’ve got going on. If I’m busy, I reply slowly and the emails build up. What if I could connect the number of emails in my inbox to my Twitter account, replacing the avatar with a ‘Red/Amber/Green’ or ‘Calm/Busy/Overloaded’ image?

Accessing your inbox

First, let’s open up a new Google Apps Script.

You can either visit script.google.com

or

visit drive.google.com and Create > More > Script

Click on ‘Create Blank Project’ and you’ll immediately be presented with a code editor, with an empty method called myFunction():

function myFunction() {  }

This is where we drop our code to access and control Google Apps.

There is excellent documentation to the APIs, which Google exposes for its platforms at developers.google.com/apps-script. For this, we’re mostly interested in the Gmail APIs – which are at developers.google.com/apps-script/class_gmailapp.

As you can see from the list of methods, you’re able to do dozens of tasks, such as getting a list of all of your spam (handy), searching Gmail (very handy), getting particular conversations (super handy) and retrieving a list of all of the conversations in your inbox (for this task, perfect!).

function myFunction() {       // retrieve the threads (conversations) from my inbox       var threads = GmailApp.getInboxThreads();}

You can now hit Run, and see what your script does. If this is your first time using Google Scripts, you’ll be asked for a series of authorisations, mostly to allow Google Scripts to access your inbox, and so on. You’ll reach a page which says something like ‘Your script is now authorised to run’, which you can close down, and hit Run again.

Et voila. Nothing.

OK – this doesn’t do much more than access your inbox and retrieve a list of your emails. Normally, if using JavaScript, you could have a look at the output by using alert() or writing the response to the HTML page or a text area, but as this script is running in the cloud, there is no visual interface to view its output, so we need to use the Logger class.

function myFunction() {     // retrieve the threads (conversations) from my inbox     var threads = GmailApp.getInboxThreads();     Logger.log(threads);}

Run this script, and once it has executed, click on the View menu, and select ‘Logs’ (or hit Ctrl+Enter). Assuming you have email in your inbox, you’ll see something like:

[GmailThread, GmailThread]

This is an array of your emails. You could go ahead and access specific properties of the conversations here, but I’m only interested in the amount of conversations.

Modifying the code enables us to just deal with the count, rather than the threads themselves.

function myFunction() {     // retrieve the thread (conversations) count from my inbox     var inboxcount = GmailApp.getInboxThreads().length;     Logger.log(inboxcount);}

Super simple.

Modifying your avatar

Next up, I want to call a PHP script I’ve written, which takes that data and uploads a suitable image for the number of emails in my inbox.

Google Apps Script enables us to call a remote URL using the URLFetchApp:

function myFunction() {     // retrieve the thread (conversations) count from my inbox     var inboxcount = GmailApp.getInboxThreads().length;     // send inbox size to remote script     UrlFetchApp.fetch( "http://yourserver.com/updateavatar/script.php?count=" + inboxcount );}

This single line makes a call over HTTP to my remote script, along with the inbox count as a query string variable. The PHP script then uses the excellent twitter-async library by @jmathai to connect to the Twitter REST API to push a replace my avatar with a selected image:

Some of the sprites used in the script
Some of the sprites used in the script
<?php // uses <a href="https://github.com/jmathai/twitter-asyncinclude" title="https://github.com/jmathai/twitter-asyncinclude">https://github.com/jmathai/twitter-asyncinclude</a> 'EpiCurl.php'; include 'EpiOAuth.php'; include 'EpiTwitter.php';  // Calculate which image to show, based upon the inbox count. &#36;inboxcount=0; if ( isset( &#36;_GET['count'] ) ) &#36;inboxcount = (int)&#36;_GET['count']; if ( &#36;inboxcount < 10 ) {  &#36;imagename = 'n' . &#36;inboxcount; } else {  &#36;imagename = ceil( &#36;inboxcount/10 );  if (&#36;imagename > 5 ) &#36; imagename = 5; }&#36;filename = dirname( __FILE__ ) . '/' . &#36;imagename . '.png'; // push the image to twitter // you&rsquo;ll need to get your various twitter API keys from <a href="https://dev.twitter.com/apps/new" title="https://dev.twitter.com/apps/new">https://dev.twitter.com/apps/new</a> &#36;twitterObj = new EpiTwitter( &#36;consumer_key, &#36;consumer_secret, &#36;token, &#36;secret ); &#36;twitterObj->post( '/account/update_profile_image.json', array( '@image' => "@&#36;filename" ) ); // yes, it is really THAT easy?>Updating the avatar every hour           

Finally, we need to make the script run every hour, to keep the avatar updated. Google Apps Script, again, comes to the rescue.

Under the Resources menu, you’re able to access a list of Triggers. Events and Triggers allow you to run scripts upon external influences, like time passing or files being opened or edited. We want to write a trigger which executes the script every hour.

Clicking on 'Add New Trigger' provides some simple drop-down options, where we select the function we want to run (myFunction), the event we want to hook into (Time-driven), which event we’re interested in (Hour Timer), and then the data itself (Every hour). This is effectively a cronjob.

Now, we can hit 'Save', walk away, and every hour, the remote URL will be called.

Of course, we’re not limited to just updating an avatar, or indeed basing it upon inbox size, the Google Apps Script API is substantial, it allows you to create documents, connect many of the Google services together, and generally automate your Google apps.

I decided to call a remote URL to allow my own server to do the heavy lifting (ie uploading images, handling the OAuth, etc), but in fact Google Apps could connect directly to the Twitter API using OAuth and HTTP calls, meaning I could run a script entirely on Google’s infrastructure without needing any hosting.

Being able to demonstrate an idea using just a handful of lines of really simple code goes a long way, so maybe that painting of a stormy sea is not so far off.

Log in to Creative Bloq with your preferred social network to comment

OR

Log in with your Creative Bloq account

site stat collection