How can i check if a twitch channel exists? - discord.js

Im trying to write a code that checks for twitch channels if they exist or not, i tried using request but the statusCode its allways 200
request(`https://www.twitch.tv/${args[1]}`, function(error, response, body){
console.log('statusCode', response.statusCode)
edit: tried using twith api kraken but doesn't seem to work, if i use existing channels its the same response.
request('https://api.twitch.tv/kraken/channels/' + args[1], function(channel, response) {
console.log(channel)
if (channel == null) {
return console.log("doesnt exists")
} else {
return console.log("Exists")
}

The status code of an HTML request is the status code of the request, not what was requested. 200 means that the request went through fine without problems.
You could either look through the response and body of the request or try the Kraken, which I'm not very familiar with. Have you looked through the docs?
The docs about this part use this syntax:
curl -H 'Accept: application/vnd.twitchtv.v5+json' \
-H 'Client-ID: uo6dggojyb8d6soh92zknwmi5ej1q2' \
-X GET 'https://api.twitch.tv/kraken/channels/44322889'
Your syntax probably works fine. The issue is probably that the response isn't null, but rather something like an empty object.
What response ARE you getting? What is your console output if you use console.log(channel);
console.log(response);
I hope I could help a bit.

Related

Codenameone Execute Postman REST Call

Using Postman I am able to successfully connect to my login server and receive an access token.
I would like to replicate this call within my CN1 code
This is my postman script:
cURL
curl --location --request POST 'https://myloginserver.com/accounts/login' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'username=myusername' \
--data-urlencode 'password=mypassword'
Java
Unirest.setTimeouts(0, 0);
HttpResponse<String> response = Unirest.post("https://myloginserver/accounts/login")
.header("Content-Type", "application/x-www-form-urlencoded")
.field("username", "myusername")
.field("password", "mypassword")
.asString();
And this is my CN1 code
ConnectionRequest getTokenConnReq = null;
try {
getTokenConnReq = new ConnectionRequest("https://myloginserver.com/accounts/login");
getTokenConnReq.setPost(true);
getTokenConnReq.addRequestHeader("Content-Type","application/x-www-form-urlencoded");
getTokenConnReq.setHttpMethod("POST");
getTokenConnReq.setRequestBody("username=myusername&password=mypassword");
getTokenConnReq.setFailSilently(true);
getTokenConnReq.setCookiesEnabled(false);
NetworkManager.getInstance().addToQueueAndWait(getTokenConnReq);
result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(getTokenConnReq.getResponseData()), DocumentInfo.ENCODING_UTF8));
return result;
} catch (Exception err22) {
System.err.println(err22);
return null;
}
Unfortunately my responses vary from the 300's to the 400's depending on how I tweak the code.
Please advise how I get this working in CN1?
(I think that it may have something to do with Cookies as I do see Postman adding cookies to the call in the background)
Any help will be appreciated.
Thanks
I would suggest using the Rest API which is much easier to use for these sort of calls:
Rest.post("https://myloginserver.com/accounts/login")
.contentType("application/x-www-form-urlencoded")
.queryParam("username", username)
.queryParam("password", password)
.fetchAsJsonMap(result -> {
Map parsedJson = result.getResponseData();
// key/value pairs from the resulting JSON
});

How to get correct $http error code, instead of -1?

I use $http to retrieve data from server. In case error happen, all statusCode = -1. I cannot get correct errorCode to handle in client. I don't have permission to update server code.
$http(options).then(function (response) {
if (response.status === 200) {
resolve(response.data);
} else {
exceptionHandler(response);
}
}, function (error) {
exceptionHandler(error);
});
console.log is put on exceptionHandler function.
Please help me get correct error code. Many thanks.
In the responses you have shown, the 404 error is available as error.status but the other two responses were denied access by your browser when it performed the preflight OPTIONS request.
In that case the browser returns a status of -1 to indicate that the request was aborted. There is no HTTP status code for your request because it was never sent. The status 500 shown in the console log is not made available to any javascript code.
You should handle a status of -1 as indicating that no response was received from the server, either because it was never sent (this case), or because it was sent but timed out.

Quickbook No apptoken detected; (PHP)errorCode=003102; statusCode=401

I am new in quickbooks API implementation, I am always getting one error No apptoken detected; errorCode=003102; statusCode=401 when I am doing API call for customer add etc.
I am giving my steps, please look over that.
My sandbox info like that
Consumer Key: qyprdffbBBInX4a82jG73Mreyy96tC
Consumer Secret: IgpJzJrYvb9FmmdB7A0ECDGHG62Cp7dqVWjfMTvU
Access Token: qyprdlo3WrK0KhGZMTeA857AuKiVy2eaAmpXsRvG3jycYaMQ
Access Token Secret: TdPGpcUI8AiAdWFiCyb8jAAygH16bzU7VRGaspx4
I am Using PHP.
First I have generated oauth_signature.
$URL =
rawurlencode('https://sandbox-quickbooks.api.intuit.com/v3/company/408554291/customer');
$method = 'POST'; $parameter =
rawurlencode('oauth_consumer_key=qyprdffbBBInX4a82jG73Mreyy96tC&oauth_nonce=BlyqIBbv3R4T0P4qglAv1RjoYisMZk1449659733&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1449659733&oauth_token=qyprdlo3WrK0KhGZMTeA857AuKiVy2eaAmpXsRvG3jycYaMQ&oauth_version=1.0');
$ukey =
rawurlencode('IgpJzJrYvb9FmmdB7A0ECDGHG62Cp7dqVWjfMTvU').'&'.rawurlencode('TdPGpcUI8AiAdWFiCyb8jAAygH16bzU7VRGaspx4');
$hasmac = hash_hmac("sha1", $BaseURL,$ukey,1);
and My oauth_signature is jZ8JhECy/e0kpPbUdZp/o/EUC7U=
When i call API with this oauth_signature, i am getting Error 'No apptoken detected; errorCode=003102; statusCode=401'
My CURL call like this
curl -X POST -H 'Content-Type: application/json, Authorization: OAuth
oauth_token=qyprdlo3WrK0KhGZMTeA857AuKiVy2eaAmpXsRvG3jycYaMQ,oauth_consumer_key=qyprdffbBBInX4a82jG73Mreyy96tC,oauth_signature_method=HMAC-SHA1,oauth_timestamp=1449659733,oauth_version=1.0,oauth_nonce=BlyqIBbv3R4T0P4qglAv1RjoYisMZk1449659733,oauth_signature=jZ8JhECy/e0kpPbUdZp/o/EUC7U='
-d '{"data": [{"BillAddr":{"Line1":"86 A Topsia","City":"Kolkata","Country":"India","CountrySubDivisionCode":"WB","PostalCode":"700102"},"Title":"Mr.","GivenName":"ApurbaK","MiddleName":"Kumar","FamilyName":"ApurbaK","PrimaryPhone":{"FreeFormNumber":"564545465"},"PrimaryEmailAddr":{"Address":"apurbahazra12#navsoft.in"}}]}'
'https://sandbox-quickbooks.api.intuit.com/v3/company/408554291/customer'
Please look over that.
Thanks,
Apurba
Firstly, you don't want to be doing this yourself -- use a library. OAuth is complex, and implementing it yourself is going to be a hairy process, rife with errors.
Go grab a library:
https://github.com/consolibyte/quickbooks-php
Follow the quick-start guide linked there, and benefit from the examples:
https://github.com/consolibyte/quickbooks-php/tree/master/docs/partner_platform/example_app_ipp_v3
With that said, if you do decide to write it yourself, make sure you follow the OAuth spec:
https://www.rfc-editor.org/rfc/rfc5849
So far, the issues I immediately see with your implementation are:
You can't hard-code the timestamp like this: &oauth_timestamp=1449659733 The timestamp should be ever-changing, and set to the currenty timestamp.
You can't hard-code a nonce like this: &oauth_nonce=BlyqIBbv3R4T0P4qglAv1RjoYisMZk1449659733 The nonce has to change with every single request so this is going to fail after your first request.
You haven't normalized your request parameters / sorted them, per the spec.
This is the incorrect way to specify multiple headers with cURL: -H 'Content-Type: application/json, Authorization: OAuth .... Please see the cURL docs: http://curl.haxx.se/docs/manpage.html#-H
In the code you posted, you haven't actually set $BaseURL anywhere, so right now you're signing an empty string (unless you forgot to paste some code somewhere?)
What is $ukey set to? It doesn't appear to be defined in your code anywhere (did you forget to paste some code in?)

Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter..?

I am trying to send a PUT request to an amazonS3 presigned URL. My request seems to be called twice even if I only have one PUT request. The first request returns 200 OK, the second one returns 400 Bad Request.
Here is my code:
var req = {
method: 'PUT',
url: presignedUrl,
headers: {
'Content-Type': 'text/csv'
},
data: <some file in base64 format>
};
$http(req).success(function(result) {
console.log('SUCCESS!');
}).error(function(error) {
console.log('FAILED!', error);
});
The 400 Bad Request error in more detail:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>InvalidArgument</Code>
<Message>Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified</Message>
<ArgumentName>Authorization</ArgumentName>
<ArgumentValue>Bearer someToken</ArgumentValue>
<RequestId>someRequestId</RequestId>
<HostId>someHostId</HostId>
</Error>
What I don't understand is, why is it returning 400? and What's the workaround?
Your client is probably sending an initial request that uses an Authorization header, which is being responded with a 302. The response includes a Location header which has a Signature parameter. The problem is that the headers from the initial request are being copied into the subsequent redirect request, such that it contains both Authorization and Signature. If you remove the Authorization from the subsequent request you should be good.
This happened to me, but in a Java / HttpClient environment. I can provide details of the solution in Java, but unfortunately not for AngularJS.
For the Googlers, if you're sending a signed (signature v4) S3 request via Cloudfront and "Restrict Bucket Access" is set to "Yes" in your Cloudfront Origin settings, Cloudfront will add the Authorization header to your request and you'll get this error. Since you've already signed your request, though, you should be able to turn this setting off and not sacrifice any security.
I know this may be too late to answer, but like #mlohbihler said, the cause of this error for me was the Authorization header being sent by the http interceptor I had setup in Angular.
Essentially, I had not properly filtered out the AWS S3 domain so as to avoid it automatically getting the JWT authorization header.
Also, the 400 "invalid argument" may surface as a result of wrong config/credentials for your S3::Presigner that is presigning the url to begin with. Once you get past the 400, you may encounter a 501 "not implemented" response like I did. Was able to solve it by specifying a Content-Length header (specified here as a required header). Hopefully that helps #arjuncc, it solved my postman issue when testing s3 image uploads with a presigned url.
The message says that ONLY ONE authentication allowed. It could be that You are sending one in URL as auth parameters, another - in headers as Authorization header.
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:scavenger_inc_flutter/utils/AuthUtils.dart';
import 'package:scavenger_inc_flutter/utils/URLS.dart';
class ApiClient {
static Dio dio;
static Dio getClient() {
if (dio == null) {
dio = new Dio();
dio.httpClientAdapter = new CustomHttpAdapter();
}
return dio;
}
}
class CustomHttpAdapter extends HttpClientAdapter {
DefaultHttpClientAdapter _adapter = DefaultHttpClientAdapter();
#override
void close({bool force = false}) {
_adapter.close(force: force);
}
#override
Future<ResponseBody> fetch(RequestOptions options,
Stream<List<int>> requestStream, Future<dynamic> cancelFuture) async {
String url = options.uri.toString();
if (url.contains(URLS.IP_ADDRESS) && await AuthUtils.isLoggedIn()) {
options.followRedirects = false;
options.headers.addAll({"Authorization": await AuthUtils.getJwtToken()});
}
final response = await _adapter.fetch(options, requestStream, cancelFuture);
if (response.statusCode == 302 || response.statusCode == 307) {
String redirect = (response.headers["location"][0]);
if(!redirect.contains(URLS.IP_ADDRESS)) {
options.path = redirect;
options.headers.clear();
}
return await fetch(options, requestStream, cancelFuture);
}
return response;
}
}
I disallowed following redirects.
Used the response object to check if it was redirected.
If it was 302, or 307, (HTTP Redirect Codes), I resent the request after clearing the Auth Headers.
I used an additioal check to send the headers only if the path contained my specific domain URL (or IP Address in this example).
All of the above, using a CustomHttpAdapter in Dio. Can also be used for images, by changing the ResponseType to bytes.
Let me know if this helps you!
I was using django restframework. I applied Token authentication in REST API. I use to pass token in request header (used ModHeader extension of Browser which automatically put Token in Authorization of request header) of django API till here every thing was fine.
But while making a click on Images/Files (which now shows the s3 URL). The Authorization automatically get passed. Thus the issue.
Link look similar to this.
https://.s3.amazonaws.com/media//small_image.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXXXXXXXXXXXXXXXX%2F20210317%2Fap-south-XXXXXXXXFaws4_request&X-Amz-Date=XXXXXXXXXXXXXXX&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
I lock the ModHeader extension to pass Authorization Token only while making rest to REST API and not while making resquest to S3 resources. i.e. do not pass any other Authorization while making request to S3 resource.
It's a silly mistake. But in case it helps.
Flutter: if you experience this with the http dart package, then upgrade to Flutter v2.10!
Related bugs in dart issue tracker:
https://github.com/dart-lang/sdk/issues/47246
https://github.com/dart-lang/sdk/issues/45410
--> these has been fixed in dart 2.16, which has been shipped with Flutter v2.10!
https://medium.com/dartlang/dart-2-16-improved-tooling-and-platform-handling-dd87abd6bad1

Trying to insert Contact, getting 400 Bad Request

I'm attempting to insert a Contact to the Mirror API, but I keep getting a 400 Bad Request error.
My code to build the request is as follows:
Http h = new Http();
HttpRequest firstPost = new HttpRequest();
firstPost.setEndpoint('https://www.googleapis.com/mirror/v1/contacts');
firstPost.setMethod('POST');
firstPost.setHeader('Authorization', 'Bearer ' +access_token);
System.debug('Bearer '+access_token);
firstPost.setBody(postBody);
firstPost.setHeader('Content-Type', 'application/json');
The postBody is hardcoded for now as:
{
"kind":"mirror#contact",
"id":"harold",
"displayName":"Harold Penguin",
"imageUrls": ["https://developers.google.com/glass/images/harold.jpg"]
}
I've confirmed the access_token is being sent. Any ideas? Thanks!
You don't need (and should not specify) the kind attribute when doing contact.insert. This is assumed (you better be inserting a contact), and I can see how it might be causing problems if you provide it. Notice that https://developers.google.com/glass/v1/reference/contacts/insert does not list it as an attribute, and the Raw HTTP example does not show it.

Resources