Post a message to slack using https://slack.com/api/chat.postMessage - slack

I want to post a message to slack on x channel
I need to send the following x parameters
how do I send the following parameters to a website
"channel": "XXXXX",
"token": "token",
"text": "text"

Add your parameters to the end of Slack's chat.postMessage endpoint like this:
http://slack.com/api/chat.postMessage?token=XXX&channel=XXX&text=XXX
Then make a GET request to that URL to post your message. Personally I'd suggest doing this as a Node application and using the request package obtained via npm. Makes it very easy.
Post message to Slack in a Node App
Create a new node project and then change to that folder on the command line
On the command line type npm install -g request to install the request module for your project
Inside the index.js file (or wherever you plan on calling the API) do as follows:
//Import request module
var request = require('request');
//Replace your token, channelID and text here
var path_to_call = 'http://slack.com/api/chat.postMessage?token=XXX&channel=XXX&text=XXX';
request(path_to_call, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Success');
} else {
console.log(error);
}
});

If you just want to post messages I would recommend to use an Incoming Webhook. They are specifically designed for that purpose and easier to use than API calls.
An Incoming webhook is a custom URL that you can create for your Slack team and then use to send messages into any channel. For sending a message you only need to submit your message in JSON format along with some parameters as POST request to your webhook URL.
If you are using PHP scripting on your website then you best use CURL for the call.
Check out the documentation for details on how to use it.

var url = "https://slack.com/api/chat.postMessage";
var auth_token = auth_token; //Your Bot's auth token
var headers = {
"Authorization": "Bearer " + auth_token,
"Content-Type" : "application/json"
}
var body = {
channel: userSlackId, // Slack user or channel, where you want to send the message
text: "Your text goes here."
}
request.post({
"url": url,
"headers": headers,
"body": JSON.stringify(body)
}, (err, response, body) => {
if (err) {
reject(err);
}
console.log("response: ", JSON.stringify(response));
console.log("body: ",body);
});
You have to set headers as Authorization, and add Bearer before your token as it is mentioned in slack docs. Also, send user/channel in body. Here I'm providing the link for the same for your reference https://api.slack.com/methods/chat.postMessage#channels . Hope this helps.

Not sure which language you're using, but if using Postman to test, you can try the following format.
raw Postman request
POST /api/chat.postMessage HTTP/1.1
Host: slack.com
Content-Type: application/json
Cache-Control: no-cache
{
"text": "This is a line of text.\nAnd this is another one.",
"token": "XXXX",
"channel": "XXXX",
}

Related

Vue.js Axios Post request blocked

I am trying to build a test app with a vue frontend and a spring boot backend. The backend receive a json from the frontend to register a new user.
But I am struggeling at the point to send a post request from the vue frontend to the backend. I only receive the status Blocked.
So this is the method in vue which should send the post request:
testMethodToClick() {
const data = {
"firstName": "Test",
"lastName": "Tester",
"email": "test.tester#test.de",
"password": "password"
}
const header = {
"Content-Type": "application/json",
"Accept": "*/*"
}
axios.post("http://ptsv2.com/t/ty0mk-1643012780/post");
axios.post("http://localhost:8886/api/v1/registration", data, header);
}
The first post request to ptsv2.com is just to test if the post request generally is working.
But this is the result:
But if I try to test the endpoint with postman, than it works:
So I did something wrong on the vue side.
Does someone know what I am missing?
Thank you very much!

AWS API Gateway adding Content-Type Header to OPTIONS Reques

I am trying to write an OPTIONS request using a Lambda and AWS Gateway to respond to post requests - this code comes from AWS documentation:
exports.handler = function(event, context) {
var responseCode = 200;
var response = {
statusCode: responseCode,
headers: {
"Access-Control-Allow-Origin": "*"
}
};
context.succeed(response);
};
When I test it in AWS Lambda, it provides the correct response
Response:
{
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
}
}
However, when I try to run it using AWS API Gateway,
it adds on a Content-Type header that was not part of the response. As a result, when I tried to make a post requests, I get the error that 'Content Type in not allowed in preflight response'. Any idea what the issue could be?
if you run the below command,
curl -H "origin: example.com" -v "https://h64hstwg05.execute-api.us-east-1.amazonaws.com/default/optionsrequest"
it returns content-type: application/json. it is because application/json is the default value when it is not specified.
here is this from aws docs.
When the Content-Type header is absent in the request, API Gateway assumes that its default value is application/json
Reference:
https://docs.amazonaws.cn/en_us/apigateway/latest/developerguide/request-response-data-mappings.html
You could always override and return a different content-type header from the lambda.
Hope this helps.

Send recaptcha secret in POST body instead of URL parameters

Server Integration of ReCaptcha works well when I pass values as URL parameters.
{
"success": false,
"error-codes": [
"missing-input-response",
"missing-input-secret"
]
}
The request fails when I pass values as JSON in POST body.
{
"success": true,
"challenge_ts": "2018-10-26T16:01:24Z",
"hostname": "testkey.google.com"
}
Sample code I have seen so far suggests using URL parameters but does not explain why JSON POST body is not supported.
Google's FAQ does not list it either, I am wondering if I am doing something wrong. Is it even possible to request through JSON?
Google's recaptcha api does not support json body. They expect you to send the body as query params.
For example:
POST request.
Body: 'secret=xxxxxxxxxxxxxxxx&response=xxxxxxxxxxxxxxxxxxxxxxxxxx'
Header: 'Content-Type': 'application/x-www-form-urlencoded'

Google cloud text-to-speech : the server responded with a status of 403 ()

I am trying to build a web page which will translate the text into mp3 using google cloud text-to-speech. After lots of search I found using REST API I can request the API to translate the text into mp3.
I am using JQuery and AJAX for the HTTP request.
Problem is that I am requesting the cloud server to translate the text using following data,
"data" : {
"input": {
"text": encodeURIComponent(text)
},
"voice" : {
"languageCode" : "en-US",
"name" : "en-US-Wavenet-A",
},
"audioConfig" : {
"audioEncoding" : "MP3",
}
},
By sending this I'm getting error 403 which clearly says that I do not have access to perform the requested action, in this document
I know without API key and authorization I cannot access the service. So my questions is how can I send my API key and authorizations keys so that I can get the authorization and perform the requested action.
Edit-1
I am sending request to server using following URL,
https://texttospeech.googleapis.com/v1beta1/text:synthesize?further_parameters_goes_here
If anyone want more information I can give it. Any help will be appreciated.
Thank you in advance.
Regards,
Vaibhav M
First you need to get your Google Cloud's API Key from your acount (https://cloud.google.com/docs/authentication/api-keys) and try the code bellow, replacing your-api-key in the script:
$( document ).ready(function() {
// An element to play the speech from Google Cloud
var Sound = (function () {
var df = document.createDocumentFragment();
return function Sound(src) {
var snd = new Audio(src);
df.appendChild(snd); // keep in fragment until finished playing
snd.addEventListener('ended', function () {df.removeChild(snd);});
snd.play();
return snd;
}
}());
// The settings for the Ajax Request
var settings = {
"async": true,
"crossDomain": true,
"url": "https://texttospeech.googleapis.com/v1/text:synthesize",
"method": "POST",
"headers": {
"x-goog-api-key": "**your-api-key**",
"content-type": "application/json",
"cache-control": "no-cache",
},
"processData": false,
"data": "{'input':{'text':'I have added the event to your calendar.'},'voice':{'languageCode':'en-gb','name':'en-GB-Standard-A','ssmlGender':'FEMALE'},'audioConfig':{'audioEncoding':'MP3' }}"
}
// The Ajax Request, on success play the speech
$.ajax(settings).done(function (response) {
console.log(response.audioContent);
var snd = Sound("data:audio/wav;base64," + response.audioContent);
});
});
You need to pass your API key as a header, the header field is "X-Goog-Api-Key". Also make sure you're setting the proper body encoding in the request using the "Content-Type" header, in your case I think it should be "Content-Type: application/json; charset=utf-8". And lastly, I'm think you shouldn't be encoding the text field in the request body.
If you don't have the API key yet, you can follow these steps to get to it
Create a project (or use an existing one) in the Cloud
Console.
Make sure that billing is enabled for your project.
Enable the Text-to-Speech API.
Create an API key.
I'm not familiar with JQuery and AJAX syntax, but you could use this curl command for reference
Curl -H "X-Goog-Api-Key: PUT_YOUR_API_KEY_HERE" \
-H "Content-Type: application/json; charset=utf-8" \
--data "{
'input':{
'text':'Android is a mobile operating system developed by Google,
based on the Linux kernel and designed primarily for
touchscreen mobile devices such as smartphones and tablets.'
},
'voice':{
'languageCode':'en-gb',
'name':'en-GB-Standard-A',
'ssmlGender':'FEMALE'
},
'audioConfig':{
'audioEncoding':'MP3'
}
}" "https://texttospeech.googleapis.com/v1beta1/text:synthesize" > synthesize-text.txt
I found out two possibilities that can help you.
Obtain a Bearer token.
If you installed the Cloud SDK, you can easily get the token with this command: gcloud auth application-default print-access-token. It can be executed in the Cloud Shell too. Just be sure that the default user you are logged in has the appropriate role to access the text-to-speech service. Then, attach the token to the header request, for example a final request can look like this.
curl -H "Authorization: Bearer ya29.GqUB8gVkiMCyl2ZCKEfS8Tb9QmS_LRb1bQP__fIPYbCU.....LUAlCRJU9OpFc_hCzSVUwlAZAhac2aZhoh" \
-H "Content-Type: application/json; charset=utf-8" \
--data "{
'input: {
'text': 'my custom text'
},
'voice' : {
'languageCode' : 'en-US',
'name' : 'en-US-Wavenet-A'
},
'audioConfig' : {
'audioEncoding' : 'MP3'
}
}" "https://texttospeech.googleapis.com/v1beta1/text:synthesize"
This link integrates the request and the command in one step.
Obtain an API key.
An API key is more portable than a token, but it can be used by anyone who possess it. It's recommended to restrict such key to the text-to-speech service. Then, you should use the key in the endpoint URL, for example "https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=AIzaSynAJU-EGnhdDaaXH4NVcc". A complete example looks like the following:
curl -H "Content-Type: application/json; charset=utf-8" \
--data "{
'input':{
'text':'my custom text'
},
'voice':{
'languageCode':'en-gb',
'name':'en-GB-Standard-A',
'ssmlGender':'FEMALE'
},
'audioConfig':{
'audioEncoding':'MP3'
}
}" "https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=AIzaSynAJU-EGnhdDaaXH4NVcc"

How to properly set Authorization to consume Wordpress Rest API (Oauth1) with Nativescript[2.5.4]?

I'm trying to consume the WP Rest API with Nativescript.
The WP API and the Authorization with OAUTH1 is already well setup and tested with POSTMAN.
Nativescript Login function to consume rest is already setup too and work without OAUTH.
Now I'm trying to Login with OAUTH here the code :
authorizationString = 'OAuth oauth_consumer_key="T2yXcbN28Ufj",
oauth_token="AmEVr5oSNmbKyZKccFjtmnSk",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1492267438",
oauth_nonce="rGFJG2",
oauth_version="1.0",
oauth_signature="Ru%2BaSvsZn2liesd2ENy8GeNsdHY%3D"';
login(user: User){
console.log("Try to login User : " + user.email);
let headers = new Headers({"Authorization": authorizationString});
let body = JSON.stringify({
username: user.username,
email: user.email,
password: user.password
});
headers.append("Content-Type", this.contentType);
return this.http.post(
this.api,
body,
{headers: headers}
)
.map( response => response.json() )
.do(data => {
//Do work!!
})
.catch(this.handleErrors);
}
But i got an error, this error means the autorization is not well formatted or sent :
"data": {
"code": "rest_cannot_access",
"message": "Only authenticated users can access the REST API.",
"data": {
"status": 401
}
}
How to properly use oauth1 with Nativescript?
I just switched to OAUTH2 by using a opensource plugin :
https://github.com/wlcdesigns/WP-OAuth2-Server-Client
and it's more easy to use with the authorization : Bearer

Resources