diff --git a/Readme.md b/Readme.md index c55afcf..3a2cf62 100644 --- a/Readme.md +++ b/Readme.md @@ -74,6 +74,53 @@ socket.on('connect', function() { ``` +## With multiplexed socket.io + +#### Server +```js +const Botmaster = require('botmaster'); +const SocketioBot = require('botmaster-socket.io'); +const botmaster = new Botmaster(); +const io = require('socket.io')(botmaster.server); // this is required for socket.io. You can set it to another node server object if you wish to. But in this example, we will use the one created by botmaster under the hood + +const socketioSettings = { + id: 'SOME_BOT_ID_OF_YOUR_CHOOSING', + socket_io: io.of('/news'), // a custom namespace +}; + +const socketioBot = new SocketioBot(socketioSettings); +botmaster.addBot(socketioBot); + +botmaster.use({ + type: 'incoming', + name: 'my-middleware', + controller: (bot, update) => { + return bot.reply(update, 'Hello world!'); + } +}); +``` + +#### Client +```js +const io = require('socket.io-client'); + +const socket = io('ws://localhost:3000/news'); //namespace used in server + +socket.on('connect', function() { + const update = { + message: { + text: 'Hey there botmaster!' + } + }; + + socket.send(update); +}); + +``` + + + + ## The Botmaster Socket.io bot Socket.io is a great library that allows developers to write apps using webSockets (with fallbacks to http long-polling and others when webSockets aren't available on the client). You can read more about it on their own website here: http://socket.io. diff --git a/lib/socket.io_bot.js b/lib/socket.io_bot.js index 044daed..4ca8de2 100644 --- a/lib/socket.io_bot.js +++ b/lib/socket.io_bot.js @@ -23,12 +23,16 @@ class SocketioBot extends BaseBot { throw new Error('bots of type \'socket.io\' are expected to have \'id\' in their settings'); } this.id = settings.id; - - if (!settings.server) { - throw new Error('bots of type \'socket.io\' must be defined with \'server\' in their settings'); + + if (settings.server) { + this.server = settings.server; + } else if(settings.socket_io){ + this.socket_io = settings.socket_io; + } else { + throw new Error('bots of type \'socket.io\' must be defined with \'server\' or \'socket_io\' in their settings'); } - this.server = settings.server; + this.receives = settings.receives || { text: true, @@ -65,8 +69,12 @@ class SocketioBot extends BaseBot { }; } - __setupSocketioServer() { - this.ioServer = io(this.server); + __setupSocketioServer(settings) { + if(this.socket_io){ + this.ioServer = this.socket_io; + } else { + this.ioServer = io(this.server); + } this.ioServer.on('connection', (socket) => { debug(`new socket connected with id: ${socket.id}`);