Connect quickblox chat server from node.js - node.js

Please tell me the whether I have called the methods in is correct format or not
var QB=require('quickblox');
var QuickBlox = require('quickblox').QuickBlox;
var QBChat = require('quickblox');
var QB2 = new QuickBlox();
var params, chatUser, chatService;
params = {email: 'raji#gmail.com', password: ''};
QB.init(21000,'NBRQfWA2OWwfBre','GNwMJzqPL8wZb8g');
// QuickBlox session creation
QB.createSession(params, function(err, result) {
if (err) {
console.log(err.detail);
} else {
console.log(result.user_id);
console.log(params.password)
chatUser = {
id: result.user_id,
pass: params.password
};
console.log(chatUser)
connectChat(chatUser);
}
});
function connectChat(chatUser) {
chatService = new QB.chat({
onConnectFailed: onConnectFailed,
onConnectSuccess: onConnectSuccess,
onConnectClosed: onConnectClosed,
onChatMessage: onChatMessage
});
// connect to QB chat service
console.log("connection")
//connection = new Strophe.Connection(CHAT.bosh_server);
chatService.connect(chatUser);
}
function onConnectFailed() {}
// Connection is success
function onConnectSuccess() {}
// Connection is closed
function onConnectClosed() {}
var recipientID = 978816;
var message = {
body: 'Hello world',
type: 'chat'
};
// send user message
//chatService.sendMessage(recipientID, 'hello');
// getting messages
function onChatMessage(senderID, message) {}
I'm getting the following error
TypeError: object is not a function
at connectChat (C:\Program Files\nodejs\chat1.js:33:16)
at C:\Program Files\nodejs\chat1.js:28:3
at C:\Program Files\nodejs\node_modules\quickblox\js\modules\qbAuth.js:52:27
at Request.requestCallback [as _callback] (C:\Program Files\nodejs\node_modu
les\quickblox\js\qbProxy.js:126:16)
at Request.self.callback (C:\Program Files\nodejs\node_modules\request\reque
st.js:373:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request.<anonymous> (C:\Program Files\nodejs\node_modules\request\request
.js:1318:14)
at Request.EventEmitter.emit (events.js:117:20)
at IncomingMessage.<anonymous> (C:\Program Files\nodejs\node_modules\request
\request.js:1266:12)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
How to connect quickblox chat server from node.js. I'm trying to connect using chat plugin but can't even create chat instance. It shows the error

Related

Send/Reply direct message using Twitter API v2

I have a nodejs application, I need to add a feature were I can send a survey using direct messaging on twitter to the user and when the user replies, the application will send the next question and so on (preferably if I can add options for the replies expected).
What I'm stuck in currently is sending the direct message, the examples that I found seem to work with the old version and not working with Twitter API v2.
One sample code that I tried but also not working is below:
const Twit = require('twit');
const config = require('./config.js');
const T = new Twit(config);
const stream = T.stream('user');
const SendMessage = user => {
const { screen_name, name } = user.source;
const obj = {
screen_name: screen_name,
text: "Hi there!"
};
timeout = 5000;
setTimeout(() => {
T.post("direct_messages/new", obj)
.catch(err => {
console.error("error", err.stack);
})
.then(result => {
console.log(`Message sent successfully To ${screen_name}!`);
});
}, timeout);
};
user = new Object;
user.source = { screen_name: 'name', name: 'userDisplayedName' };
SendMessage(user);
Output Error:
throw er; // Unhandled 'error' event
^
Error: Bad Twitter streaming request: 404
at Object.exports.makeTwitError (/../node_modules/twit/lib/helpers.js:74:13)
at Request.<anonymous> (/../node_modules/twit/lib/streaming-api-connection.js:96:29)
at Request.emit (events.js:327:22)
at IncomingMessage.<anonymous> (/../node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:421:28)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on StreamingAPIConnection instance at:
at Request.<anonymous> (/../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:80:21) {
code: null,
allErrors: [],
twitterReply: '',
statusCode: 404
}
does anyone know how to send a direct message using Twitter API v2 with Nodejs?
At the time of writing this answer, the Direct Message APIs have not been migrated to v2, so you will need to continue to use Twitter API v1.1 for Direct Messages.
The error here is not in sending, but in receiving -> Bad Twitter streaming request -> 404. This is because the code you have found is trying to use the Twitter user streams API, which was removed in 2018. These have been replaced with the Account Activity API (webhooks). You will need to build an app that receives webhook events for Direct Messages, and then post replies. This is all in v1.1 of the API.

Getting "InternalServerError" while using Mongo with Node js

I am new to Node js programming. Trying to write a simple user create using.. code along with the stack track is given below. Appreciate any help as to what is causing this..
users-add.mjs:
'use strict';
const util = require('util');
const restify = require('restify-clients');
console.log("starting...");
var client = restify.createJsonClient({url: 'http://localhost:'+process.env.PORT, version: '*'});
console.log("starting...2 ");
client.basicAuth('them', 'D4ED43C0-8BD6-4FE2-B358-7C0E230D11EF');
client.post('/create-user', { username: "me", password: "w0rd", provider: "local",
familyName: "GUD", givenName: "RG", middleName: "Ud", emails: [], photos: []},
(err, req, res, obj) => {
console.log("starting...4 ");
if(err) {
console.log("starting...5");
console.error(err.stack);
}
else {
console.log("starting...6");
console.log('Created ' + util.inspect(obj));
}
});
console.log("starting...3 ");
Here is the error I'm getting.. Surprisingly the server side code is able to insert the record into MongoDB, and yet I get this error..
InternalServerError: {}
at Object.createHttpErr (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/helpers/errors.js:91:26)
at ClientRequest.onResponse (/Users/raviguduru/node-web-dev/chapter8/users/node_modules/restify-clients/lib/HttpClient.js:309:26)
at Object.onceWrapper (events.js:300:26)
at ClientRequest.emit (events.js:210:5)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:583:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:115:17)
at Socket.socketOnData (_http_client.js:456:22)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
Pls help.
This problem is solved now.. The internal server error comes when we have MongoDBClient calls not wrapped in try/catch blocks. After I included try/catch blocks, they went away.

Howo to get IPP endpoint

I'm using the ipp npm module to send a print job from a google cloud function. I believe I have set up the printer correctly but I don't know how I'm supposed to know the exact uri for sending the print job.
The printer model is Brother MFC-L3770CDW
Here is how my settings look in the web view for the printer configuration.
And here is the function code.:
var ipp = require('ipp');
var PDFDocument = require('pdfkit');
var doc = new PDFDocument;
doc.text("Hello World");
var buffers = [];
doc.on('data', buffers.push.bind(buffers));
doc.on('end', function () {
var printer = ipp.Printer("https://10.0.0.55:443");
var file = {
"operation-attributes-tag":{
"requesting-user-name": "User",
"job-name": "Print Job",
"document-format": "application/pdf"
},
data: Buffer.concat(buffers)
};
printer.execute("Print-Job", file, function (err, res) {
if(err) {
console.log(err);
}
else{
console.log("Printed: "+res.statusCode);
}
});
console.log('executing');
});
doc.end();
console.log('finished executing');
I have tried various uris such as
https://10.0.0.55:631
https://10.0.0.55:443
https://10.0.0.55:631/ipp
https://10.0.0.55:631/ipp/printer
Sometimes I get an error like:
"Error: socket hang up
at TLSSocket.onHangUp (_tls_wrap.js:1148:19)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at TLSSocket.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)
code: 'ECONNRESET',
path: null,
host: '10.0.0.55',
port: '631',
localAddress: undefined }"

How to search via elasticsearch in Node.js?

I have indexed data from firebase via elasticSearch .
And Its Working Properly .
Now I am Searching data via firebase below cloud function :
exports.searchIt = functions.database.ref('/search/{key}')
.onUpdate(event => {
let key=event.params.key;
let elasticSearchConfig = functions.config().elasticsearch;
const esClient = new elastic.Client({
host: 'http://35.198.221.164',
log: 'error'
});
console.log('client Created');
let searchBody = {
size: 20,
from: 0,
query: {
match_all: {}
}
};
esClient.search({index: 'offers', body: searchBody})
.then(results => {
console.log('Successfully Entered');
results.hits.hits.forEach(
(hit, index) => console.log(hit)
)
})
.catch(console.error);
});
But this gives error below :
textPayload: "{ Error: Not Found at respond
(/user_code/node_modules/elasticsearch/src/lib/transport.js:307:15) at
checkRespForFailure
(/user_code/node_modules/elasticsearch/src/lib/transport.js:266:7) at
HttpConnector.
(/user_code/node_modules/elasticsearch/src/lib/connectors/http.js:159:7)
at IncomingMessage.bound
(/user_code/node_modules/elasticsearch/node_modules/lodash/dist/lodash.js:729:21)
at emitNone (events.js:91:20) at IncomingMessage.emit
(events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at
_combinedTickCallback (internal/process/next_tick.js:80:11) at process._tickDomainCallback (internal/process/next_tick.js:128:9)
And on changing host to any other it still create client.
Why is this happening?

Node.js Node-Crawler TypeError : undefined is not a function

I try use node-crawler project https://github.com/sylvinus/node-crawler
here is code is used (it's in doc)
var Crawler = require("crawler");
var url = require('url');
var c = new Crawler({
maxConnections : 10,
// This will be called for each crawled page
callback : function (error, result, $) {
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
$('a').each(function(index, a) {
var toQueueUrl = $(a).attr('href');
c.queue(toQueueUrl);
});
}
});
// Queue just one URL, with default callback
c.queue('http://joshfire.com');
when i run this code it's give this error :
TypeError: undefined is not a function
at Object.Crawler.callback (/home/app/app.js:10:9)
at Crawler._onContent (/home/app/node_modules/crawler/lib/crawler.js:461:17)
at Request._callback (/home/app/node_modules/crawler/lib/crawler.js:351:18)
at Request.self.callback (/home/app/node_modules/crawler/node_modules/request/request.js:236:22)
at Request.emit (events.js:98:17)
at Request.<anonymous> (/home/app/node_modules/crawler/node_modules/request/request.js:1142:14)
at Request.emit (events.js:117:20)
at IncomingMessage.<anonymous> (/home/app/node_modules/crawler/node_modules/request/request.js:1096:12)
at IncomingMessage.emit (events.js:117:20)
at _stream_readable.js:944:16
node.js version i use : v0.10.37
// Update your node.js, node-crawler and try this code instead of your callback function
callback : function (error, res, done) {
var $ = res.$;
$('a').each(function(index, a) {
var toQueueUrl = $(a).attr('href');
c.queue(toQueueUrl);
});
}

Resources