@blendvision/chatroom-javascript-sdk
v2.1.0
Published
BlendVision Chatroom JavaScript SDK
Downloads
852
Readme
BlendVision Chatroom JavaScript SDK
BlendVision Chatroom provides real-time messaging, admin-controlled bans, message deletion, and pinned announcements.
Installing
1. Get your chatroom token
Integrator could get chatroom token and refresh token with BlendVision API.
2. Add dependency
via NPM
npm install @blendvision/chatroom-javascript-sdk@latest --save
via CDN
<script type="module">
import 'https://unpkg.com/@blendvision/chatroom-javascript-sdk/index.min.js';
</script>
Configure BlendVision JavaScript SDK
1. Initialize the Chatroom
The init()
method initializes the settings required for BlendVision Chatroom.
Integrator could call the init()
method on app startup, preferably in the index file.
via NPM
import { Chatroom } from '@blendvision/chatroom-javascript-sdk';
// For TypeScript Integrator
import { ChatroomConfig } from '@blendvision/chatroom-javascript-sdk/type';
const chatToken = 'YOUR_CHATROOM_TOKEN';
const host = 'https://api.one.blendvision.com';
const refreshToken = 'YOUR_CHATROOM_REFRESH_TOKEN';
Chatroom.init({ chatToken, host, refreshToken }).then(
(data: ChatroomConfig) => {
console.log('Initialization completed successfully', data);
},
(error) => {
console.log('Initialization failed with error:', error);
}
);
via CDN
<script type="module">
import 'https://unpkg.com/@blendvision/chatroom-javascript-sdk/index.min.js';
const chatToken = 'YOUR_CHATROOM_TOKEN';
const host = 'https://api.one.blendvision.com';
const refreshToken = 'YOUR_CHATROOM_REFRESH_TOKEN';
const { Chatroom } = window.BlendVisionChatroomSDK;
Chatroom.init({ chatToken, host, refreshToken }).then(
(data) => {
console.log('Initialization completed successfully', data);
},
(error) => {
console.log('Initialization failed with error:', error);
}
);
</script>
Responses
The response data type for the API call is structured as follows:
interface User {
id: string;
deviceId: string;
customName: string;
isAdmin: boolean;
}
interface BlockedUser {
blockedUser: User;
actionTaker: string;
}
interface TextMessage {
id: string;
text: string;
sender: User;
}
interface PinnedMessage {
textMessage: TextMessage;
actionTaker: string;
}
interface ViewerInfo {
enabled: boolean;
count: number;
version: number;
updatedAt: string;
}
interface CustomCounter {
key: string;
value: number;
version: number;
updatedAt: string;
disabled: boolean;
}
interface ChatroomType {
id: string;
muted: boolean;
blockedUsers: BlockedUser[];
pinnedMessages: PinnedMessage[];
viewerInfo: ViewerInfo;
customCounters: CustomCounter[];
createdAt: string;
updatedAt: string;
}
interface ChatroomConfig {
user: User;
chatroom: ChatroomType;
}
Cleanup with disconnect()
method
The chatroom needs to be cleaned up to prevent memory leaks and ensure optimal browser performance. Integrator can achieve this by using the disconnect()
method to destroy the chatroom instance.
Chatroom.disconnect();
2. Handle Received Messages with register()
// For TypeScript Integrator
import { ReceivedMessage, ReceivedMessageText } from '@blendvision/chatroom-javascript-sdk/type';
import { IConnackPacket, IDisconnectPacket, ErrorWithReasonCode } from 'mqtt';
Chatroom.register({
// Connection Status
onConnect: (packet: IConnackPacket) => {
console.log('The chatroom is successfully connected', packet);
},
onDisconnect: (packet: IDisconnectPacket) => {
console.log('The chatroom is disconnected', packet);
},
onReconnect: () => {
console.log('The chatroom is reconnecting');
},
onError: (error: Error | ErrorWithReasonCode) => {
console.log('The chatroom failed to connect', error);
},
// Interaction Message
onTextReceived: (textMessage: ReceivedMessageText) => {
console.log('onTextReceived', textMessage);
},
onMuteReceived: (message: ReceivedMessage) => {
console.log('onMuteReceived', 'The chatroom is muted by', message.user.customName);
},
});
Connection Status
Integrator could check the Packet type here. If there is a connection error, the reason code could be found in here.
Interaction Message
The basic interaction message type is:
interface User {
id: string;
deviceId: string;
customName: string;
isAdmin?: boolean;
}
enum InteractionType {
Text = 'INTERACTION_TYPE_TEXT',
Custom = 'INTERACTION_TYPE_CUSTOM',
CustomCounterUpdate = 'INTERACTION_TYPE_CUSTOM_COUNTER_UPDATE',
Mute = 'INTERACTION_TYPE_MUTE',
Unmute = 'INTERACTION_TYPE_UNMUTE',
Pin = 'INTERACTION_TYPE_PIN_MESSAGE',
Unpin = 'INTERACTION_TYPE_UNPIN_MESSAGE',
Block = 'INTERACTION_TYPE_BLOCK_USER',
Unblock = 'INTERACTION_TYPE_UNBLOCK_USER',
Delete = 'INTERACTION_TYPE_DELETE_MESSAGE',
ViewerInfoEnabled = 'INTERACTION_TYPE_VIEWER_INFO_ENABLED',
ViewerInfoDisabled = 'INTERACTION_TYPE_VIEWER_INFO_DISABLED',
ViewerInfoUpdate = 'INTERACTION_TYPE_VIEWER_INFO_UPDATE',
Broadcast = 'INTERACTION_TYPE_BROADCAST_UPDATE',
}
interface ReceivedMessage {
id: string;
type: InteractionType;
user: User;
sentAt: string; // Timestamp indicating when the message was received by the SDK.
receivedAt: string; // Timestamp indicating when the message reached the server.
}
Text Message
It is required for the register() function, since the message needs to be handled by the integrator.
| Function | Required | Interaction Type | Description |
| -------------- | -------- | ----------------------- | ----------------- |
| onTextReceived | Required | INTERACTION_TYPE_TEXT
| The text message. |
interface ReceivedMessageText extends ReceivedMessage {
type: InteractionType.Text;
text: string;
}
Custom Message
| Function | Required | Interaction Type | Description |
| ---------------- | -------- | ------------------------- | ------------------- |
| onCustomReceived | Optional | INTERACTION_TYPE_CUSTOM
| The custom message. |
interface ReceivedMessageCustom extends ReceivedMessage {
type: InteractionType.Custom;
value: string; // usually structure in JSON format
}
Custom Counter Message
The message would be sent with the batch setting by default, the batching interval could be adjusted here.
| Function | Required | Interaction Type | Description |
| ----------------------- | -------- | ------------------------- | --------------------------- |
| onCustomCounterReceived | Optional | INTERACTION_TYPE_CUSTOM
| The custom counter message. |
interface ReceivedMessageCustomCounter extends ReceivedMessage {
type: InteractionType.Custom;
key: string; // the key that set up when create chatroom
value: string; // usually structure in JSON format, would be empty string if no value provided
}
Custom Counter Update
The actual value of the counter would be updated by the function.
Since the integrator could update the counter via the chatroom API, the SDK would received the update event by this function.
| Function | Required | Interaction Type | Description |
| ----------------------------- | -------- | ---------------------------------------- | ---------------------------------------------- |
| onCustomCounterUpdateReceived | Optional | INTERACTION_TYPE_CUSTOM_COUNTER_UPDATE
| Update the custom counter's value or disabled. |
interface ReceivedMessageCustomCounterUpdate extends ReceivedMessage {
type: InteractionType.CustomCounterUpdate;
key: string; // Indicate the key of counter
value: string; // Indicate the actual amount of counter
version: number;
updatedAt: string;
disabled: boolean; // Would be true if the counter key has been removed
}
Mute the chatroom
| Function | Required | Interaction Type | Description |
| ---------------- | -------- | ------------------------- | ---------------------------------------------------- |
| onMuteReceived | Optional | INTERACTION_TYPE_MUTE
| The chatroom is muted, viewers can not send message. |
| onUnmuteReceived | Optional | INTERACTION_TYPE_UNMUTE
| The chatroom is unmuted. |
No extra information would be sent with the mute / unmute message.
Pin / Unpin a message
| Function | Required | Interaction Type | Description |
| ---------------------- | -------- | -------------------------------- | ------------------------ |
| onPinMessageReceived | Optional | INTERACTION_TYPE_PIN_MESSAGE
| The message is pinned. |
| onUnpinMessageReceived | Optional | INTERACTION_TYPE_UNPIN_MESSAGE
| The message is unpinned. |
interface User {
id: string;
deviceId: string;
customName: string;
isAdmin?: boolean;
}
interface ReceivedMessagePin extends ReceivedMessage {
type: InteractionType.Pin | InteractionType.Unpin;
pinUnpinMessage: {
textMessage: {
id: string;
text: string;
sender: User;
};
actionTaker: string;
};
}
Block / Unblock User
| Function | Required | Interaction Type | Description |
| --------------------- | -------- | ------------------------------- | ---------------------- |
| onBlockUserReceived | Optional | INTERACTION_TYPE_BLOCK_USER
| The user is blocked. |
| onUnblockUserReceived | Optional | INTERACTION_TYPE_UNBLOCK_USER
| The user is unblocked. |
interface User {
id: string;
deviceId: string;
customName: string;
isAdmin?: boolean;
}
interface ReceivedMessageBlockUnblock extends ReceivedMessage {
type: InteractionType.Block | InteractionType.Unblock;
blockUnblockMessage: {
user: User;
actionTaker: string;
};
}
Delete Message
| Function | Required | Interaction Type | Description |
| ----------------------- | -------- | --------------------------------- | ----------------------- |
| onDeleteMessageReceived | Optional | INTERACTION_TYPE_DELETE_MESSAGE
| The message is deleted. |
interface ReceivedMessageDelete extends ReceivedMessage {
type: InteractionType.Delete;
deletedMessage: {
id: string;
actionTaker: string;
};
}
Viewer Info
interface ViewerInfoMessage extends ReceivedMessage {
type: InteractionType.Update | InteractionType.Enabled | InteractionType.Disabled;
viewerInfo: {
enabled: boolean; // Indicates whether viewer information is enabled. Default value is false.
count: number; // Represents the number of viewers.
updatedAt: string;
version: number; // The version number of the viewer information. A larger number represents a newer version.
};
}
Broadcast
| Function | Required | Interaction Type | Description |
| ------------------- | -------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------ |
| onBroadcastReceived | Optional | INTERACTION_TYPE_BROADCAST_UPDATE
| When received the concurrent viewer (unique viewer identified by id
) update and total viewer update. |
interface Metrics {
count: number;
updatedAt: string;
}
interface ReceivedMessageBroadcast extends ReceivedMessage {
type: InteractionType.Broadcast;
viewerMetrics: {
concurrent: Metrics;
total: Metrics;
};
}
3. General Action's API
The actions could be called from both admin and viewer users.
Text message
const textMessage = {
text: 'Here is a message',
};
Chatroom.sendTextMessage(textMessage).then(
() => {
console.log('Message sent successfully');
},
(error) => {
console.log('Message sending failed with error:', error);
}
);
| Parameter | Required | Description |
| --------- | -------- | ------------------------------------------------------- |
| text
| Required | String. The maximum length of text message is 1000. |
Custom message
const customMessage = {
value: 'ANY CUSTOM VALUE YOU MAY HAVE',
};
Chatroom.sendCustomMessage(customMessage).then(
() => {
console.log('Message sent successfully');
},
(error) => {
console.log('Message sending failed with error:', error);
}
);
| Parameter | Required | Description |
| --------- | -------- | --------------------------------------------------------------------- |
| value
| Required | String. The custom value that you want to send with chatroom service. |
Custom counter message
const customCounterMessage = {
key: 'like',
value: 'ANY CUSTOM VALUE YOU MAY HAVE',
};
Chatroom.sendCustomCounterMessage(customCounterMessage).then(
() => {
console.log('Message sent successfully');
},
(error) => {
console.log('Message sending failed with error:', error);
}
);
| Parameter | Required | Description |
| --------- | -------- | ------------------------------------------------------------------------------------------- |
| key
| Required | String. The key of increment count that you set when creating chatroom. |
| value
| Optional | The custom value that you want to bring with the counter. Usually structure in JSON String. |
Retrieve Chat Message History
The default without any query parameters will retrieve 100 messages from the latest to the oldest, and can continue to retrieve the next 100 messages by providing the beforeAt
query parameter which can assign the receivedAt
value of the first message from the previous response. If the response returns an empty array, means no more message in the condition.
Only the INTERACTION_TYPE_TEXT
, INTERACTION_TYPE_CUSTOM
would be list.
Example 1
interface ReceivedHistoryMessage = ReceivedTextMessage | ReceivedCustomMessage
Chatroom.getChatMessages().then(
(data: ReceivedHistoryMessage[])=>{
console.log('Messages:', data)
// Will get the latest 100 messages by default.
},
(error)=>{
console.log('Get messages failed with error:', error);
}
);
Example 2
function getYesterdayISOString() {
const currentDate = new Date();
currentDate.setDate(currentDate.getDate() - 1);
return currentDate.toISOString();
}
const params = {
afterAt: getYesterdayISOString(),
limit: 50,
fromOldest: true,
};
Chatroom.getChatMessages({ afterAt, limit, fromOldest }).then(
(data: ReceivedHistoryMessage[]) => {
console.log('Messages:', data);
// Will get the oldest 50 messages after yesterday time.
},
(error) => {
console.log('Get messages failed with error:', error);
}
);
| Parameter | Required | Description |
| ------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| beforeAt
| Optional | List the messages before the time, default is current time. Will list from the latest in the chatroom if not provide. |
| limit
| Optional | Number. The number of messages to retrieve. The default is 100
. |
| afterAt
| Optional | List the messages after the time. Will list from the latest until the time by default. If require to list from the setting time, please set the fromOldest
to true
. |
| fromOldest
| Optional | Boolean. Indicate the list direction between interval. The default is false
, will list messages from latest to oldest. |
| types
| Optional | Array of InteractionType. Filter messages based on the provided message types. If not provided, all message types will be listed by default. Currently, only filtering by the INTERACTION_TYPE_CUSTOM
type is supported. |
Further explanation of the parameters
- Assume there are chat messages exist in a chatroom, and have set the
after_at
andbefore_at
boundary to list as follows:
m1 m2 m3 m4 m5 m6 m7 m8 m9 m10
^ ^
after_at before_at
from_oldest=false
,limit=2
=>[m6, m7]
from_oldest=true
,limit=2
=>[m3, m4]
- Assume there are chat messages exist in a chatroom, and haven't set the
after_at
andbefore_at
boundary to list as follows:
m1 m2 m3 m4 m5 m6 m7 m8 m9 m10
from_oldest=false
,limit=2
=>[m9, m10]
from_oldest=true
,limit=2
=>[m1, m2]
4. Admin Action's API
The actions could be called from admin users only.
Mute & Unmute the Chatroom
The admin user could mute & unmute the chatroom. Viewer users message would be limited, only admin user could send message when the chatroom is muted.
// Mute the chat room. `onMuteReceived` would receive interaction message upon success.
Chatroom.mute();
// Unmute the chat room. `onUnmuteReceived` would receive interaction message upon success.
Chatroom.unmute();
Block & Unblock a User
The admin user could block / unblock a certain user. If a user in blocked, it's future message would be hidden to other viewer users, and added 'blocked' label when send to admin user.
// Block a user. `onBlockUserReceived` would receive interaction message upon success.
const userForBlock = {
id: 'USER_ID_FOR_BLOCK',
deviceId: 'USER_DEVICE_ID_FOR_BLOCK',
customName: 'USER_CUSTOM_NAME_FOR_BLOCK',
};
Chatroom.blockUser(userForBlock);
// Unblock a user. `onUnblockUserReceived` would receive interaction message upon success.
const id = 'USER_ID_FOR_UNBLOCK';
Chatroom.unblockUser({ id });
Delete a Message
The admin user could delete specific message within the chatroom. If a message is deleted, user would received the id of it.
// Delete a message. `onDeleteMessageReceived` would receive interaction message upon success.
const messageForDelete = {
id: 'MESSAGE_FOR_DELETE_ID',
sentAt: 'MESSAGE_FOR_DELETE_SENT_AT', //optional. would improve the message delete time.
receivedAt: 'MESSAGE_FOR_DELETE_RECEIVED_AT', //optional. would improve the message delete time.
};
Chatroom.deleteMsg(messageForDelete);
Pin & Unpin a Message
The admin could pin / unpin a specific message within the chatroom.
// Pin a message. `onPinMessageReceived` would receive interaction message upon success.
const messageForPin = {
id:'MESSAGE_ID';
text:'MESSAGE_TEXT';
sender:{
id:'MESSAGE_SENDER_ID';
deviceId:'MESSAGE_SENDER_DEVICE_ID';
customName:'MESSAGE_SENDER_CUSTOM_NAME';
};
}
Chatroom.pinMessage(messageForPin);
// Unpin a message. `onUnpinMessageReceived` would receive interaction message upon success.
const id = 'UNPIN_MESSAGE_ID';
Chatroom.unpinMessage({ id });
Show & Hide viewer info
Modify the visibility of viewer info in the chatroom.
If true
, the user could receive the viewer info update, on the other hand, the viewer info would be invisible for viewer user.
// Update viewer info. `onUpdateViewerInfoReceived` would receive interaction message upon success.
const viewerInfo = {
enabled: false,
};
Chatroom.updateViewerInfo(viewerInfo);
Update a user
The admin users could update their custom name by the function.
// Update a user.
const customName = 'Bella';
Chatroom.updateUser({ customName });