posting a custom JSON message on Slack using Webhook - javascript

How can i post a custom JSON Message with formatting & indented using slack webhook? I am using nodejs app
var Slack = require('slack-node');
var JsonMessage = process.argv[2];
webhookUri = "https://hooks.slack.com/services/XXXX/xxxx/xxxxxxxx";
slack = new Slack();
slack.setWebhook(webhookUri);
var textmsg = '```' + JsonMessage + '```';
slack.webhook({
channel: "#status",
username: "Monitor Bot",
icon_emoji: ":ghost:",
text: textmsg
}, function(err, response) {
console.log(response);
});
The above code helps to send the JSON but it is not in formatted one. It comes as a string. I would like to have the JSON indented.
Thank you.

Your JsonMessage argument is just a string, therefore it is sent as such to slack. I'd suggest sending it through JSON.parse to convert it into native JavaScript objects. You can then send it through a formatter to format it properly for you. e.g.
var formatter = ('format-json');
var formattedJson = formatter.plain(JSON.parse(JsonMessage));

Related

How to do otp verification using 2 factor

I have taken free trail from 2 factor for sending sms as otp and needs to be verified again, I am able to send the sms and also console.log the status on node side, but the issue is I am not able to send the response to client weather otp is sent or not and how could I verify it
What I have done till now
let otp = Math.floor(100000 + Math.random() * 900000) // geterating otp
const no = req.body.cPhoneNo //phone no from UI
console.log(no)
var options = {
"method": "POST",
"hostname": "2factor.in",
"port": null,
"path": "/API/V1/{{api_key}}/ADDON_SERVICES/SEND/TSMS",
"headers": {}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
let sendData = body.toString()
console.log(body.toString())
res.json({status:body.toString}) //here I am getting error as type error json is not a function
});
});
req.write(JSON.stringify({
From: 'something',
To: no,
TemplateName: 'some Name',
VAR1: 'var 1',
VAR2: otp
// SendAt: '{OptionScheduleTime}'
}));
req.end();
I have mentioned with comment Where I am trying to send status back to client if it is send or not, but it is not taking json as throwing error .json throws type error
**One more thing I found from there website is **
I have found two url end points one to send sms with some session Id and other to get otp entered from user and verify that These are two urls
To send Otp https://2factor.in/API/V1/{api_key}/SMS/{phone_number}/AUTOGEN
To receive Otp https://2factor.in/API/V1/{api_key}/SMS/VERIFY/{session_id}/{otp_input}
api_key= The key I have got from 2factor
phone_number = receivers no
My issue is How I can use this endpoints to send the sms and to do verification, from client end I am on button click I am sending req to server via axios but in backend I have been suffering to send the msg and verify the otp
You can check out this link
Anyone out here please guide me
I don't see res.json method in node's HTTP module. Express has res.json method. Instead you should use JSON.parse. Have a look at this example from documentation.

POST to a REST service using Ajax is failing

I am working with a javascript client that I am trying to use to communicate with a server. I have a Javascript function that is POSTing to a Spring Boot REST service. The service is a simple test service that doesn't do much...
#RequestMapping(method = RequestMethod.POST,value="/testservice")
#ResponseBody
public String testPostRequest(#RequestParam String someText)
{
System.out.println("Reached the counting service! Param value: " + someText);
if(someText != null)
{
...
perform some actions
...
}
return("Success");
}
The Javascript I am using to send POST requests to the server is below:
var sendWords = function(toSend) {
var data = { DataList : [toSend] };
var param = { someText: data };
$.post("http://localhost:8080/testservice",param,
function(status,ret) {
alert("We're back "+status);
});
};
The toSend parameter is just a string containing some text that will be posted to the service. Note that the port for the service was set to 8080 in the server's application.properties file.
When I call the Javascript function and post the string to the service, I get the following log message from the server:
2019-07-28 20:00:06.292 WARN 80844 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'someText' is not present]
I am doing something wrong, but cannot figure out what it is. I am sending an object that is tagged as the someText string, but it is not being recognized by the server for some reason.
Can someone tell me what I am missing? How do I get this to work?
var data = { DataList : [toSend] };
var param = { someText: data };
Here data is not string.
You may need to stringify it.
var param = { someText: JSON.stringify(data) };
You are missing the value in the #RequestParam(), such as #RequestParam(value="someText", required=true).
You could use #PathVariable too.
This could be helpful:
#RequestParam vs #PathVariable

Pass JSON from SQL Server to D3 Javascript

I'm building an ASP.NET using C#, Visual Studio, SQL Server, D3.JS.
I have values in a SQL Server that I'm getting from the database and the results are:
[
{"AMOUNT":1.000000000000000e+002},{"AMOUNT":1.000000000000000e+003},
{"AMOUNT":1.000000000000000e+004},{"AMOUNT":5.000000000000000e+003}, {"AMOUNT":2.000000000000000e+003},{"AMOUNT":1.000000000000000e+003},
{"AMOUNT":5.000000000000000e+003},{"AMOUNT":3.000000000000000e+003},{"AMOUNT":8.000000000000000e+003},{"AMOUNT":1.200000000000000e+004},
{"AMOUNT":5.000000000000000e+003},{"AMOUNT":1.300000000000000e+004},
{"AMOUNT":1.500000000000000e+004}
]
Okay so my Json output is correct, below is code I'm using to get the json output above:
public string jsonString = "";
public string JasonGet()
{
var queryWithForJson = "SELECT AMOUNT FROM PeopleTable WHERE Bal = 'Acc' FOR JSON AUTO";
var conn = new SqlConnection(#"MyConnectSource!");
var cmd = new SqlCommand(queryWithForJson, conn);
conn.Open();
var jsonResult = new StringBuilder();
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
Label1.Text = jsonResult.ToString();
// jsonString = (new JavaScriptSerializer()).Serialize(jsonResult);
return (new JavaScriptSerializer()).Serialize(jsonResult);
}
And this works fine above I believe since I am putting the results on a label1.Text from a jsonString to see it for myself but the last return line is where I'm part confused because now I wish to pass the JSON result to my D3.JS. Let me show what I'm doing in D3...
<script>
d3.json('<%= JasonGet() %>').then(function (data) {
console.log("Json string: " + data);
});
</script>
Okay so I believe in my C# function that I have the correct results but I think the error is when I'm passing the values to my Javascript. Below is the error code I'm getting:
Uncaught SyntaxError: Unexpected end of JSON input
and
Failed to load resource: the server responded with a status of 400 (Bad Request)
I appreciate any suggestions, sorry if it's not explained properly but to sum it up, we are getting json values from the database from a C# function and then want to pass it into Javascript.

Better way to pass data to server?

So I am using query strings to pass data from a form to my server. The query strings look like this:
this.$http.post('http://localhost:3000/operation?Stime='+this.Stime+'&Etime='+this.Etime+'&eAMPM='+this.eAMPM+'&sAMPM='+this.sAMPM+'&id='+this.id+'&activity='+this.activity+'&auto_insert='+this.auto_insert+'&yearmonthday='+this.yearmonthday+'&color1='+this.c)
and In my server I have all these variables to store the query's variables:
var color = req.query.color1;
var Stime = req.query.Stime;
var Etime = req.query.Etime;
var sAMPM = req.query.sAMPM;
var eAMPM = req.query.eAMPM;
var id = req.query.id;
var activity = req.query.activity;
var requestAccepted = req.query.requestAccepted;
var yearmonthday = req.query.yearmonthday;
var auto_insert = req.query.auto_insert;
It just seems like a lot of code to just post my variables to the server (It works just fine) but I was wondering if there were some ways I could refactor it/ make it cleaner
Of course there is!
Consider doing some research into the HTTP message body:
A message body is the one which carries the actual HTTP request data (including form data and uploaded, etc.) and HTTP response data from the server ( including files, images, etc.).
In your case, you can change your Angular $http POST request to as follows -
var data = {
Stime: '+this.Stime+',
Etime: '+this.Etime+',
eAMPM: '+this.eAMPM+',
sAMPM: '+this.sAMPM+',
id: '+this.id+',
activity: '+this.activity+',
auto_insert: '+this.auto_insert+',
yearmonthday: '+this.yearmonthday+',
color1: '+this.c+'
}
$http({
method: 'POST',
url: 'http://localhost:3000/operation',
data: JSON.stringify(data)
})

Netsuite POST data from a Portlet to a RESTlet in JSON

In NetSuite, I'm trying to create a form Portlet POST data to a RESTlet in JSON. I've checked the documentation and internet and all the examples I've been able to find are GET requests or they post to a backend Suitelet instead.
I've come to a point where I can make the request reach the RESTlet but it's not being formatted in JSON, so I get the following error:
Account: xxxxxxxxxxxxx
Environment: Production Date & Time: 6/11/2015 5:09 pm
Execution Time: 0.06s
Script Usage: 0
Script: gw_SS_FormBackend
Type: RESTlet
Function: postWMForm
Error: UNEXPECTED_ERROR
SyntaxError: Empty JSON string (null$lib#3)
I'm using the following code to set the submit button and it's working fine:
var headers = new Array();
headers['User-Agent-x'] = 'SuiteScript-Call';
headers['Authorization'] =
'NLAuth nlauth_account=' + cred.account +
', nlauth_email=' + cred.email +
', nlauth_signature=' + cred.password +
', nlauth_role=' + cred.role;
headers['Content-Type'] = 'application/json';
portlet.setSubmitButton(nlapiRequestURL(getRESTletURL(), null, headers, 'POST'), 'Submit', '_hidden');
My problem is I don't know how to convert the form data to JSON before submitting it.
I'd appreciate any help.
Why would you want to use a RESTlet? If you are in a portlet then you already have a valid NS session so you'd be better off using a Suitelet. A Suitelet you know is set up to handle JSON would be called thus:
nlapiRequestURL(suiteletURL', JSON.stringify{test:'it', when:new Date(), by:'Brett'}), {"content-type":'application/json'}, function(resp){console.log(resp.getBody());}, 'POST');
and your Suitelet code might include something like:
var body = request.getBody();
nlapiLogExecution('DEBUG', 'posted body', body);
var asJSON = JSON.parse(body);
var user = nlapiGetContext().getUser(); // system already knows who this is.
...
var obj = {
success:true,
stuff: asProcessed
};
response.setContentType('JAVASCRIPT');
response.writeLine( JSON.stringify(obj) );
Not quite as clean as a RESTlet but you avoid having to hack the credentials.
you can use JSON.stringify() function.
var headers = new Array();
headers['User-Agent-x'] = 'SuiteScript-Call';
headers['Authorization'] =
'NLAuth nlauth_account=' + cred.account +
', nlauth_email=' + cred.email +
', nlauth_signature=' + cred.password +
', nlauth_role=' + cred.role;
headers['Content-Type'] = 'application/json';
var myJsonHeader = JSON.stringify(headers);
portlet.setSubmitButton(nlapiRequestURL(getRESTletURL(), null, myJsonHeader, 'POST'), 'Submit', '_hidden');
Regards

Categories