botmasterai / botmaster-socket.io

The socket.io Botmaster integration
MIT License
8 stars 8 forks source link

Catch socket io connect event #9

Closed willemevenwel closed 6 years ago

willemevenwel commented 6 years ago

As this plain example from socketio's web site describes:

const socket = io('http://localhost');

socket.on('connect', () => {
console.log(socket.connected); }

);

How would i catch this 'connect' event server side, using Botmaster?

jdwuarin commented 6 years ago

The socket.io server is exposed via: bot.ioServer. So you can use that just as you would with any standard socket.io server to listen for a connect event server side. Actually, you can see that's what gets done in the code here: https://github.com/botmasterai/botmaster-socket.io/blob/c3c32d0bce2410c1df483c2c528af9ac57e9ce6b/lib/socket.io_bot.js#L71

Cheers,

HtH

willemevenwel commented 6 years ago

This helps a lot thanks!

Thanks for answering so promptly, sorry for the pedantic questions, I tried to read through the docs to keep my questions to a minimum.

Last question upon
`this.ioServer.on('connection', (socket) => { how would i get the specific client id which just connected the value parse from the query string: botmasterUserId

Regards

willem

jdwuarin commented 6 years ago

You can see how I do that in the function at this line: https://github.com/botmasterai/botmaster-socket.io/blob/c3c32d0bce2410c1df483c2c528af9ac57e9ce6b/lib/socket.io_bot.js#L92

The same should work for you given a socket object.

I'm wondering though why you need access to this ID, as it will be accessible in every request your bot will get inupdate.sender.id as per the Readme where I mention:

On the first line, we call: var socket = io('?botmasterUserId=wantedUserId');. This effectively opens up a socket connection with our backend by making a request to something like this: io('ws://localhost:3000?botmasterUserId=wantedUserId');. Here as you can see, we are setting a query param called botmasterUserId to "wantedUserId". This is done because we want to make sure that when we are getting updates in our backend, the update.sender.id part will be what we set it to here and not anything else (by default the randomly allocated socket.id value). This is even more important when your users can connect from different clients and you want to make sure the botmaster reply is propagated to all the clients.

I.e. any backend user creation that may need to happen could happen upon receiving a request from some new botmasterUserId

willemevenwel commented 6 years ago

I just want to log the exact time that a given botmasterUserId connected to the chat bot server. This same id is a primary key to retrieve the chat history etc. So its important for me to get hold of it.