Skip to content

Instantly share code, notes, and snippets.

@xl1
Created May 9, 2012 00:28
Show Gist options
  • Save xl1/2640706 to your computer and use it in GitHub Desktop.
Save xl1/2640706 to your computer and use it in GitHub Desktop.
@rousaibot on Google Spreadsheet
/*
copied from https://sites.google.com/site/usakoyama/gastotwitterbot
*/
function tweetInitialize() {
// Setup OAuthServiceConfig
var oAuthConfig = UrlFetchApp.addOAuthService("twitter");
oAuthConfig.setAccessTokenUrl("http://api.twitter.com/oauth/access_token");
oAuthConfig.setRequestTokenUrl("http://api.twitter.com/oauth/request_token");
oAuthConfig.setAuthorizationUrl("http://api.twitter.com/oauth/authorize");
oAuthConfig.setConsumerKey(ScriptProperties.getProperty("twitterConsumerKey"));
oAuthConfig.setConsumerSecret(ScriptProperties.getProperty("twitterConsumerSecret"));
}
function twitterPost(text) {
// Setup optional parameters to point request at OAuthConfigService. The "twitter"
// value matches the argument to "addOAuthService" above.
var options =
{
"oAuthServiceName" : "twitter",
"oAuthUseToken" : "always",
"method" : "POST"
};
var encodedTweet = encodeURIComponent(text);
var result = UrlFetchApp.fetch("http://api.twitter.com/1/statuses/update.json?status=" + encodedTweet, options);
var o = Utilities.jsonParse(result.getContentText());
Logger.log(o);
Logger.log(result.getResponseCode());
}
function randint(m){
return Math.random() * m |0;
}
function heightOf(range){
var len = range.getHeight(),
values = range.getValues();
for(var i = 0; i < len; i++){
if(!values[i][0]) return i;
}
return len;
}
function splitText(text){
if(text.length < 140) return [text];
var top = text.substr(0, 140),
lastPeriodIdx = top.lastIndexOf('。') + 1,
first, rest;
if(lastPeriodIdx){
first = text.substr(0, lastPeriodIdx);
rest = text.substr(lastPeriodIdx);
} else {
first = text.substr(0, 139) + '…';
rest = '…' + text.substr(139);
}
return [first].concat(splitText(rest));
}
function getRousaiText(){
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets(),
sheet = sheets[randint(sheets.length)],
range = sheet.getRange('D3:D'),
size = heightOf(range),
value = range.getValues()[randint(size)][0];
Logger.log(value);
return value;
}
function main(){
tweetInitialize();
splitText(getRousaiText()).forEach(twitterPost);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment