Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

schedule twitter #17

Closed
YiuriV opened this issue Dec 4, 2015 · 4 comments
Closed

schedule twitter #17

YiuriV opened this issue Dec 4, 2015 · 4 comments

Comments

@YiuriV
Copy link

YiuriV commented Dec 4, 2015

Hi, I'm using this library to connect my google spreadsheet with twitter so I can schedule my tweets. I have a function that authorizes my app. Then I schedule my tweets and use a trigger to send out the tweets. However, in the function that sends them out, I somehow have to get such a oauth object without going through the whole authenticating process again. Can someone help me with this?

@erickoledadevrel
Copy link

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.

@YiuriV
Copy link
Author

YiuriV commented Dec 4, 2015

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?

@erickoledadevrel
Copy link

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

@YiuriV
Copy link
Author

YiuriV commented Dec 4, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants