Clear all callbacks for an event.
the event to unregister from (e.g. 'legStatusUpdate')
void
client.clearCallbacks('sessionError');
This is useful for cleaning up callbacks when you no longer need them.
Create a session with a token and optional sessionId If no sessionId is provided, a new one will be generated and returned. If a sessionId is provided, it will be used to resume an existing session.
Optional sessionId: null | stringoptional sessionId to use
the sessionId of the session
const token = 'token';
try {
const sessionId: string = await client.createSession(token);
console.log({ sessionId });
} catch (e) {
console.log({ e });
}
Get a Conversation
the Conversation's id or conversation name
the Conversation
try {
const conversation: Conversation = await client.getConversation(
'conversationIdOrName'
);
console.log({ conversation });
} catch (e) {
console.log({ e });
}
Unregister a callback for an event.
the event to register for (e.g. 'legStatusUpdate')
the callback symbol to unregister
true if the callback was unregistered, false otherwise
client.off('reconnecting', reeconnectingListener);
client.off('reconnection', reeconnectionListener);
client.off('sessionError', sessionErrorListener);
We recommend deregistering callbacks when you no longer need them.
Register a callback for an event.
the event to register for (e.g. 'legStatusUpdate')
the callback to register for the event
a symbol that can be used to unregister the callback
const eventHandler = (event: ConversationEvent) => {
if (event.kind == 'member:invited') {
console.log(`Member invited: ${event.body.memberId}`);
} else if (event.kind == 'member:joined') {
console.log(`Member joined: ${event.body.memberId}`);
} else if (event.kind == 'member:left') {
console.log(`Member left: ${event.body.memberId}`);
} else if (event.kind == 'ephemeral') {
console.log(`Ephemeral event: ${event.body}`);
} else if (event.kind == 'custom') {
console.log(`Custom event: ${event.body}`);
} else if (event.kind == 'message:text') {
console.log(`Text message: ${event.body.text}`);
} else if (event.kind == 'message:custom') {
console.log(`Custom message: ${event.body.customData}`);
} else if (event.kind == 'message:image') {
console.log(`Image message: ${event.body.imageUrl}`);
} else if (event.kind == 'message:video') {
console.log(`Video message: ${event.body.videoUrl}`);
} else if (event.kind == 'message:audio') {
console.log(`Audio message: ${event.body.audioUrl}`);
} else if (event.kind == 'message:file') {
console.log(`File message: ${event.body.fileUrl}`);
} else if (event.kind == 'message:vcard') {
console.log(`Vcard message: ${event.body.vcardUrl}`);
} else if (event.kind == 'message:location') {
console.log(`Location message: ${event.body.location}`);
} else if (event.kind == 'message:template') {
console.log(`Template message: ${event.body.template}`);
} else if (event.kind == 'event:delete') {
console.log(`Template message: ${event.body}`);
} else if (event.kind == 'message:seen') {
console.log(`Template message: ${event.body}`);
} else if (event.kind == 'message:delivered') {
console.log(`Message delivered event: ${event.body}`);
} else if (event.kind == 'message:rejected') {
console.log(`Message rejected event ${event.body}`);
} else if (event.kind == 'message:submitted') {
console.log(`Message delivered event ${event.body}`);
} else if (event.kind == 'message:undeliverable') {
console.log(`Message undeliverable event ${event.body}`);
} else {
exhaustiveCheck(event);
}
};
const listener = client.on('conversationEvent', eventHandler);
client.off('conversationEvent', listener);
Be sure to store the symbol returned by this method so you can unregister the callback later. We recommend unregistering callbacks when you no longer need them. See off.
Set a configuration for the client SDK
A configuration object
void
const config: ClientConfig = new ClientConfig(ConfigRegion.EU);
config.apiUrl = 'https://api.example.com';
config.websocketUrl = 'https://ws.example.com';
config.rtcStatsTelemetry = true;
config.autoReconnectMedia = false;
client.setConfig(config);
// or
client.setConfig({
apiUrl: 'https://api.example.com',
websocketUrl: 'https://ws.example.com'
});
client.setConfig({
region: 'EU'
});
Updates a conversation object identified by its unique conversation ID.
This method overrides the conversation properties to the provided parameters and rest remains as it is.
the Conversation's id.
The properties of the conversation. These will replace existing values to the provided ones, rest will remain as they are.
conversation, this object will contain the updated conversation properties if the update is successful.
const conversation = await client.updateConversation('ConversationID', {
// Update Name
name: some('name'),
// Reset Display Name
displayName: some(null),
// Update imageUrl
imageUrl: 'imageUrl',
// Leave TTL as is (implicitly via omission)
// Leave customSortKey as is (explicitly via none)
customSortKey: none(),
customData: { key: 'value' }
});
Create a conversation
Optional parameters: Nullable<CreateConversationParameters>A CreateConversationParameters object containing the parameters for the creation request.
the cid of the conversation
const conversationId = await client.createConversation({
name: 'name',
displayName: 'displayName',
imageUrl: 'imageUrl',
ttl: 60,
customSortKey: 'customSortKey',
customData: { key: 'value' }
});
Get a Conversation's Events
the Conversation's id
Optional parameters: Nullable<GetConversationEventsParameters>A GetConversationEventsParameters object containing the parameters for the request.
a EventsPage containing the events
const { events, nextCursor, previousCursor } =
await client.getConversationEvents('CONVERSATION_ID', {
order: PresentingOrder.DESC,
pageSize: 10,
cursor: undefined,
eventFilter: ['message', 'member:joined'], // event filter query
includeDeletedEvents: false,
startId: 3 // start event id
});
Get a Member of a Conversation
the Conversation's id
the Member's id
the Member
const { id, state, channel } = await client.getConversationMember(
'CONVERSATION_ID',
'MEMBER_ID'
);
console.log(
`Member ID: ${id}, State: ${state}, Channel Type: ${channel?.type}`
);
Get a Conversation's Members
the Conversation's id
Optional parameters: Nullable<GetConversationMembersParameters>A GetConversationMembersParameters object containing the parameters for the request.
a MembersPage containing the members
const { members, nextCursor, previousCursor } =
await client.getConversationMembers('CONVERSATION_ID', {
order: PresentingOrder.ASC,
pageSize: 10
});
Get a list of Conversations for the user.
Optional parameters: Nullable<GetConversationsParameters>A GetConversationsParameters object containing the parameters for the request.
a ConversationsPage containing the conversations
const { conversations, nextCursor, previousCursor } =
await client.getConversations({
order: PresentingOrder.DESC,
pageSize: 10,
cursor: undefined,
includeCustomData: true,
orderBy: OrderBy.CUSTOM_SORT_KEY
});
Invite a user to a Conversation by user's name
the Conversation's id
the name of the user to invite
the memberId of the member
const memberId = await client.inviteToConversation(
'CONVERSATION_ID',
'USERNAME'
);
Send a Custom event to a Conversation
the Conversation's id
the body of the event
the timestamp of the message
const customData = {
key1: 'val1',
key2: 'val2'
};
const timestamp = await client.sendCustomEvent(
'CONVERSATION_ID',
'custom:test',
customData // or JSON.stringify(customData)
);
Send an ephemeral event to a Conversation
the Conversation's id
the body of the event
the timestamp of the message
const memberId = 'MEMBER_ID';
const readMessageEvent = {
type: `${memberId}:readUpdate`,
eventId: 'EVENT_ID',
timestamp: 'TIMESTAMP'
};
const timestamp = await client.sendEphemeralEvent(
'CONVERSATION_ID',
readMessageEvent // or JSON.stringify(readMessageEvent)
);
Send a audio message to a Conversation.
the Conversation's id
the url of the audio resource.
the timestamp of the message
const timestamp = await client.sendMessageAudioEvent(
'CONVERSATION_ID',
audioURL
);
Send a custom message to a Conversation
the Conversation's id
the body of the message
the timestamp of the message
const attachmentPayload = {
attachment: {
payload: {
buttons: [
{
payload: '{"<cid>": "$","action": "connect","mid": "<mid>"}',
title: 'Connect to an agent',
type: 'postback'
}
],
template_type: 'button',
text: "Hi, My name is Chatbot, Welcome to my chatbot's corner. How can We help you"
},
type: 'template'
}
};
const timestamp = await client.sendMessageCustomEvent(
'CONVERSATION_ID',
attachmentPayload // or JSON.stringify(attachmentPayload)
);
Send a file message to a Conversation.
the Conversation's id
the url of the file resource.
the timestamp of the message
const timestamp = await client.sendMessageFileEvent(
'CONVERSATION_ID',
fileURL
);
Send a Image message to a Conversation.
the Conversation's id
the url of the image resource.
the timestamp of the message
const timestamp = await client.sendMessageImageEvent(
'CONVERSATION_ID',
imageUrl
);
Send a Location message to a Conversation.
the Conversation's id
the description of the location.
the timestamp of the message
const timestamp = await client.sendMessageLocationEvent('CONVERSATION_ID', {
latitude: 'LATITUDE',
longitude: 'LONGITUDE',
name: 'Name', //optional
address: 'Address' //optional
});
Send a message seen event to a Conversation
the event id
the conversation id
the timestamp of the message
const eventId = 0;
const timestamp = await client.sendMessageSeenEvent(
eventId,
'conversation_id'
);
Send a template message to a Conversation.
the timestamp of the message
const timestamp = await client.sendMessageTemplateEvent(
'CONVERSATION_ID',
{
name: 'name',
parameters: ['Params1'] // optional
},
{
policy: '',
locale: ''
}
);
Send a text message to a Conversation
the Conversation's id
the Body of the message
whether to send the text as raw or not (default: false, not recommended)
the timestamp of the message
const timestamp = await client.sendMessageTextEvent(
'CONVERSATION_ID',
'Hello World!'
);
Send a vcard message to a Conversation.
the Conversation's id
the url of the vCardUrl resource.
the timestamp of the message
const timestamp = await client.sendMessageVCardEvent(
'CONVERSATION_ID',
vCardUrl
);
Send a Vidoe message to a Conversation.
the Conversation's id
the url of the video resource.
the timestamp of the message
const timestamp = await client.sendMessageVideoEvent(
'CONVERSATION_ID',
videoURL
);
Get a Call's Legs
Optional parameters: Nullable<GetCallLegsParameters>A GetCallLegsParameters object containing the parameters for the request.
a LegsPage containing the legs
const { legs, nextCursor, previousCursor } = await client.getCallLegs(
'callId',
{
order: PresentingOrder.DESC,
pageSize: 10,
cursor: undefined
}
);
Hangup a call.
the callId of the call to hangup
Optional reasonText: stringoptional reason text to send to the other party
Optional reasonCode: stringoptional reason code to send to the other party
void
const callId = 'callId';
await client.hangup(callId);
Sends a TTS message to the Call
the callId of the call to send the message to
the text to send
void
Sends a TTS message to the Call
the callId of the call to send the message to
the CallSayParams to send
void
const callId = 'callId';
await client.say(callId, 'Hello World');
const ssmlExample =
'<speak>Hello World <break strength="weak"/> I am using <say-as interpret-as="character">SSML</say-as> <break strength="weak" /> how cool is that? </speak>';
await client.say(callId, {
text: ssmlExample,
voiceName: 'Kimberly',
ssml: true,
level: 1,
loop: 2
});
Make a server call to the Vonage API. This is used to initiate a call using the Voice API and NCCO.
Optional context: Jsonthe context to send to the server passed as Custom data to the voice answer webhook
the callId of the call
const context = {
callee: 'user1'
};
const callId = await client.serverCall(context);
VonageClient is the main entry point for the Vonage Client SDK.