I'm trying to invoke a service that sends a sms from a google apps script. The service wants the data in iso 8859-1. The code below send a message with the åäö as bad chars.
function sendSMS() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('b8');
var payload =
{
"username" : "XXXX",
"password" : "YYYY",
"nr" : "0123123123",
"type" : "text",
"data" : "Hello world...åäö"
};
var options =
{
"method" : "post",
"payload" : payload
};
var response = UrlFetchApp.fetch("http://www.mosms.com/se/sms-send.php", options);
Browser.msgBox(response.getContentText());
}
function testFetch (){
var response = UrlFetchApp.fetch("http://www.google.com/");
Browser.msgBox(response.getContentText());
}
As mentioned in the other question that Serge linked to in the comments, you can change the encoding of a string by first converting it to a Blob and then using the getDataAsString() method:
var result = Utilities.newBlob('Hello World').getDataAsString('ISO-8859-1');
Related
I found a code that I linked to a button so that, when clicking it, a message is sent in Slack. So far I was only able to have that message within the code itself, as in here:
function sendNotification() {
const url = "https://hooks.slack.com/services/"
const params = {
method: "post",
contentType: "application/json",
payload: JSON.stringify({
"text":"Hello, World!"
})
}
const sendMsg = UrlFetchApp.fetch(url, params)
var respCode = sendMsg.getResponseCode()
Logger.log(sendMsg)
Logger.log(respCode)
}
However, what I would want it to do is to grab the text from a cell, and send that as the message. Also, I don´t know if this would change anything, but the message in the cell comes up as the result of a formula un that cell, so it is the text that needs to go through, but not the formula.
If someone could help with this that would be awesome! TIA!
To retrieve the text from a specific cell, you can use getRange() and getValue().
You can use the following example, just make sure to change the name of the sheet and the cell in the script:
function sendNotification() {
let ss = SpreadsheetApp.getActive();
let sheet = ss.getSheetByName("Sheet1");//Change the name of the sheet where you have the message
let message = sheet.getRange("C1").getValue();//Change the cell where you have the message
const url = "https://hooks.slack.com/services/"
const params = {
method: "post",
contentType: "application/json",
payload: JSON.stringify({
"text":message
})
}
const sendMsg = UrlFetchApp.fetch(url, params)
var respCode = sendMsg.getResponseCode()
Logger.log(sendMsg)
Logger.log(respCode)
}
My objective is to use the upload attachment functionality of the Gmail API. The uploaded file is to be processed within my Gmail add-on. I found the following POST request in this link.
POST https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=media
Here is my try so far:
function testPOST() {
Logger.log('Testing of POST in Apps script');
// var url = ScriptApp.getService().getUrl();
var url = "https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send"
Logger.log('URL:'+url);
var options =
{
"method" : "POST",
"uploadType" : "media"
};
// Trying to fetch the file
var result = UrlFetchApp.fetch(url, options);
Logger.log('Response code: ' + result.getResponseCode());
// maybe I need to use some function in 'Gmail.Users.*'
}
I pulled this code from this question.
Applying the author's solution, I am always given this error:
I get my key and secret from my created twitter app here:
I have the app configured to write...
What am I doing wrong?
//post tweet
function oAuth() {
var CONSUMER_KEY = "xxxx";
var CONSUMER_SECRET = "xxxxx";
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='Operational!';
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');
}
I was getting this error also, until I realized you need to specify a 'CallBack URL' in Twitter:
Specifying that as either 'https://script.google.com' or 'https://script.google.com/macros' is allowing me to Authorize. I've tested this and it's currently letting me post with the code that you've listed.
One note however if you try and post the same 'status' text twice, it will throw you the following error:
This isn't an issue as you simply change the value of the variable 'Status', but it threw me the first time.
As the title suggests, my goal here is to be able to send a tweet from a script.gs. The tweet would be posted to my feed, ideally without me having to visit the Twitter website.
I wrote two main functions to attempt this:
script.gs
//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/authorize");
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 = "Tweet";
var Roptions = {
method: "post",
oAuthServiceName: "twitter",
oAuthUseToken: "always",
status: status
};
var url = "https://api.twitter.com/1.1/statuses/update.json";
Logger.log('begin post');
var request = UrlFetchApp.fetch(url, Roptions); //the trouble line. Execution stops.
Logger.log('post complete');
}
After about a day of relentless hacking, I was able to get the first function, oAuth() to work. That logs, well, my user data. However, for the life of me, I cannot figure out what is holding up request. I do get this error: Request failed for returned code 403. Truncated server response: {"errors":[{"message":"SSL is required","code":92}]}. Googling this didn't turn up much. I'm guessing that the issue is somewhere in Roptions. Any help would be appreciated, and I can try to provide further clarification if needed.
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
The json sent to server php file as post request from ibm worklight Http adapter not accessible even after decoding:
Here are the codes:
Http adapter:
function storeRegistrationData(emailVal, passVal, fname1, gender, phone, userType, vehType) {
var credentials = JSON.stringify({jemailVal: emailVal, jpassVal: passVal, jfname1: fname1, jgender: gender, jphone: phone, juserType : userType, jvehType : vehType});
var input = {
method : 'post',
returnedContentType : 'json',
path : "/carbikepooling/index.php",
parameters: {credentials: credentials}
};
return WL.Server.invokeHttp(input);
}
Server php code:
$jsonObj = (isset($_POST['credentials']) ? $_POST['credentials'] : null);
$credentials = json_decode($jsonObj);
$email = $credentials->jemailVal;
$pass = $credentials->jpassVal;
$uname = $credentials->jfname1;
$gender = $credentials->jgender;
$phone = $credentials->jphone;
$usertype = $credentials->juserType;
$vehtype = $credentials->jvehType;
$boolean = false;
$userId; $userTypeId;
// sanitation, database calls, etc
$connection = mysqli_connect("localhost","root","","carbikepooling");
if (mysqli_connect_errno($connection))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connection,"insert into userInfo values(0,".$email.",'".$pass."','".$uname."','".$gender."','".$phone."')");
$result1 = mysqli_query($connection, "select u.userId from userInfo u order by u.userId desc limit 1");
if($result1){
$row1 = mysqli_fetch_row($result1);
$userId = $row1[0];
mysqli_query($connection,"insert into userType values(0,".$userId.",'".$usertype."')");
$result2 = mysqli_query($connection, "select t.userTypeId from userType t order by t.userTypeId desc limit 1");
if($result2){
$row2 = mysqli_fetch_row($result2);
$userTypeId = $row2[0];
mysqli_query($connection, "insert into vehicleType values(0,".$userTypeId.",'".$vehtype."')");
$boolean = true;
}
}
mysqli_close($connection);
$returnData[] = array(
'boolean' => "$boolean"
);
echo json_encode($returnData);
?>
Javascript code to show return result from server php:
function storeFormData(emailVal, passVal, fname1, gender, phone, userType, vehType){
var invocationData = {
adapter : 'registerUser',
procedure : 'storeRegistrationData',
parameters : [emailVal, passVal, fname1, gender, phone, userType, vehType]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : storeFormDataSuccess,
onFailure : storeFormDataFailure,
});
}
function storeFormDataSuccess(result){
WL.Logger.debug('Data stored Successfully');
alert(JSON.stringify(result.invocationResult));
}
function storeFormDataFailure(result){
WL.Logger.error('Error in storing Data');
}
What happens is that when I used decoded json data in server php file in the insert statements, nothing happens. I tried echoed values of email, gender, etc. but nothing prints as if they contain no values. However, if I sent the decoded json values of email, gender etc. in the returnData array as they are used in insert statements, values successfully received by the app which made the request, i.e: shown those values in the alert in the js code. Please solve this problem?
Hmm, that is strange. I copied and pasted your exact code and I was able to echo the variables that were passed from the Worklight adapter. Maybe the way you are trying to use the variables for your sql statements is wrong?
Can you change your mysql query to look something more like this?
mysqli_query($connection, "insert into vehicleType values(0, '$userTypeId','$vehtype')");
Notice how I've removed the concatenation '.' from the query and I now I just have the variables surrounded by single quotes.