XMPP Node.js Client – Demo


root@RAMESH-LENOVO:~/xmpp-echo-bot# cat index.js
//const ddg = require('ddg')
ddg = require('ddg');
const Client = require('node-xmpp-client')
, ltx = Client.ltx
const options = {
 jid: 'bot@localhost',
 password: 'password',
 host: 'localhost',
 resource: 'echo'
}
const client = new Client(options)
client.once('online', (connectionDetails) => {
 console.log('We are connected!')
 console.log(connectionDetails)
 sendPresence()
})
const sendPresence = () => {
 const stanza = new ltx.Element('presence')
 .c('show')
 .t('available')
 console.log('Sending presence: ' + stanza.toString())
 client.send(stanza)
}
const NS_CHAT_STATE = 'http://jabber.org/protocol/chatstates'
const sendChatState = (to, state) => {
 const stanza = new ltx.Element('message', { type: 'chat', to })
 stanza.c(state, { xmlns: NS_CHAT_STATE })
 console.log('Sending chat state: ' + stanza.toString())
 client.send(stanza)
}
const handleMessage = (stanza) => {
 const query = stanza.getChildText('body')
 if (!query) return /* Not a chat message */
 const from = stanza.attr('from')
 sendChatState(from, 'active')
 sendChatState(from, 'composing')
 ddg.query(query, (error, data) => {
 result = null
 if (error) {
 result = 'Unfortunately we could not answer your request'
 } else {
 if (!data.RelatedTopics[0]) {
 result = 'Sorry, there were no results!'
 } else {
 const item = data.RelatedTopics[0]
 result = item.FirstURL + '\n' + item.Text
 }
 }
 const reply = new ltx.Element(
 'message',
 { type: 'chat', to: from }
 )
 reply.c('body').t(result)
 .up()
 .c('inactive', { xmlns: NS_CHAT_STATE })
 console.log('Sending response: ' + reply)
 client.send(reply)
 })
}
const handlePresence = (stanza) => {
 if (false === stanza.attr('subscribe')) {
 return /* We don't handle anything other than a subscribe */
 }
 const reply = new ltx.Element(
 'presence',
 { type: 'subscribed', to: stanza.attr('from') }
 )
 client.send(reply)
}
client.on('stanza', (stanza) => {
 if (true === stanza.is('message')) {
 return handleMessage(stanza)
 } else if (true === stanza.is('presence')) {
 return handlePresence(stanza)
 }
})
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s