Using CURL with discord.js and 5sim API - api

Im trying to make a command for my discord bot, so I can get a verification code for any kind of account from 5sim via their api... I think im very close since some of my code worked in https://reqbin.com/req/c-vdhoummp/curl-get-json-example... but im having trouble implementing it into my command! This is my first time using Curl so im not too familiar, but I was wondering if anyone could give me some help with my broken code?
const Discord = require(`discord.js`)
const curl = require(`curl`)
module.exports = {
name: `buynumber`,
description: `buys a phone number!`,
async execute(message) {
const response = curl 'https://5sim.net/v1/user/buy/activation/cambodia/any/yahoo',
{
headers: {
Authorization: "Bearer MYAUTHORIZATIONTOKENHERE",
Accept: "application/json"
}
}; data = await response.json()
message.channel.send(data.number)
}}
the current error im facing is
[Sun Sep 12 2021 21:26:16] [LOG] Initializing Startup!
[Sun Sep 12 2021 21:26:16] [ERROR] (node:12692) UnhandledPromiseRejectionWarning: C:\Users\manof\Desktop\Main Bots\Celly Bot\commands\buy.js:8
const response = curl "https://5sim.net/v1/user/buy/activation/cambodia/any/discord",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
all help would be greatly appreciated!

can you try doing
const response = curl('https://5sim.net/v1/user/buy/activation/cambodia/any/yahoo', {
headers: {
Authorization: "Bearer MYAUTHORIZATIONTOKENHERE",
Accept: "application/json"
}
});
const data = await response.json();
Because your syntax is incorrect.

You're trying to call the function curl.get in the curl package and hence it requires you to call it via () this is a simple syntax error and can be fixed like so:
let data;
const response = curl.get('https://5sim.net/v1/user/buy/activation/cambodia/any/yahoo',
{
headers: {
Authorization: "Bearer MYAUTHORIZATIONTOKENHERE",
Accept: "application/json"
}
});
data = await response.json()
I suggest you to read the examples given here

Related

ERR_ABORTED 403 (Forbidden)

I'm trying to build a program which can control my Sonos Speaker. I'm following the instructions over at https://developer.sonos.com/build/direct-control/authorize/.
The first step - getting the authorization code - is working as intended but the problem I'm facing arises when I try to send the authorization code per POST request with the following code:
const redirect_uri = "https%3A%2F%2Fsonoscontrol-c4af4.web.app%2F";
const redirect_url = "https://sonoscontrol-c4af4.web.app/";
const client_id = // API Key (deleted value for safety)
const secret = // Secret (deleted value for safety)
const auth_url = `https://api.sonos.com/login/v3/oauth?client_id=${client_id}&response_type=code&state=testState&scope=playback-control-all&redirect_uri=${redirect_uri}`;
function GetAccessToken() {
var target_url = "https://api.sonos.com/login/v3/oauth/access/";
var authCode = GetAuthCode();
var encoded_msg = btoa(client_id + ":" + secret); // base64-encodes client_id and secret using semicolon as delimiter
var params = "grant_type=authorization_code" + `&code=${authCode}` + `&redirect_uri=${redirect_uri}` + `&client_id=${client_id}`;
var myHeaders = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Authentication': `Basic {${encoded_msg}}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});
fetch(target_url, {
method: "POST",
mode: "no-cors",
credentials: "include",
redirect: "follow",
headers: myHeaders,
body: params
}).then((res) => {
console.log(res.responseText);
}).catch(function(error) {
console.log(error);
});
}
function GetAuthCode() {
return (new URLSearchParams(location.search)).get('code'); // returns authorization code from URL
}
Now I get the following error when trying to send the POST request: POST https://api.sonos.com/login/v3/oauth/access/ net::ERR_ABORTED 403 (Forbidden)
I am using a Cloud Firebase app as webserver and added the correct redirect URL in the credentials.
What could be the problem for this error message?
I noticed a couple of things in your code that may be causing your 403 Forbidden issue.
Your "Authentication" header should be "Authorization", eg: "Authorization: Basic {YourBase64EncodedClientId:SecretGoesHere}"
Your "target_url" has a trailing slash, it should be "https://api.sonos.com/login/v3/oauth/access"
Your query parameters "params" are including the client_id on the token request, which isn't necessary, though I don't believe it will cause an error.
Addressing the above should hopefully resolve your issue!
Thanks,
-Mark

RabbitMQ HTTP API returning 401 (Unauthorized)

Using RabbitMQ localhost and trying to use his API.. when i Call from postman it's work fine.
But i'm trying to use this API inside my app code and I'm getting 401 error:
const test = {
count: 5,
ackmode: 'ack_requeue_true',
encoding: 'auto',
truncate: 50000
}
testPost() {
fetch('http://localhost:15672/api/queues/%2F/QA.MOBILE/get', {
method: 'post',
mode: 'no-cors',
body: JSON.stringify(test),
headers: {Authorization: 'Basic ' + btoa('guest:guest'), Accept: 'application/json', 'Content-Type': 'application/json'}
});
}
POST http://localhost:15672/api/queues/%2F/QA.MOBILE/get net::ERR_ABORTED 401 (Unauthorized)
I'm missing something?
thanks
I just had this problem myself. Even though my issue was not CORS related, I thought I would document the issue here in case future readers have the same problem.
My issue was that I was not correctly base64ing the user credentials. From a browser you can just call any of the RabbitMQ API endpoints like this:
http://somename:somepassword#servername:15672/api/cluster-name
But when calling it programatically, you need to remove the credentials from the url and base 64 them instead.
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "http://servername:15672/api/cluster-name"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"somename:somepassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var response = httpClient.SendAsync(request).Result;
if (response.IsSuccessStatusCode == true)
{
string jsonContent = response.Content.ReadAsStringAsync().Result;
}
}
}
The above code is C# but it would be the same process for Java, etc.

How to use fetch() in react native with headers json?

Postman output:
HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type: application/json
Date: Fri, 08 Feb 2019 12:13:36 GMT
{"status":1,"msg":"success","celeb":[{"id":1,"name":"Test Name"....
I'm getting my json in postman like this.
when I try to use fetch(), I'm getting an error json parse error, unknown identifier HTTP
fetch('https://myurl/fetch')
.then((response) => response.json())
.then((response) => {...}
let func = async () => {
const url = 'https://myurl/fetch';
const data = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: await AsyncStorage.getItem(ACCESS_TOKEN), /*or whatever you have on your api*/
}),
};
const response = await fetch(url , data);
const responseData = await response.json();
console.log(responseData);
}
I believe you are missing to set to configure you API call method, headers, mode etc... Check out Fetch Examples for a better explanation.

Upload a file but set Content-Type

I got Watson Speech-to-Text working on the web. I am now trying to do it on react native but am getting errors on the file upload part.
I am using the HTTPS Watson API. I need to set the Content-Type otherwise Watson returns a error response. However in react-native, for the file upload to work, we seem to need to set 'Content-Type' to 'multipart/form-data'. Is there anyway to upload a file in react-native while setting Content-Type to 'audio/aac'?
The error Watson API gives me if I set 'Content-Type': 'multipart/form-data' is:
{
type: "default",
status: 400,
ok: false,
statusText: undefined,
headers: Object,
url: "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true",
_bodyInit: Blob,
_bodyBlob: Blob
}
The response body is:
{
"code_description": "Bad Request",
"code": 400,
"error": "No JSON object could be decoded"
}
Here is my code (full code is here - gist.github.com ):
const ext = 'aac';
const file_path = '/storage/emulated/0/Music/enter-the-book.aac';
data.append('file', {
uri: `file://${file_path}`,
name: `recording.${ext}`,
type: `audio/${ext}`
}, `recording.${ext}`);
const response = await fetch('https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true', {
method: 'POST',
headers: {
// 'Content-Type': `audio/${ext}`,
'Content-Type': 'multipart/form-data',
'X-Watson-Authorization-Token': token
},
body: data
});
console.log('watson-stt::getResults - response:', response);
if (response.status !== 200) {
const error = await response.text();
throw new Error(`Got bad response "status" (${response.status}) from Watson Speach to Text server, error: "${error}"`);
}
Here is a screenshot of the error I get when I set 'Content-Type': 'audio/aac':
Thanks so much to DanielBolanos and NikolayShmyrev this is the solution I used:
This code is for iOS so I recorded the audio as blah.ulaw BUT the part_content_type is aduio/mulaw;rate=22050 this is very important to use mulaw even though file ext is ulaw. An interesting note: I couldn't play the blah.ulaw file on my macOS desktop.
Also note that you MUST NOT set Content-Type to multipart/form-data this will destroy the boundary.
Also Bluemix requires rate in the part_content_type for mulaw
const body = new FormData();
let metadata = {
part_content_type: 'audio/mulaw;rate=22050' // and notice "mulaw" here, "ulaw" DOES NOT work here
};
body.append('metadata', JSON.stringify(metadata));
body.append('upload', {
uri: `file://${file_path}`,
name: `recording.ulaw`, // notice the use of "ulaw" here
type: `audio/ulaw` // and here it is also "ulaw"
});
const response = await fetch('https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true', {
method: 'POST',
headers: {
// 'Content-Type': 'multipart/form-data' // DO NOT SET THIS!! It destroys the boundary and messes up the request
'Authorization': `Basic ${btoa(`${USERNAME}:${PASSWORD}`)}`
},
body
});
According to the documentation for multipart requests the request should be:
curl -X POST -u "{username}":"{password}"
--header "Transfer-Encoding: chunked"
--form metadata="{
\"part_content_type\":\"audio/flac\",
\"timestamps\":true,
\"continuous\":true}"
--form upload="#audio-file1.flac"
"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
So the content-type should be multipart/form-data, you can specify aac as "part_content_type": "audio/aac".
The big problem you have is that audio/aac is not in supported formats. You might probably need another codec.

Angular 2 Token: Response for preflight has invalid HTTP status code 400

I have an Angular2/TypeScript application running i Visual Studio Code.
An API running in VS 2015. This is the API project: http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
I can use the API and create new users, but when I try to login(Use the Token function), then I get the following error:
XMLHttpRequest cannot load https://localhost:44305/Token. Response for preflight has invalid HTTP status code 400
The header looks like this:
Request URL:https://localhost:44305/Token
Request Method:OPTIONS
Status Code:400
Remote Address:[::1]:44305
Response Headers
cache-control:no-cache
content-length:34
content-type:application/json;charset=UTF-8
date:Wed, 10 Aug 2016 19:12:57 GMT
expires:-1
pragma:no-cache
server:Microsoft-IIS/10.0
status:400
x-powered-by:ASP.NET
x-sourcefiles:=?UTF-8?B?QzpcQ2hlY2tvdXRcQVBJXzJ2czJcQVBJXEFQSVxUb2tlbg==?=
Request Headers
:authority:localhost:44305
:method:OPTIONS
:path:/Token
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, sdch, br
accept-language:en-US,en;q=0.8,da;q=0.6,nb;q=0.4
access-control-request-headers:authorization
access-control-request-method:POST
cache-control:no-cache
origin:http://evil.com/
pragma:no-cache
referer:http://localhost:3000/signin
user-agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
My angular service looks like this:
loginAccount(account: Account): Observable<string> {
var obj = { Email: account.Email, Password: account.Password, grant_type: 'password' };
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions( {method: RequestMethod.Post, headers: headers });
let body = JSON.stringify(obj);
console.log('loginAccount with:' + body);
return this._http.post('https://localhost:44305/Token', body, options)
.map(this.extractData)
.catch(this.handleError);
}
When I use the AJAX funtions that a in the API project: http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api then it works fine ?? What am I doing wrong in the Angular POST request ?
I found the solution. Thanks to the comments on the API site: http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
I had to set the correct header for application/x-www-form-urlencoded; charset=UTF-8 and serialize the object i posted. I canĀ“t find an Angular serializer method, so I made my own(copy from another stackoverflow site) in JavaScript.
Here is the final call when the user login on the API and request a token, when using Angular2 & TypeScript:
loginAccount(account: Account): Observable<string> {
var obj = { UserName: account.Email, Password: account.Password, grant_type: 'password' };
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
let options = new RequestOptions( {method: RequestMethod.Post, headers: headers });
let body = this.serializeObj(obj);
return this._http.post('https://localhost:44305/Token', body, options)
.map(this.extractData)
.catch(this.handleError);
}
private serializeObj(obj) {
var result = [];
for (var property in obj)
result.push(encodeURIComponent(property) + "=" + encodeURIComponent(obj[property]));
return result.join("&");
}
I was also facing same issue from last week and searched on google and stack overflow but all solutions in vein. but after lot of reading and investigation we have found below solution, we were facing issue in only POST method,GET called successfully.
Instead of directly passing Options we need to first stringify option object like JSON.stringify(options)
CreateUser(user:IUser): Observable<void> {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:22736/api/Employee/Create', **JSON.stringify(options)**)
.map((res: Response) => {
return res.json();
})
.catch(this.handleError);
}
It worked for me, Hope it will help others too.
I found that in angular 4 you have to make it like this.
public addQuestion(data: any): Observable<Response> {
let headersObj = new Headers();
headersObj.set('Content-Type', 'application/x-www-form-urlencoded');
let requestArg: RequestOptionsArgs = { headers: headersObj, method: "POST" };
var params = new URLSearchParams();
for(let key of Object.keys(data)){
params.set(key,data[key]);
};
return this.http.post(BaseApi.endpoint + 'Question', params.toString(), requestArg)
.map((res: Response) => res.json().data);
}
Another native solution is by using HttpParams class and it's toString() method:
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
let options = { headers, observe: 'response' };
const body = new HttpParams()
.set('grant_type', 'password')
.set('username', accountInfo.username)
.set('password', accountInfo.password);
return this._http.post('https://localhost:44305/Token', body.toString(), options)
toString() - Serialize the body to an encoded string, where
key-value pairs (separated by =) are separated by &s.
Note. Also it works without setting the headers