Comments (4)
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.
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.
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.
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)
- QuickBooks error when querying with = HOT 1
- Modify Callback Function? HOT 2
- Not working anymore? HOT 1
- Lack of RSA-SHA1 support HOT 3
- Support for "2-legged" OAuth v1.0a? HOT 6
- Goodreads OAuth Problems HOT 3
- Support for Standalone Google Apps Script Projects HOT 1
- Etsy OAuth 1.0 issues HOT 9
- OAUTH Token undefined HOT 2
- OAuth1a without TokenUrl HOT 5
- Can I pass Basic Auth of request url ? HOT 4
- Unknown or previously rejected token HOT 1
- XeroPrivate.gs needs PLAINTEXT oauth signature method but RSA-SHA1 encoded consumer secret HOT 1
- Upgrade to the latest version of the OAuth signer library
- Implement fetchAll
- OAuth1 not working in Chrome V8 Engine HOT 1
- Trello Invalid Signature HOT 1
- Security: OAuth Client ID and Secret are accessible to any user of an Apps Script in almost all samples HOT 1
- [SyncRepoSettings bot] - Invalid config file
- .
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from apps-script-oauth1.