I’ve written code to write a chat message to anyone who has sent a chat message to your business, or has the Wix app installed. (My problem is that they don’t get notifications for those those messages, which I’m putting in a feature request)
This code requires that you set up a private Database called ‘ChatChannels’ first. You can leave it empty because it will fill up through an events listener. When it has filled up with chat channels, you can start to send chat messages through calling sendChatMessage(messageText, userId)
First create backend code chat.jws and put this code in it
import wixChat from 'wix-chat-backend';
import wixData from 'wix-data';
let options = {
"suppressAuth": true,
"suppressHooks": false
};
export function saveChannel(participantId, channelId) { // see events.js
let toSave = {
"_id": participantId,
"channelId": channelId
};
wixData.save("ChatChannels", toSave, options)
}
export function sendChatMessage(messageText, userId) {
return findChatChannel(userId)
.then((channelId) => {
console.log("sending message through " + channelId)
wixChat.sendMessage({
"messageText": messageText,
"channelId": channelId,
"sendAsVisitor": false,
"metadata": {"type:": "notification"}
})
})
.then(() => {
console.log("Chat message sent");
})
.catch((error) => {
console.log(error);
});
}
function findChatChannel(userId) {
return wixData.query("ChatChannels")
.eq("_id", userId)
.find()
.then((results) => {
if (results.items.length > 0) {
let firstItem = results.items[0];
let channelId = firstItem.channelId
return channelId
} else {
let em = "no channel found for user"
throw em
}
})
.catch((err) => {
let errorMsg = err;
console.log(errorMsg)
});
}
To save chat channels to the database, we need to put some code in events.js The database will start to fill up once someone starts a chat, or installs the Wix Mobile App. Each chat message updates the database with the associated channel. So, at this to events.js
import wixChat from 'wix-chat-backend';
import {saveChannel} from 'backend/chat'
export function wixChat_onMessage(event) {
const participantId = event.participantId;
const channelId = event.channelId;
const direction = event.direction
if (direction === "VisitorToBusiness"){saveChannel(participantId, channelId)}
}
We only want to save the channel when a message is sent in the ‘direction’ visitor to business, because we save the Id that gets saved to the database is the sender.