Post a tweet to my feed using Google Apps Script

萝らか妹 提交于 2019-12-04 14:53:14

Eureka! Here's the solution. The irony is that I had had something like this before, but had dismissed it. Turns out https was my biggest problem. I'll feast on humble pie tonight.

script to send tweet

//post tweet
function oAuth() {
  var CONSUMER_KEY = "*************************";
  var CONSUMER_SECRET = "**************************************************";
  ScriptProperties.setProperty("TWITTER_CONSUMER_KEY", CONSUMER_KEY);
  ScriptProperties.setProperty("TWITTER_CONSUMER_SECRET", CONSUMER_SECRET);
  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/authenticate");
  oauthConfig.setConsumerKey(ScriptProperties.getProperty("TWITTER_CONSUMER_KEY"));
  oauthConfig.setConsumerSecret(ScriptProperties.getProperty("TWITTER_CONSUMER_SECRET"));
  var options = {muteHttpExceptions: true,oAuthServiceName:'twitter',oAuthUseToken:'always'}
  var url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
  var response = UrlFetchApp.fetch(url, options).getContentText();
  Logger.log(response);
}
function postTweet() {
  oAuth();
  Logger.log('oAuth complete');
  var status='Test tweet';
  var options = {
    "method": "post",
    "oAuthServiceName": "twitter",
    "oAuthUseToken": "always",
    "payload":{"status":status}
  };
  var url = "https://api.twitter.com/1.1/statuses/update.json";
  Logger.log('begin post');
  var request = UrlFetchApp.fetch(url, options);
  Logger.log('post complete');
}

When you register your Twitter app, you have to check the option Allow this application to be used to Sign in with Twitter. This prevents continual Authorize popups. Also, the tweet text CANNOT contain single quotes (').

@J148, oauthConfig depricated and you can't use it anymore;

Now for twitter you have to use OAuth1 for Apps Script. Migration docs: https://developers.google.com/apps-script/migration/oauth-config?utm_campaign=oauth-appsscript-315&utm_source=gadbc&utm_medium=blog

Sample: https://github.com/googlesamples/apps-script-oauth1/blob/master/samples/Twitter.gs

To make sample working you have to:

  • Add "OAuth1 for Apps Script library" to your script project
  • Declare some stub "Callback URL" in the twitter app's settings
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!