When you are travelling or going on a vacation, with limited access to the Internet, you often create an “out of office” reply in your email program to let people know that you won’t be able to respond to them right away. How about doing something similar for people who are trying to reach you through Twitter?
WHAT WILL THE TWITTER AUTO-RESPONDER DO
Unlike your email program, Twitter offers no easy way for you to setup out of office auto-replies but we can easily and quickly add such a feature to our Twitter account(s) with the help of this simple Google Script.
Use this Google Script to setup Out of Office auto-replies in Twitter. The script reads all the Twitter @mentions and sends them a tweet with a custom status message.
/* O U T O F O F F I C E F O R T W I T T E R */ /* - - - - - - - - - - - - - - - - - - - - - */ function start() { // Please enter dates in YYYY-MM-DD HH:MM format var OUTOFOFFICE_START_DATE = "03/11/2013 18:13"; var OUTOFOFFICE_END_DATE = "03/11/2013 19:00"; // This is your Out-Of-Office reply. Keep it less than 120 characters. var OUTOFOFFICE_TEXT = "I am currently out of the office, with limited access to Twitter. Thanks!"; // Get your Twitter keys from dev.twitter.com var CONSUMER_KEY = "AAA"; var CONSUMER_SECRET = "BBB"; // Change this with your Twitter handle var TWITTER_HANDLE = "way2trick"; // DO NOT MODIFY ANYTHING AFTER THIS LINE storeKeys ( CONSUMER_KEY, CONSUMER_SECRET, OUTOFOFFICE_TEXT, TWITTER_HANDLE ); initialize ( OUTOFOFFICE_START_DATE, OUTOFOFFICE_END_DATE ); // Make sure that Twitter oAuth is working doTwitter(); } // Delete exiting Apps Script triggers, if any function removeTriggers() { var triggers = ScriptApp.getScriptTriggers(); for(var i=0; i < triggers.length; i++) { ScriptApp.deleteTrigger(triggers[i]); } clearDatabase(); } function storeKeys(key, secret, text, handle) { ScriptProperties.setProperty("TWITTER_CONSUMER_KEY", key); ScriptProperties.setProperty("TWITTER_CONSUMER_SECRET", secret); ScriptProperties.setProperty("OUTOFOFFICE_TEXT", text); ScriptProperties.setProperty("MAX_TWITTER_ID", 0); ScriptProperties.setProperty("TWITTER_HANDLE", handle); } // Clean and Initialize the ScriptDB database function clearDatabase() { var db = ScriptDb.getMyDb(); while (true) { var result = db.query({}); if (result.getSize() == 0) { break; } while (result.hasNext()) { db.remove(result.next()); } } } // Setup triggers for the START and END dates function initialize(start, end) { var startDate = new Date(start); var endDate = new Date(end); removeTriggers(); ScriptApp.newTrigger("autoReply") .timeBased() .at(startDate) .create(); ScriptApp.newTrigger("removeTriggers") .timeBased() .at(endDate) .create(); } function autoReply() { clearDatabase(); ScriptApp.newTrigger("outOfOffice") .timeBased() .everyMinutes(5) .create(); } function oAuth() { var oauthConfig = UrlFetchApp.addOAuthService("twitter"); oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token"); oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token"); oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize"); oauthConfig.setConsumerKey( ScriptProperties.getProperty("TWITTER_CONSUMER_KEY")); oauthConfig.setConsumerSecret( ScriptProperties.getProperty("TWITTER_CONSUMER_SECRET")); } // This function will poll twitter every 5 minutes for any @mentions function outOfOffice() { oAuth(); var twitter_handle = ScriptProperties.getProperty("TWITTER_HANDLE"); var phrase = "to:" + twitter_handle; var search = "https://api.twitter.com/1.1/search/tweets.json?count=10" + "&include_entities=false&result_type=recent&q=" + encodeString(phrase) + "&since_id=" + ScriptProperties.getProperty("MAX_TWITTER_ID"); var options = { "method": "get", "oAuthServiceName":"twitter", "oAuthUseToken":"always" }; try { var result = UrlFetchApp.fetch(search, options); if (result.getResponseCode() === 200) { var data = Utilities.jsonParse(result.getContentText()); if (data) { var tweets = data.statuses; if (tweets.length) { var db = ScriptDb.getMyDb(); var reply = ScriptProperties.getProperty("OUTOFOFFICE_TEXT"); for (var i=tweets.length-1; i>=0; i--) { var sender = tweets[i].user.screen_name; var found = db.query({user: sender}); if ( ! found.hasNext() ) { db.save({user:sender}); sendTweet(sender, tweets[i].id_str, reply); } } } } } } catch (e) { Logger.log(e.toString()); } } // If an @mention is found, send an Out of Office tweet to that user. function sendTweet(user, reply_id, tweet) { var options = { "method": "POST", "oAuthServiceName":"twitter", "oAuthUseToken":"always" }; var text = "@" + user + " " + tweet; text = encodeString(text.substr(0, 140)); var status = "https://api.twitter.com/1.1/statuses/update.json" + "?status=" + text + "&in_reply_to_status_id=" + reply_id; try { var result = UrlFetchApp.fetch(status, options); ScriptProperties.setProperty("MAX_TWITTER_ID", reply_id); } catch (e) { Logger.log(e.toString()); } } function doTwitter() { oAuth(); var req = "https://api.twitter.com/1.1/application/rate_limit_status.json"; var options = { "method": "get", "oAuthServiceName":"twitter", "oAuthUseToken":"always" }; try { var result = UrlFetchApp.fetch(req, options); } catch (e) { Logger.log(e.toString()); } } function encodeString (q) { var str = encodeURIComponent(q); str = str.replace(/!/g,'%21'); str = str.replace(/\*/g,'%2A'); str = str.replace(/\(/g,'%28'); str = str.replace(/\)/g,'%29'); str = str.replace(/'/g,'%27'); return str; }
You specify the start date and the end date when the auto-responder should be active and any tweets sent to you during this period will automatically get a reply from your Twitter account saying you are out of office (the auto-reply text can be configured). The replies are sent only once so if a person sends you two or more tweets during your vacation period, they will get only one out-of-office auto-reply.
HOW TO SETUP OUT OF OFFICE REPLIES IN TWITTER
STEP A: SETUP A TWITTER APP
1. Go to apps.twitter.com and sign-in with your existing Twitter account. Create a new Twitter app , add a description, website (any URL) and put https://spreadsheets.google.com/macros/ in the callback URL field.
2. Once the Twitter app has been created, click the Permissions tab and set Read and Write as the Application Type. Click Update Settings to save your changes.
3. Switch to the API Keys tab and make note of the Consumer API Key and API Secret.
STEP B: SETUP THE AUTO-RESPONDER SCRIPT
1. Make a copy of this auto-responder script into your Google Drive.
/* O U T O F O F F I C E F O R T W I T T E R */
/* - - - - - - - - - - - - - - - - - - - - - */
function start() {
// Please enter dates in YYYY-MM-DD HH:MM format
var OUTOFOFFICE_START_DATE = "2014/08/20 18:00";
var OUTOFOFFICE_END_DATE = "2014/08/24 09:00";
// This is your Out-Of-Office reply. Keep it less than 120 characters.
var OUTOFOFFICE_TEXT = "I am currently out of the office, with limited access to Twitter. Thanks!";
// Get your Twitter keys from dev.twitter.com
var CONSUMER_KEY = "YOUR_KEY_HERE";
var CONSUMER_SECRET = "YOUR_SECRET_HERE";
var TWITTER_HANDLE = "YOUR_HANDLE_HERE";
// Ignore everything after this line
storeKeys( CONSUMER_KEY, CONSUMER_SECRET, OUTOFOFFICE_TEXT, TWITTER_HANDLE );
initialize( OUTOFOFFICE_START_DATE, OUTOFOFFICE_END_DATE );
// Make sure that Twitter oAuth is working
doTwitter();
}
function removeTriggers() {
var triggers = ScriptApp.getScriptTriggers();
for(var i=0; i < triggers.length; i++) {
ScriptApp.deleteTrigger(triggers[i]);
}
}
function storeKeys(key, secret, text, handle) {
var props = PropertiesService.getScriptProperties();
props.setProperty("TWITTER_CONSUMER_KEY", key);
props.setProperty("TWITTER_CONSUMER_SECRET", secret);
props.setProperty("OUTOFOFFICE_TEXT", text);
props.setProperty("MAX_TWITTER_ID", 0);
props.setProperty("TWITTER_HANDLE", handle);
}
// Setup triggers for the START and END dates
function initialize(start, end) {
var startDate = new Date(start);
var endDate = new Date(end);
removeTriggers();
ScriptApp.newTrigger("autoReply")
.timeBased()
.at(startDate)
.create();
ScriptApp.newTrigger("removeTriggers")
.timeBased()
.at(endDate)
.create();
}
function autoReply() {
ScriptApp.newTrigger("outOfOffice")
.timeBased()
.everyMinutes(5)
.create();
}
function oAuth() {
var props = PropertiesService.getScriptProperties();
var oauthConfig = UrlFetchApp.addOAuthService("way2trick");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(props.getProperty("TWITTER_CONSUMER_KEY"));
oauthConfig.setConsumerSecret(props.getProperty("TWITTER_CONSUMER_SECRET"));
}
// This function will poll twitter every 5 minutes for any @mentions
function outOfOffice() {
oAuth();
var props = PropertiesService.getScriptProperties();
var twitter_handle = props.getProperty("TWITTER_HANDLE");
var phrase = "to:" + twitter_handle;
var search = "https://api.twitter.com/1.1/search/tweets.json?count=10"
+ "&include_entities=false&result_type=recent&q="
+ encodeString(phrase) + "&since_id="
+ props.getProperty("MAX_TWITTER_ID");
var options =
{
"method": "get",
"oAuthServiceName":"way2trick",
"oAuthUseToken":"always"
};
var key = "Twitter" + Utilities.formatDate(new Date(), "UTC", 'yw');
try {
var result = UrlFetchApp.fetch(search, options);
if (result.getResponseCode() === 200) {
var data = Utilities.jsonParse(result.getContentText());
if (data) {
var tweets = data.statuses;
if (tweets.length) {
var db = props.getProperty(key) || "";
var reply = props.getProperty("OUTOFOFFICE_TEXT");
for (var i=tweets.length-1; i>=0; i--) {
var sender = "#" + tweets[i].user.screen_name + "#";
if (db.indexOf(sender) == -1) {
props.setProperty(key, db + sender)
sendTweet(tweets[i].user.screen_name, tweets[i].id_str, reply, props);
}
}
}
}
}
} catch (e) {
Logger.log(e.toString());
}
}
// If an @mention is found, send an Out of Office tweet to that user.
function sendTweet(user, reply_id, tweet, props) {
var options =
{
"method": "POST",
"oAuthServiceName":"way2trick",
"oAuthUseToken":"always"
};
var text = encodeString("@" + user + " " + tweet).substr(0, 140);
var status = "https://api.twitter.com/1.1/statuses/update.json"
+ "?status=" + text + "&in_reply_to_status_id=" + reply_id;
try {
var result = UrlFetchApp.fetch(status, options);
props.setProperty("MAX_TWITTER_ID", reply_id);
}
catch (e) {
Logger.log(e.toString());
}
}
function doTwitter() {
try {
var req = "https://api.twitter.com/1.1/application/rate_limit_status.json?resources=search";
var options =
{
"method": "get",
"oAuthServiceName":"way2trick",
"oAuthUseToken":"always"
};
oAuth();
var result = UrlFetchApp.fetch(req, options);
} catch (e) {
throw(e.toString());
}
}
function encodeString (q) {
q = q.replace(/\!|\*|\(|\)|\'/g, '');
return encodeURIComponent(q);
//str = str.replace(/!/g,'%21');
//str = str.replace(/\*/g,'%2A');
//str = str.replace(/\(/g,'%28');
//str = str.replace(/\)/g,'%29');
//str = str.replace(/'/g,'%27');
//return str;
}
2. Enter the start and end dates of your vacation, the Twitter API keys (from the previous step), and your Twitter handle.
3. Go to Run -> Start to initialize the auto-responder. Say Yes if the script requires you to authorize access to certain Google Script services.
4. Choose Run -> Start again and authorize the script to post tweets from your Twitter account.
The script will invoke itself on the specified start date and will respond to all incoming tweets until the end date. It will then stop itself automatically. As always, you are free to use, modify and distribute the source code with attribution.
When you are taking another vacation, just open the auto-responder script already present in your Google Drive, change the Start and End dates and choose Start from the Run menu to initialize the autoresponder again.
0 comments:
Post a Comment