Create new tweet with Google Script

Viewed 289

(I have read already the solution given in Tweet using Google Script but it doesn't work for me. Please don't delete this question.)

Page https://ctrlq.org/code/19995-google-script-to-twitter shows a way to create a tweet in Google Script. I simply pasted the code offered there and successfully followed this instructions:

  1. Go to apps.twitter.com and create a new app
  2. Generate Access Token and Secret
  3. Include Twitter library key «MKvHYYdYA4G5JJHj7hxIcoh8V4oX7X1M_» in Google Script
  4. Activate «Enable Sign in with Twitter» in «App details» in Twitter
  5. Add the «Callbacks URL» in Twitter using my Google Script Project Key: https://script.google.com/macros/d/ML3pMd5z.../usercallback

Now, when I run the code almost nothing happens, but this error message: ReferenceError: "twit" is not defined. (line 22, file "Code").

function sendTweet(status){

status = status || "I found this snippet on @labnol's ctrlq.org";

var twitterKeys= {
TWITTER_CONSUMER_KEY: "1fZn8cBR...",
TWITTER_CONSUMER_SECRET: "588gJxh...",
TWITTER_ACCESS_TOKEN: "112c5e0...",
TWITTER_ACCESS_SECRET: "DcvV614.",
};

var props = PropertiesService.getScriptProperties();

props.setProperties(twitterKeys);

var service = new Twitter.OAuth(props);

if ( service.hasAccess() ) {

var response = twit.sendTweet(status); // ← THIS IS LINE 21

if (response) {
  Logger.log("Tweet ID " + response.id_str);
} else {
  // Tweet could not be sent
  // Go to View -> Logs to see the error message
    }
  }  
}

Please tell me how to fix this specific code.


Found the answer in https://medium.com/javascript-in-plain-english/i-made-a-twitter-bot-from-nothing-but-a-google-sheet-ef0ba6e1b194 and simply added the missing variable after var service = new Twitter.OAuth(props);:

var twit = new Twitter.OAuth(props);

The final code is like so:

function sendTweet(){
  var status = "Text to be tweeted goes here.";
  var twitterKeys= {
    TWITTER_CONSUMER_KEY: "1fZBR...",
    TWITTER_CONSUMER_SECRET: "Ig...tzpa4E...",
    TWITTER_ACCESS_TOKEN: "1125...90...",
    TWITTER_ACCESS_SECRET: "...22GrDcv...",
    };
  var props = PropertiesService.getScriptProperties();
  props.setProperties(twitterKeys);
  var service = new Twitter.OAuth(props);
  var twit = new Twitter.OAuth(props); // ← THIS WAS THE MISSING VARIABLE
  if ( service.hasAccess() ) {
    var response = twit.sendTweet(status);
      if (response) {
        Logger.log("Tweet ID " + response.id_str);
        } else { }
     }  
  }
0 Answers
Related