2 Replies - 268 Views - Last Post: 26 July 2014 - 11:48 AM

#1 youbob1212  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 16
  • View blog
  • Posts: 132
  • Joined: 31-October 10

Using google script just to send out a tweet?

Posted 25 July 2014 - 11:03 PM

Sorry I didn't know where I could post this thread..

But all I really want to know is how can I use Google script to send out a Tweet! Just that function, and I think I can figure out the time factor. I don't understand the code just yet There are plenty of projects using GS for retweets, that involves using yahoo pipes, but only one site has the answer that I want, however, I only seen it execute correctly once, and for some reason it wont run on auto pilot, or even repeat the same results. Maybe I'm doing something wrong?


Main.gs
function startBot() {
  //Connects to the API to access Twitter features
  var bot = new Twitterbot();
  bot.consumerKey = "CAN'T SHOW YOU MY API KEYS";
  bot.consumerSecret = "BUT THEY ARE CORRECTLY PLACE IN";
  bot.makeTweet = makeTweet;
  return bot;
}

function schedule(){
  //Creates a tweet and sends it to the twitter account
  //This is the function that should have a time trigger to post regularly
  var bot = startBot();
  var result = bot.sendTweet();
  result = JSON.parse(result);
  Logger.log(result);          //The entire JSON object of the sent tweet
  Logger.log(result["text"]);  //Just the text content of the sent tweet. "None" if the tweet failed.
}

function makeTweet(bot){
  //Returns the URI-encoded text of the tweet that will be sent.
  //You should have it return empty string "" if it fails.
  var tweet = "";
  
  //-------------Your code here---------------------------------------------
  tweet = "Get Some New #bitcoin hourly here:http://freebitco.in/?r=222176  Get Some #dogecoin hourly here:http://freedoge.co.in/?r=21851";
  //------------------------------------------------------------------------
  
  
  /*
  Twitter will throw an error if tweet is longer than 140 characters, so
  there should always be a failsafe to return an empty string instead if
  you can't reduce character count. The empty string will be caught by sendTweet()
  */
  if (tweet.length>140){
    tweet = "";
  }
  
  Logger.log(tweet);
  tweet = encodeString(tweet); //URI-encodes tweet for HTTP post request
  return tweet;
}


twitterbot.gs
function Twitterbot(){
  this.consumerKey = "";
  this.consumerSecret = "";
  this.makeTweet; //function that creates tweet to send
  this.sendTweet = sendTweet;
  this.authorizeTwitter = authorizeTwitter;
  this.requestDataPOST = {
    "method": "POST",
    "oAuthServiceName": "twitter",
    "oAuthUseToken": "always"
  };
  this.requestDataGET = {
    "method": "GET",
    "oAuthServiceName": "twitter",
    "oAuthUseToken": "always"
  };
  
  function authorizeTwitter() {
    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(this.consumerKey);
    oauthConfig.setConsumerSecret(this.consumerSecret);
  }
  
  function updateStatus(tweet, responseID){
    //tweet should be URI encoded
    var baseURL  = "https://api.twitter.com/1.1/statuses/update.json?status="+tweet;
    if (responseID!=null){
      baseURL+="&in_reply_to_status_id="+responseID;
    }
    
    try {
      this.authorizeTwitter();
      if (tweet.length==0){
        return '{"text":"none"}';
      }
      var result = UrlFetchApp.fetch(tweet, this.requestDataPOST);   
      Utilities.sleep(1000);
      return result;
    } 
    catch(e) {
      return '{"text":"'+e.toString()+'"}';
    }
  }
  
  function deleteTweet(tweetID){
    //returns destroyed status if successful
    var baseURL  = "https://api.twitter.com/1.1/statuses/destroy/"+tweetID+".json";
    try {
      this.authorizeTwitter();
      if (tweet.length==0){
        return '{"text":"none"}';
      }
      var result = UrlFetchApp.fetch(baseURL, this.requestDataPOST);   
      Utilities.sleep(1000);
      return result;
    } 
    catch(e) {
      return '{"text":"'+e.toString()+'"}';
    }
  }
  
  function retweet(tweetID){
    //returns original tweet if successful
    var baseURL  = "https://api.twitter.com/1.1/statuses/retweet/"+tweetID+".json";
    try {
      this.authorizeTwitter();
      var result = UrlFetchApp.fetch(baseURL, this.requestDataPOST);   
      Utilities.sleep(1000);
      return result;
    } 
    catch(e) {
      return '{"text":"'+e.toString()+'"}';
    }
  }
  
  function search(query, count){
    //simple search for now
    //query should be URI encoded
    //returns latest tweets as a set
    var baseURL = "https://api.twitter.com/1.1/search/tweets.json?q="+query+"&count="+(count==null?15:100); //15 is default, 100 max.
    try {
      this.authorizeTwitter();
      var result = UrlFetchApp.fetch(baseURL, this.requestDataGET);   
      Utilities.sleep(1000);
      return result;
    } 
    catch(e) {
      return '{"text":"'+e.toString()+'"}';
    }
  } 
  

  function sendTweet(tweetToSend) {
    var tweet    = (tweetToSend != null) ? tweetToSend : this.makeTweet(this);
    var baseURL  = "https://api.twitter.com/1.1/statuses/update.json?status=";
    
    try {
      this.authorizeTwitter();
      if (tweet.length==0){
        return '{"text":"none"}';
      }
      tweet = baseURL+tweet;
      var result = UrlFetchApp.fetch(tweet, this.requestDataPOST);   
      Utilities.sleep(1000);
      return result;
    } 
    catch(e) {
      return '{"text":"'+e.toString()+'"}';
    }
  }
}

function getAndSendReplies() {
  var bot = startBot();
  bot.authorizeTwitter();
  var replies = [];
  
  var username = "USERNAME" //The Twitter handle of the account to get 
  var search = "https://api.twitter.com/1.1/search/tweets.json?count=100&include_entities=false&result_type=recent&q="; 
  search = search + encodeString("to:"+username) + "&since_id=" + ScriptProperties.getProperty("MAX_TWEET_ID");    
  
  try {
    var result = UrlFetchApp.fetch(search, bot.requestDataGET);   
    Logger.log(result);

    if (result.getResponseCode() === 200) {
      var data = JSON.parse(result);
      if (data) {
        var tweets = data.statuses;
        for (var i=tweets.length-1; i>=0; i--) {
          Logger.log(tweets[i]["text"]);
          var answer = makeResponse(tweets[i]);
          sendTweet(answer);
          replies.push(answer);
          ScriptProperties.setProperty("MAX_TWEET_ID", tweets[i]["id_str"]);
          Utilities.sleep(1000);
        }
      }
    }
  } catch (e) {
    return "{ 'text': '"+e.toString()+"'}";
  }
  return "{ 'text': '"+replies.join("\n").toString()+"'}";
}

function makeResponse(tweet){
  //tweet is a tweet object from the twitter api
  //function returns URI encoded response tweet, Should return null string "" if fails.
  //Reply data is appended at end of tweet, e.g.:
  //return encodeString(response)+"&in_reply_to_status_id="+replyID;
  
  var text = tweet["text"];
  var username = tweet["screen_name"];
  var replyID = tweet["id_str"];
  var response = "@"+username+" "; //repsonse starts out as @username in reponse to tweet
  
  //Add onto the response here
  
  return encodeString(response)+"&in_reply_to_status_id="+replyID;
}

function randomNumber(max){
  return Math.floor(Math.random()*max);
}

function randomChoice(set){
  return set[randomNumber(set.length)];
}

//Encodes string as URI, replacing problematic characters
function encodeString (q) {
  var str = q;
  str = str.replace(/!/g,'‼');
  str = str.replace(/\*/g,'');
  str = str.replace(/\(/g,'[');
  str = str.replace(/\)/g,']');
  str = str.replace(/'/g,'ʼ');
  str = str.replace(/&/g, "&");
  str = str.replace(/&lt;/g, "<");
  str = str.replace(/&gt;/g, ">");
  var str =  encodeURIComponent(str);
  return str;
}




Here is the thing. I have searched hard on google. Trying to look for something that allows you to send a tweet on GS, but nothing that I can use or understand at the moment, and anything thing that does work is off the topic, you must pay for, or download some computer virus.

I know the answer is out that but any can only at least point me in the right direction?

Is This A Good Question/Topic? 0
  • +

Replies To: Using google script just to send out a tweet?

#2 youbob1212  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 16
  • View blog
  • Posts: 132
  • Joined: 31-October 10

Re: Using google script just to send out a tweet?

Posted 26 July 2014 - 09:18 AM

Ok I found out what Might be causing the problem. On the
function schedule(){
  //Creates a tweet and sends it to the twitter account
  //This is the function that should have a time trigger to post regularly
  
  var bot = startBot();
  var result = bot.sendTweet();
   result = JSON.parse(result);
  Logger.log(result);          //The entire JSON object of the sent tweet
  Logger.log(result[""]);  //Just the text content of the sent tweet. "None" if the tweet failed.
  
}


I get this error when I try to run it.
SyntaxError: Unexpected token in object literal (line 16, file "Mine")
Dismiss
It's with this line of code
result = JSON.parse(result);


I think something needs to be reset every single time the program is executed. But I still don't know how to fix this problem
Was This Post Helpful? 0
  • +
  • -

#3 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,614
  • Joined: 23-August 08

Re: Using google script just to send out a tweet?

Posted 26 July 2014 - 11:48 AM

var result = bot.sendTweet();
try {
    var parsedResult = JSON.parse(result);
    Logger.log(parsedResult);
} catch (ex) {
    Logger.log(ex + ' - Invalid result returned: ' + result);
}

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1