Twitter video upload with NodeJS - javascript

I am trying to post a video using Twitter modules in NodeJS but I am getting an error - Error 202 “Your credentials do not allow access to this resource”.
Here a snippet of code, it is missing the APPEND and FINISH calls etc but would have expected not to receive an error 202?
Has anyone managed to upload a video using JavaScript than can give me some guidance? I have tried to research and tried several different options.
T.post('media/upload', {
media: data,
encoding: 'base64',
command: 'INIT',
total_bytes: getFilesizeInBytes(image)
}, function(error, media, response) {
if (!error) {
var status = {
status: message
};
if(media) status['media_ids'] = media.media_id_string;
T.post('statuses/update', status, function(error, tweet, response) {
if(!error) console.log(' -- message sent');
else console.log(error);
});
} else {
console.log(error);
}
});

Related

My bot replies is being marked as "show additional replies..."

Hi I’m building a bot which posts message from students as a campaign on twitter. I wrote the bot using Node.js
My problem is that the bot replies with a phrase (it’s not a link or a media, just text without explicit words) but Twitter is marking these messages as “Show additional replies, including those that may contain offensive content”.
I marked the button on privacy setting for “Display media that may contain sensitive content” but it doesn't seem to change it. Anybody knows what’s wrong?? I appreciate your help.
Here is a screenshot of how the replies are showing for reference:
Image with sensitive content block
Here is some of the code I'm using to post the tweets:
Bot.get('search/tweets', { q: '#orgullopucp -filter:retweets', since_id: last_mention_id }, function(err, data, response) {
if (err){
console.log('Error!', err);
return false;
}
/* Next, let's search for Tweets that mention our bot, starting after the last mention we responded to. */
if (data.statuses.length) {
console.log(data.statuses);
data.statuses.forEach(function(status) {
console.log(status.id_str);
console.log(status.text);
console.log(status.user.screen_name);
/* Now we can respond to each tweet. */
Bot.post('statuses/update', {
possibly_sensitive:false,
status: '#' + status.user.screen_name + ' ' + random_from_array(sentences),
in_reply_to_status_id: status.id_str
}, function(err, data, response) {
if (err){
/* TODO: Proper error handling? */
console.log('Error!', err);
}
else{
fs.writeFile(__dirname + '/last_mention_id.txt', status.id_str, function (err) {
/* TODO: Error handling? */
if(err){
console.log('Error!', err);
}
});
}
});
});
} else {
/* No new mentions since the last time we checked. */
console.log('No new mentions...');
}
});
});
response.sendStatus(200);

Why doesn't 'res.send()' redirect upon completion of MongoDB 'deleteMany' call?

My call to Express's 'res.send(string)' fails to redirect and display the provided text upon completion of a call to MongoDB's 'deleteMany()'. The database is cleared and no error is thrown.
I've tried adjusting my call to 'res' with 'res.json()' and such, but to no avail. I've also adjusted the ordering my other calls within the 'delete' request, with no success. My inclination is that my issue is related to Promises.
.delete(function(req, res){
//if successful response will be 'complete delete successful'
console.log('deleting all documents');
MongoClient.connect(MONGODB_CONNECTION_STRING, { useNewUrlParser: true }, (connectErr, client) => {
if(connectErr) res.json({ "error": "Error connecting to database!", "error": connectErr });
const db = client.db('test-db');
try {
db.collection('testCollection2').deleteMany({}, (err) => {
if(err) throw err;
res.send('complete delete successful');
console.log('complete delete successful');
});
} catch(err) {
console.log('Complete delete failed!');
res.send('Complete delete failed!');
}
});
});
Despite not redirecting or receiving an error message, I still receive the console.log output confirming the successful call to 'deleteMany'. I'm not sure how to test this in more depth, since I'm using Glitch for the project. Thanks in advance for any help!

403: Quota Error: User Rate Limit Exceeded witht Batch Request

I'm getting the error code "403: Quota Error: User Rate Limit Exceeded" with batch requests to the Google Analytics Management API (v3) pointing to management views (profiles): patch.
I'm aware of quota limits from the docs, which suggest that I hit the write limit of 50 queries/day.
However, this only happens with batch requests. Individual calls like this:
gapi.client.analytics.management.profiles.patch({
"accountId": "someAccountId",
"webPropertyId": "some propertyID",
"profileId": "someProfileId",
"resource": {
"excludeQueryParameters" : "someTestValue"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
});
still come through with a 200er code.
For the batch request, the first request added to the batch always succeeds, whereas all following ones throw the 403er.
The code for batch requests looks something like this:
function runQuery(someArray) {
var batch = gapi.client.newBatch();
var request = function (query) {
return gapi.client.request({
//For demonstration purposes only. Imagin "path" gets adapted to the individual API calls
"path" : "https://www.googleapis.com/analytics/v3/management/accounts/accountId/webproperties/webPropertyId/profiles/profileId",
"method" : "PATCH",
"body" : {
"excludeQueryParameters" : "someTestValue1"
}
});
}
//Add to Batch
someArray.forEach(function(el) {
batch.add(request(el))
});
//Execute Batch Request
batch
.then(function(response) {
console.log("Response", response);
},
function(err) { console.error("Execute error", err);
}
);
};
The full error message is this:
body: "{"error":{"errors":[{"domain":"global","reason":"userRateLimitExceeded","message":"Quota Error: User Rate Limit Exceeded."}],"code":403,"message":"Quota Error: User Rate Limit Exceeded."}}"
I'm guessing you are hitting the 1.5 qps write limit. Since you are sending more than 2 writes at a time in a batch. So the first write succeed then all other writes fails.

Get image as buffer from URL

I have spent couple of hours trying to get image data as a buffer, search results lead me to using "request" module, others suggestions lead to using other modules in higher version of node, which I cannot use because we depend on node v 6.11 so far.
Here are my trials:
request(imageURL).pipe(fs.createWriteStream('downloaded-img-
1.jpg')).on('close', function () {
console.log('ok');
});
request(imageURL, function (err, message, response) {
fs.writeFile('downloaded-img-2.jpg', response, 'binary', function (err) {
console.log('File saved.');
});
fs.writeFile('downloaded-img-3.jpg', chunks, 'binary', function (err) {
console.log('File saved.');
})
resolve(response);
})
.on('data', function (chunk) {
chunks.push(chunk);
})
.on('response', function (response) {
});
});
The "downloaded-img-1.jpg" gets downloaded correctly, but I have to avoid saving the file on disk, then read it as a stream, it's a PRD environment constraint. So the next option is to use image data, as demonstrated by "downloaded-img-2.jpg" and "downloaded-img-3.jpg", by waiting for the "response" or the hand-made "chunks", the problem is that these 2 images are always corrupted, and I don't know why?
What is the point behind all of that? I am trying to add the image behind the URL in a zip file, and the zip lib I use (js-zip) accepts buffer as an input. Any ideas why I am not getting the "chunks" or the "response" correctly?
I've tested the code below in Node 6.9.2, it will download an image as a buffer. I also write the buffer to a file (just to test all is OK!), the body object is a buffer containing the image data:
"use strict";
var request = require('request');
var fs = require('fs');
var options = {
url: "https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Hubble2005-01-barred-spiral-galaxy-NGC1300.jpg/1920px-Hubble2005-01-barred-spiral-galaxy-NGC1300.jpg",
method: "get",
encoding: null
};
console.log('Requesting image..');
request(options, function (error, response, body) {
if (error) {
console.error('error:', error);
} else {
console.log('Response: StatusCode:', response && response.statusCode);
console.log('Response: Body: Length: %d. Is buffer: %s', body.length, (body instanceof Buffer));
fs.writeFileSync('test.jpg', body);
}
});

How to handle error in Angular Controller from MongoDB database update/delete in Express?

I am trying to figure out how to handle an error when deleting or updating a document in MongoDB in Angular JS?
I have the following route in Node/Express:
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
//log the reason for the error
res.status(code || 500).json({
"error": message
});
}
app.delete("/polls/:id", auth, function(req, res) {
db.collection(POLLS_COLLECTION).deleteOne({
_id: new ObjectID(req.params.id), userID: req.user.id
//userID must match the req.user.id from Passport to make sure the poll belongs to the user
}, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to delete poll");
} else {
res.status(204).end();
}
});
});
The following in an Angular JS controller:
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
alert("Error deleting poll");
console.log(response);
})
};
deleteThisPoll in the controller calls a deletePoll service that sends a a request to the route:
this.deletePoll = function(pollId){
var url = "/polls/" + pollId;
return $http.delete(url);
};
What I want is to alert "Error deleting poll" from the Angular controller when the database delete is not executed (because for example user is not authenticated or the poll doesnt belong to the user) and "Poll Deleted" when the delete was successfull.
However: the error callback is never used and the app always alerts "Poll deleted!" no matter if the document was deleted or not deleted.
Doesn't my route send an error response when the delete was not executed and will it not hit my Angular error callback?
You can do like code below
Put this HTML code where you want to show error message :
<div style="color:red;">
{{error}}
</div>
In your angular js controller :
$scope.deleteThisPoll = function(){
Polls.deletePoll($routeParams.pollId)
.then(function(response){
alert("Poll deleted!");
var url = "/mypolls/" + $scope.userID;
$location.path(url);
}, function(response){
$scope.error="Any error message you like to show";
console.log(response);
})
};
If your API return an error. you can catch it like this :
Polls.deletePoll($routeParams.pollId).then(function(response) {
//SUCCESS CODE
}).catch(function(error) {
//NOTIFY ERROR
//NotifyService.display(error);
console.log(error);
});
thanks guys. I found out that MongoDB for some reason always returns a result object even when there was no delete/update. I solved this by checking for the result.deletedCount propety that is set to 1 or 0. Like so:
if(err){
res.status(500).end();
}
if(result.deletedCount === 0){
res.status(404).end();
//error handling in Angular error callback
} else {
res.status(204).end();
//error handling in Angular success callback
}
});
});
this makes sure that not always a 204 is send whether or not the delete was successfull.

Categories

Resources