Giter VIP home page Giter VIP logo

Comments (4)

erickoledadevrel avatar erickoledadevrel commented on May 31, 2024

It should happen automatically, since the library stores credentials in the property store that you set. Just use the same getService() function in both cases to ensure the settings are the same.

from apps-script-oauth1.

YiuriV avatar YiuriV commented on May 31, 2024

I think I've not explained myself well enough. I'll put some code down below to illustrate. First up I have the functions to authorize (function AUTHORIZE() being the one that's called initially)

function AUTHORIZE() {
var service = oAuth();
if (service.hasAccess()){
try {
var result = service.fetch(
"https://api.twitter.com/1.1/statuses/mentions_timeline.json");
authservice=service;
spreadsheet.toast("App authorized successfully! You can start entering your Tweets in sheet now and select Tweet Scheduler-> Schedule Tweets Now", "Authorized", 10);
} catch (e) {
Logger.log("Make sure you entered proper Twitter CONSUMER KEY and SECRET");
Browser.msgBox("OAuth Error!", "Make sure you entered correct Twitter CONSUMER KEY and SECRET", Browser.Buttons.OK);
}
}
else {
var authorizationUrl = service.authorize();
Browser.msgBox("authorize", "Click "+authorizationUrl+" to authorize", Browser.Buttons.OK);
}
}

function oAuth() {
var oauthConfig = OAuth1.createService('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("MyRB2iMo4xOpFRH5R3mzdIBZX");
oauthConfig.setConsumerSecret("Iku0rtIbCdEmChe73niYOVQIy2BKN1g7HCH44ki110q5CvWhRN");
oauthConfig.setProjectKey("MTiqXM6kcMZT7DXQB8n7NiwRXe9kjsIBw");
oauthConfig.setCallbackFunction('authCallback');
oauthConfig.setPropertyStore(PropertiesService.getScriptProperties());
return oauthConfig;
}
function authCallback(request) {
var service = oAuth();
var isAuthorized = service.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this page.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this page');
}
}

next the function that schedules my tweets:
function scheduleTweets() {
scriptProperties.setProperty('isInitialized', 'true');
var start = getFirstRow() + 1;
var end = SpreadsheetApp.getActiveSheet().getLastRow();
deleteoldtriggers();
PropertiesService.getScriptProperties().deleteAllProperties();
for (i = start; i <= end; i++) {
if (i < 20) {
var to = sheet.getRange(i, 1).getValue();
var message = sheet.getRange(i, 2).getValue();
var message = message.substr(0, 140);
var imgurl = sheet.getRange(i, 3).getValue();
if (sheet.getRange(i, 4).getValue()) {
var time = sheet.getRange(i, 4).getValue();
var time = new Date(time);
Logger.log(to + ":" + message + time);
var time = formatTime(time);
if (time) {
savetodb(to, message, imgurl, time);
ScriptApp.newTrigger("checkschedule").timeBased().at(new Date(time)).create();

            } else {
                Logger.log("Empty/Invalid Entry");
            }
        }
    }
}
spreadsheet.toast("All your Tweets have been scheduled and will automatically be posted on your Profile at appropriate time", "Success: Tweets Scheduled", 5);

}

The checkschedule function will gather the data and finally call out the function sendouttweets:
function sendouttweets(to, tweet, imgurl) {
Logger.log("send tweet" + to + tweet + "called");
var user = to;
var tweet = tweet;
var scriptProperties = PropertiesService.getScriptProperties();
var service = "get the auth";

var options = {
    "method": "POST",
    "oAuthServiceName": "twitter",
    "oAuthUseToken": "always"
};

var status = "https://api.twitter.com/1.1/statuses/update.json";

var imgurlenc = encodeURIComponent(imgurl);

var imageurl = UrlFetchApp.fetch(imgurl);
//var imgdata = imageurl.getContent();
var imgdatablob = imageurl.getBlob().setContentTypeFromExtension();
var boundary = Math.random().toString().substr(2);

var requestBody = Utilities.newBlob(
"--"+boundary+"\r\n"
+ "Content-Disposition: form-data; name="status"\r\n\r\n"
+ status+"\r\n"+"--"+boundary+"\r\n"
+ "Content-Disposition: form-data; name="media[]"; filename=""+imgdatablob.getName()+""\r\n"
+ "Content-Type: " + imgdatablob.getContentType()+"\r\n\r\n").getBytes();

requestBody = requestBody.concat(imgdatablob.getBytes());
requestBody = requestBody.concat(Utilities.newBlob("\r\n--"+boundary+"--\r\n").getBytes());

var optionsimg = {
method: "post",
contentType: "multipart/form-data; boundary="+boundary,
oAuthServiceName: "twitter",
oAuthUseToken: "always",
payload: requestBody
};

var uploadimgres = service.fetch("https://upload.twitter.com/1.1/media/upload.json", optionsimg);
var o = JSON.parse(uploadimgres.getContentText());
try {
var imgid = o[0].media_id;

     if (user){
        status = status + "?status=" + encodeString("@" + user + " " + tweet);}
     else{
        status = status + "?status=" + encodeString(tweet);
     }
     status = status+"&media_ids="+ encodeString(imgid);
     try {
        var result = service.fetch(status, options);
     } catch (e) {
        Logger.log(e.toString());
     }
  }
  catch(e){
     Logger.log(e.toString());
  } 

}

It's in this last function that I have to somehow use a oauth object. Do I need to do the oAuth() function again? And if so, doesn't that trigger that callback again?

from apps-script-oauth1.

erickoledadevrel avatar erickoledadevrel commented on May 31, 2024

Yes, you should just call the oAuth() function again. It doesn't automatically trigger the OAuth flow, and service.hasAccess() should be true.

from apps-script-oauth1.

YiuriV avatar YiuriV commented on May 31, 2024

Ok, so I added following code:
var service2 = oAuth();
var hasacc = "";
hasacc = service2.hasAccess();

if (hasacc == true) { ...

to first that the access and if true, to upload the image, but I get a hasacc = null. I feel i'm missing something :p

from apps-script-oauth1.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.