This is a tutorial on how to use the [[Universal Connector node|Universal-Connector-node]] to support the Dialog chat platform.
We’ll use the Dialog Bot SDK: open a terminal window in the Node-RED home dir (generally $HOME/.node-red) and install it with
npm install @dlghq/[email protected]
Install the 2.0.2
version, newer version is not compatible with the code below. Edit the settings.js to make the library available in Node-RED in the global context
{ // ... functionGlobalContext: { // ... environment: 'development', DialogBot: require('@dlghq/dialog-bot-sdk') }}
Node-RED must be restarted now.
Download the Dialog client and use the Dialog Bot to create a new chatbot
/bot new mybotnickname mybotname
Support table
and grab the access token. Next add a Universal Connector node
and store the token in the configuration
Support table
Then add an [[Extend Node|Extend-node]], this is where the magic happens. The strategy is to make the Dialog Bot up and running in Node-RED and discovery what payload is sent for each message and then implement all necessary middlewares to in the Extend node
.
Add an Extend node
and select Universal Connector from the drop down:
const DialogBotSDK = node.context().global.get('DialogBot');node.chat.onStart(function() { var chatServer = this; var options = chatServer.getOptions(); options.connector = new DialogBotSDK.Bot(options.token); options.connector.onMessage(function(peer, message) { chatServer.receive(message); }); return true;});
The onStart is executed once at the startup and it’s the right place to initialize the Dialog Bot library using the access token stored in the connector’s configuration (this.getOptions()). When a message is received by the .onMessage()_ callback is injected in the middlewares chain with the method chatServer.receive(), if you’re unsure about what a middleware chain is, check [[here|Extend-node]].
Just send a test message from the Dialog client and inspect the received payload, it should look like this
{
rid: '46016707201745159',
mid: '4f4176c0-cbf0-11e8-db0a-f43a15df867f',
sortKey: '1539109361708',
sender: {
peer: { type: 'user', id: 246093853, key: 'u246093853' },
type: 'user',
title: 'Guido Bellomo',
userName: null,
avatar: null,
bigAvatar: null,
placeholder: 'yellow'
},
isOut: false,
date: '20:22',
fullDate: 2018-10-09T18:22:41.708Z,
state: 'unknown',
isOnServer: true,
content: {
type: 'text',
text: 'test message',
media: [],
extensions: []
},
attachment: null,
reactions: [],
sortDate: 1539109361.708,
isEdited: false
}
In order to make the Universal connector to work we have to extract the chatId from the payload, in the payload above a good candidate is the peer key in the sender hash