I am using kapacitor to send alert to URL using HTTP POST. Written script is hitting on given url but it is not sending related data to any of given url.
Following is my TICK script.
stream
|from()
.measurement('cpu')
|alert()
.id('kapacitor/{{ index .Tags "host"}}')
.message('{{ .ID }} is {{ .Level }} value:{{ index .Fields "value" }}')
.info(lambda: TRUE)
.post('http://localhost:1440/alert')
.post('http://localhost/test.php')
Following is a first post script:
var express = require("express");
var app = express();
var moment = require("moment");
var dateTime = moment();
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({extended:false});
var jsonParser = bodyParser.json();
var port = 1440;
app.post('/alert', jsonParser ,function(request, response){
console.log(request.body);
response.send();
});
app.listen(port);
console.log('Express App.js listening to port '+port);
Following is a second post script:
<?php
$content = json_encode($_REQUEST);
echo file_put_contents("/home/mahendra/Documents/tick/highcputick.log", $content);
?>
both urls are getting emtpy data.
Kapacitor version is: Kapacitor 1.3.1
Following is Kapacitor [[httppost]] config
[[httppost]]
endpoint = "NodeJs"
url = "http://localhost:1440/alert"
# headers = { Example = "node" }
# basic-auth = { username = "my-user", password = "my-pass" }
You actually need to set on the tick script the endpoint, like:
...
.post()
.endpoint('NodeJs')
I had a similar problem in php - zend framework and this is how I solved the problem.
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'),true);
Your message details will be in $data. I got this here: https://github.com/influxdata/kapacitor/issues/1681
Related
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 am trying to make an HTTP request to 000webhost as below in my flutter web app. The first method is the same as the second, I only changed the URL. However, the first one works but the second does not work. Someone suggested adding more headers but I have no idea which headers to add.
// This method WORKS
getMethod()async{
print("IN GET ....");
String theUrl = 'https://jsonplaceholder.typicode.com/todos';
var res = await http.Client().get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
//var res = await http.get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
var responsBody = json.decode(res.body);
print(responsBody);
return responsBody;
}
// This DOES NOT WORK
getMethod()async{
print("IN GET ....");
String theUrl = 'https://funholidayshotels.000webhostapp.com/fetchData.php';
var res = await http.Client().get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
//var res = await http.get(Uri.encodeFull(theUrl),headers: {"Accept":"application/json"});
var responsBody = json.decode(res.body);
print(responsBody);
return responsBody;
}
After struggling with this for some time I figured out the problem was from the server side
I had to add Header add Access-Control-Allow-Origin "*" to .htaccess on 000webhost And This solves it for me
You can also Add the code below to your php file like so:
<?php
require('connection.php');
header("Access-Control-Allow-Origin: *");
....
code goes here
....
?>
I Tried this on LocalHost and it worked
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 had a Google Apps Script to take appointments from my Google Calendar, copy them into a Google Sheet, convert it to XLS and email it. It was working fine until this week.
The initial problem was a 302 error, probably caused by the new version of Sheets. This has been discussed here: Export (or print) with a google script new version of google spreadsheets to pdf file, using pdf options
I got the new location of the file by muting the HTTP exceptions and adjusting the URL accordingly. I also updated the OAuth scope to https://docs.google.com/feeds/ as suggested.
The program is failing with an "OAuth error" message. When muteHttpExceptions is set to true, the message is "Failed to authenticate to service: google".
I guess this is a scope problem but I really can't see what I've done wrong. Naturally, I've tried a few other possibilities without luck.
I've included the code below. Commented code is the instruction that worked until this week.
function getSSAsExcel(ssID)
{
var format = "xls";
//var scope = "https://spreadsheets.google.com/feeds/";
var scope = "https://docs.google.com/feeds/";
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=" + scope);
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var requestData = {
//"muteHttpExceptions": true,
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
//var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ssID
var url = "https://docs.google.com/spreadsheets/d/" + ssID
+ "/feeds/download/spreadsheets/Export?"
+ "&size=A4" + "&portrait=true" +"&fitw=true" + "&exportFormat=" + format;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
return contents;
}
Thanks for your help!
Instead of using OAuthConfig (which must be auth'ed in the Script Editor) you can pass an OAuth2 token instead, retrievable via ScriptApp.getOAuthToken().
The code snippet below uses the Advanced Drive service to get the export URL, but if you hand construct the URL you'll need to ensure that the Drive scope is still requested by your script (simply include a call to DriveApp.getRootFolder() somewhere in your script code).
function exportAsExcel(spreadsheetId) {
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
return response.getBlob();
}
I'm using the Bunny gem in Rails and AMQP in Node.js.
Rails is the publisher and the Node.js app is a subscriber.
Code from Rails:
conn = Bunny.new
conn.start
ch = conn.create_channel
x = Bunny::Exchange.new(ch, :direct, "messenger")
q1 = ch.queue("new_messages").bind(x, :routing_key => 'send')
x.publish('hi', :routing_key => 'send')
Code from Node.js:
var amqp = require('amqp');
var connection = amqp.createConnection();
connection.addListener('ready', function(){
var exchange = connection.exchange('messenger');
var queue = connection.queue('new_messages')
queue.bind('messenger', 'send')
queue.subscribe( {ack:true}, function(message){
console.log(message.data.toString())
queue.shift()
});
});
From the management plugin I can see that the Rails code works well, but the code from Node.js doesn't make sense.
Where is my mistake?
The main issue is in how you're attempting to bind your queue to the 'messenger' exchange. You've already used the exchange name to get a reference to the exchange object. Rather than pass in the string name again when binding the queue to the exchange, pass this reference into queue.bind(). Simply change the first queue.bind() argument:
var exchange = connection.exchange('messenger');
var queue = connection.queue('new_messages');
// Use the reference to the exchange object you just received;
// pass it in here instead of the exchange's name
queue.bind(exchange, 'send');
EDIT
Here is a full, working example; just drop in your own connection properties:
var amqp = require('amqp');
var connection = amqp.createConnection({
host: 'my_host',
login: 'my_login',
password: 'my_password',
authMechanism: 'AMQPLAIN',
vhost: 'my_vhost'
});
connection.addListener('ready', function(){
console.log('ready');
var exchange = connection.exchange('messenger');
var queue = connection.queue('new_messages');
queue.bind(exchange, 'send');
// if message successfully received, print message
queue.subscribe( {ack:true}, function(message){
console.log(message.data.toString());
queue.shift();
});
// test by sending a message
exchange.publish('send', 'this is a test message', {}, function() {})
});
Cheers.