Error 401 in windows command prompt? - javascript

When use npm run dev, which scripts the "node app.js" to run. But when I try to run it, I get this error code:
C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter>npm run dev
> Tweeter#1.0.0 dev C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter
> node app.js
Error: Status Code: 401
at Request.<anonymous (C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter\node_modules\twitter\lib\twitte
r.js:274:28)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestResponse (C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter\node_modules\request\request.js:
1074:10)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming]
(_http_client.js:473:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
I also get this error when I try to run sudo at all when I use bash in the cmd:
ryryfasch#LAPTOP-9TPB1OJ6:/mnt/c/Users/rfasc/Dropbox/Hackathon/HackCuTwitter$ sudo i
sudo: unable to resolve host LAPTOP-9TPB1OJ6
I have tried looking up many fixes and can't figure it out. Thanks.
Here is my app.js file:
var twitterpack = require('twitter');
var tokens = {
consumer_key: '----------SaaqAe9yVvr30CF',
consumer_secret: '---------------oK7Dfj3zoiZ2nUOTBWUjP4DqtGXIlzzbxbOY',
token_key: ' -----------------3N6RZJeOtJeH8ZhrursJUQlAqCycHqxbl',
token_secret: '---------------2QYwSSZStETF7Mr2mBikHYCTTqodV'
}
var Twitter = new twitterpack(tokens);
Twitter.stream('statuses/filter', {track: 'hey'}, function(stream) {
stream.on('data', function(stream){
console.log(tweet.text);
var meanReply = {status: "hey #" + tweet.user.screen_name}
Twitter.post('statuses/update', meanReply, function(error, tweetReply, response){
if(error) {console.log(error) /*&&db.collection('errors', error.text)*/};
console.log(tweetReply.text)}
);
});
stream.on('error', function(error) {
console.log(error);
});
});

Related

nodejs and twitter api error ' Error: Bad Twitter streaming request: 404 '

Hello i want to create a bot who will automatically send a message to the men who follow you
var Twit = require('twit');
var config = require('./config');
var T = new Twit(config);
var stream = T.stream('user');
stream.on('follow', followedMessage);
function followedMessage(eventMsg) {
console.log('+1 follow');
var fs = require('fs');
var json = JSON.parse(eventMsg);
fs.writeFile("tweet.json", json)
}
but when i start the app i got this error
throw er; // Unhandled 'error' event
^
Error: Bad Twitter streaming request: 404
at Object.exports.makeTwitError (C:\Users\guill\Desktop\Programmation\welcomemessage-V1.0.0\node_modules\twit\lib\helpers.js:74:13)
at Request.<anonymous> (C:\Users\guill\Desktop\Programmation\welcomemessage-V1.0.0\node_modules\twit\lib\streaming-api-connection.js:96:29)
at Request.emit (events.js:327:22)
at IncomingMessage.<anonymous> (C:\Users\guill\Desktop\Programmation\welcomemessage-V1.0.0\node_modules\request\request.js:1076:12)
at Object.onceWrapper (events.js:421:28)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on StreamingAPIConnection instance at:
at Request.<anonymous> (C:\Users\guill\Desktop\Programmation\welcomemessage-V1.0.0\node_modules\twit\lib\streaming-api-connection.js:99:14)
at Request.emit (events.js:327:22)
[... lines matching original stack trace ...]
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: null,
allErrors: [],
twitterReply: '',
statusCode: 404
}
someone can help me ?
Replace:
var stream = T.stream('user');
With
var stream = T.stream('statuses/filter', { track: '#<your_twitter_username>' });
Thanks to Asaolu Elijah Response on github issue
i dont think that T.stream('user'); is still working now, i have a mission now to built a bot for a client and i had the same problem,
Try to use T.stream('statuses/filter'), or T.stream('sample')

Webhook to discord url from firebase cloud function

I'm using firebase realtime database and cloud functions. The goal is on a create event in realtime database to send a message to Discord webhook.
I'm getting a 400 status error and can't work out how to get around it.
Here is my code:
const WEBHOOK_URL = 'MY DISCORD WEBHOOK URL';
exports.webhook = functions.database.ref('{sessionId}').onCreate(async (snap) => {
const sessionData = snap.val();
const response = await request({
uri: WEBHOOK_URL,
method: 'POST',
json: true,
body: sessionData.dateCreated,
resolveWithFullResponse: true,
});
if (response.statusCode >= 400) {
throw new Error(`HTTP Error: ${response.statusCode}`);
}
console.log('SUCCESS! Posted', snap.ref);
And the error message:
Error ->
StatusCodeError: 400 - {"_misc":["Only dictionaries may be used in a DictType"]}
at new StatusCodeError (/srv/node_modules/request-promise-core/lib/errors.js:32:15)
at Request.plumbing.callback (/srv/node_modules/request-promise-core/lib/plumbing.js:104:33)
at Request.RP$callback [as _callback] (/srv/node_modules/request-promise-core/lib/plumbing.js:46:31)
at Request.self.callback (/srv/node_modules/request/request.js:185:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/srv/node_modules/request/request.js:1161:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (/srv/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickDomainCallback (internal/process/next_tick.js:219:9)

I cannot post using request-promise

My problem i that I get an error telling me I can't make post request. I use the insertDocuments function to insert messages into a database. I am attempting to make a promise oriented version of the 'mongolab-data-api' node.js module. I apologize if my question is confusing
//This is a function in a class that handles all mlab related things
var rp = require('request-promise')
var insertDocuments = options => {
if (!options.database || !options.collectionName || !options.documents) throw new Error('Database name, Collection Name, and Document(s) are required')
var opt = {
uri: `https://api.mongolab.com/api/1/databases/${options.database}/collections`,
qs: {
apiKey: this.apiKey
},
method: 'POST',
body: {
documents: options.documents
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
return rp(opt)
}
var options = {
database: 'lexybase',
collectionName: 'evy-history',
documents: msg
}
insertDocuments(options)
I get this error:
Unhandled rejection StatusCodeError: 405 - {"message":"POST not allowed."}
at new StatusCodeError (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request-promise-core/1.1.1/node_modules/request-promise-core/lib/errors.js:32:15)
at Request.plumbing.callback (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request-promise-core/1.1.1/node_modules/request-promise-core/lib/plumbing.js:104:33)
at Request.RP$callback [as _callback] (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request-promise-core/1.1.1/node_modules/request-promise-core/lib/plumbing.js:46:31)
at Request.self.callback (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request/2.88.0/node_modules/request/request.js:185:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request/2.88.0/node_modules/request/request.js:1161:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request/2.88.0/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
Edit: As it turns out, the problem was that collectionName need3d to be specified and it shoul have been
body: options.documents
instead of
body: {
documents:options.documents
}
You are missing the collection name in uri:
uri: https://api.mongolab.com/api/1/databases/${options.database}/collections
should be:
uri: https://api.mongolab.com/api/1/databases/${options.database}/collections/{collectionName}
just change the collectionName
405 is returned from mongolab API

How to connect Mongo Atlas Database in Lambda function with Mongoose

I am using Serverless framework to deploy my backend to API Gateway and AWS Lambda.
Here is my serverless.yml for this specific lambda function.
It is a cron job that runs every hour.
cron:
handler: handler.transferHandler
events:
- schedule: rate(1 hour)
Now when I test on localhost it works perfectly. But when I deploy to aws I get the following error:
MongoDB connection error. Please make sure MongoDb is running. { MongoError: failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]
at Pool.<anonymous> (/var/task/node_modules/mongodb-core/lib/topologies/server.js:336:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/pool.js:280:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/connection.js:189:49)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at connectErrorNT (net.js:1021:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
name: 'MongoError',
message: 'failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]' }
Here is my function in my handler.js:
exports.transferHandler = function transferHandler(event, context) {
context.callbackWaitsForEmptyEventLoop = false;
mongoose.connect(mongoString, {useMongoClient: true});
const db = mongoose.connection;
db.on("error", (err) => {
console.log("MongoDB connection error. Please make sure MongoDb is running.", err);
process.exit();
});
db.once('open', () => {
BookingModel
.find({})
.then((bookings) => {
...
})
.catch((err) => {
console.log(err);
})
.finally(() => {
db.close();
});
});
};
After 2 weeks of being stuck on this, I learned that I needed to specify my environment variables in my serverless.yml for it to work. My functions were never connecting to the database because my mongo string was never set in lambda. Hope this helps someone.
provider:
name: aws
runtime: nodejs6.10
stage: production
region: us-west-1
environment:
MONGODB_URL: ${env:MONGODB_URL}
S3_BUCKET: ${env:S3_BUCKET}
S3_BUCKET_REPORT: ${env:S3_BUCKET_REPORT}
STRIPE_CLIENT_ID: ${env:STRIPE_CLIENT_ID}
STRIPE_PUBLIC_KEY: ${env:STRIPE_PUBLIC_KEY}
STRIPE_SECERET_KEY: ${env:STRIPE_SECERET_KEY}
JWT_SECRET: ${env:JWT_SECRET}
SEND_BIRD_TOKEN: ${env:SEND_BIRD_TOKEN}
SEND_BIRD_APP_ID: ${env:SEND_BIRD_APP_ID}
MANDRILL_APIKEY: ${env:MANDRILL_APIKEY}

Node fsmkdirSync error

I have the following folder structure:
Inside of CacheModule.js i have the following code:
socket.on('saveUserCache', function (obj, user_id) {
var jsonOutput = JSON.stringify(obj);
if (!fs.existsSync('./cacheObjects/' + user_id)) {
fs.mkdirSync('./cacheObjects/' + user_id, 0777, function (err) {
if (err) {
console.log(err);
}
});
}
fs.writeFile('./cacheObjects/' + user_id + '/cache.json', jsonOutput, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
The idea behind this is to check if the users folder exists (if not) create a new folder and then write to a file.
However im getting the following error:
Error: ENOENT: no such file or directory, mkdir './cacheObjects/125'
at Error (native)
at Object.fs.mkdirSync (fs.js:794:18)
at Socket.<anonymous> (/var/www/project/app_server/costum_modules/CacheModule.js:10:16)
at emitTwo (events.js:87:13)
at Socket.emit (events.js:172:7)
at Socket.onevent (/var/www/project/app_server/node_modules/socket.io/lib/socket.js:330:8)
at Socket.onpacket (/var/www/project/app_server/node_modules/socket.io/lib/socket.js:290:12)
at Client.ondecoded (/var/www/project/app_server/node_modules/socket.io/lib/client.js:193:14)
at Decoder.Emitter.emit (/var/www/project/app_server/node_modules/socket.io/node_modules/socket.io-parser/node_modules/component-emitter/index.js:134:20)
at Decoder.add (/var/www/project/app_server/node_modules/socket.io/node_modules/socket.io-parser/index.js:247:12)
at Client.ondata (/var/www/project/app_server/node_modules/socket.io/lib/client.js:175:18)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at Socket.onPacket (/var/www/project/app_server/node_modules/socket.io/node_modules/engine.io/lib/socket.js:99:14)
at emitOne (events.js:82:20)
at WebSocket.emit (events.js:169:7)
Can anyone tell me why this is happening. it looks like its sending mkdir with the string. Also i have given the right permissions (so it is not lacking permissions)

Categories