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)
}
Related
In new Zapier UI, I used to do below..
return z.request(options).then(response => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
let attachmentArray = [];
attachmentArray = results.data.map(function(result) {
let attachment = {};
attachment.id = result.attachment_id;
let file_url = options.url + `/${attachment.id}`;
attachment.url = file_url;
attachment.file = z.dehydrateFile(file_url, {
method: "GET",
headers: { Authorization: `Bearer ${bundle.authData.access_token}` }
});
return attachment;
});
return attachmentArray;
});
This is my code to provide a trigger. Currently, it throws
Error: You must pass in a function/array/object. We got string instead.
David here, from the Zapier Platform team. That error comes from this line, which is responsible for finding methods on your root App object. We've actually got a test covering that exact case here.
The offending code doesn't seem to be in the sample you provided above, but take a look at anywhere you're calling dehydrate('some str') or appTester('some string')
I created a bot that updates automatically a Google sheet whenever a message is posted in a specific Slack channel.
Now I want to send a message back to Slack whenever a task is marked as completed in the spreadsheet.
I thought to run a loop through a specific column to check on every edit if the value of any cell in that column has changed to 'completed' and send the text in that row to Slack.
The problem I can't solve is how to check if a specific message has been marked as 'completed' in the past and don't send that message to slack.
Any suggestions?
var SLACK_WEBHOOK_URL= "";
function pushToSlack() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var data = sheet.getDataRange().getValues();
data.splice(parseInt(0), 1); // remove the first header row
for (var i in data) {
var indicator = data[i][1];
var update = data[i][2];
var ongoing = data[i][6];
if (!ongoing) { continue; }
sendToSlack(indicator,update,ongoing);
}
}
function sendToSlack(indicator,update,ongoing) {
var payload = {
"text" : ":update_" + indicator + ": ISSUE RESOLVED:" + update
};
var options = {
"method" : "post",
"contentType" : "application/json",
"payload" : JSON.stringify(payload)
};
// push to slack channel
return UrlFetchApp.fetch(SLACK_WEBHOOK_URL, options);
}
You will need some kind of bookkeeping about which completed messages have already been sent back to Slack. One way to go about it is to use a hidden (and protected) column in the google sheet to mark messages that have already been sent.
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
I am trying to post data to mvc controller and i am unsuccessful doing so..hope i get any help...here is the xhrpost call
var reqObj =
{
Id: dojo.byId("Id").value,
Password: dojo.byId("Password").value
};
console.log(reqObj );
var xhrArgs = {
url: '~/FormController/ValidateRequest',
postData: reqObj ,
handleAs: "json",
headers: { "Content-Type": "application/json", "Accept": "application/json"},
load: function (data) {
alert(data);
}
}
var deffered = dXhr.post(xhrArgs);
console.log(deffered);
}
I could not even see a post call in firebug....what might be the problem..any clues?
Thanks in advance.
I see a couple issues:
First you populate reqObj with the values you want to post, however, you put "request" into your xhrArgs.
Second, you will need to convert reqObj to json (dojo.toJson), since you are handling the post as json.
Also, I don't see a reference to the dojo.xhrPost method? Are you using sometype of framework that encapsulates that?
var display_message="";
$('input:checked').each(function(index) {
var profile_id=$(this).val();
$.ajax({
type: 'post',
url: 'myUrl',
data: data,
success: function(data) {
if(data=="ok")
display_message = display_message + data +", ";
}
});
});
alert(display_message);
alert(display_message);
if($.trim(display_message)!=""){
jAlert("Your birthdate already exits in "+display_message.substring(0, display_message.length - 2)+".", "Bdate");
return false;
}
in this code, i use two alert-box for display display_message variable value.
when i run successfully this code, in 1st alert-box i get blank value and second alert-box i get value which i needed, then it will go in if condition.
if i doesn't use alert box then it will always take null value in display_message variable and never enters into the if condition. so what i need to change to run this code without alert box?
You are making an asynchronous call via AJAX, but your code is executing synchronously. So it is returning before the AJAX call completes. The first alert box just gives the function time to catch up. You need to handle all this code in your success callback.
var display_message="";
$('input:checked').each(function(index) {
var profile_id=$(this).val();
$.ajax({
type: 'post',
url: 'myUrl',
data: data,
success: function(data) {
if(data=="ok")
display_message = display_message + data +", ";
if($.trim(display_message)!=""){
jAlert("Your birthdate already exits in "+display_message.substring(0, display_message.length - 2)+".", "Bdate");
return false;
}
});
});
You want all your ajax queries to finish and return results, right?
Then this is a synchronization problem.
I would suggest this approach (code is simplified for clarity).
var inputs_processed = -1;
var inputs_to_process = -1;
function queryData() {
inputs_to_process = $('input:checked').length;
$('input:checked').each(function() {
$.ajax({success: function(data) {
inputs_processed += 1;
// build up that message
}});
});
}
function displayResult() {
if (inputs_processed == inputs_to_process) {
// display result
} else {
// not all queries finished yet. Wait.
setTimeout(displayResult, 500);
}
}
queryData();
displayResult();
Basically, you know how many requests should be made and you don't display result until that number of requests returns.
Why your data is "data"? I cant see any variable called data is declared here. You should pass in the value you want to use as the parameter into the data options.
Edit: This is why u getting the null value. data is not initialize into anything. Only after the success function, your "data" will have the value since you declare the return value with the same name