@vonage/client-sdk - v2.7.0
    Preparing search index...

    Class VonageClient

    VonageClient is the main entry point for the Vonage Client SDK.

    Hierarchy

    • CombinedClientJS
      • VonageClient
    Index
    • get emergencyCore(): any

      Returns any

    • Clear all callbacks for an event.

      Type Parameters

      • T extends
            | "mute"
            | "conversationEvent"
            | "callHangup"
            | "callMediaDisconnect"
            | "legStatusUpdate"
            | "rtcStatsUpdate"
            | "callInvite"
            | "callInviteCancel"
            | "sessionError"
            | "callMediaError"
            | "emergencyCallDisconnected"
            | "emergencyCallHangup"
            | "callTransfer"
            | "earmuff"
            | "dtmf"
            | "callMediaReconnecting"
            | "callMediaReconnection"
            | "reconnecting"
            | "reconnection"
            | "peerConnectionCreated"

      Parameters

      • event: T

        the event to unregister from (e.g. 'legStatusUpdate')

      Returns void

      void

      client.clearCallbacks('sessionError');
      

      This is useful for cleaning up callbacks when you no longer need them.

    • Create (or reconnect to) a session.

      When sessionId is omitted or null, a completely new session is created.

      When sessionId is set to the value returned by a previous createSession call, the Conversation Service will replay any pending events into the new session. In particular, an unanswered inbound call invite that arrived before a page refresh will be re-delivered so that onCallInvite fires automatically — no extra API call is needed.

      Important: The Conversation Service retains pending events for approximately 30 seconds. Persist the session ID (e.g. in sessionStorage) and pass it back within that window.

      Parameters

      • token: string

        JWT token of the user.

      • OptionalsessionId: string | null

        Optional previous session ID. Omit or pass null for a fresh session.

      Returns Promise<string>

      The sessionId of the newly established session.

      const token = 'token';
      
      try {
        const sessionId: string = await client.createSession(token);
        console.log({ sessionId });
      } catch (e) {
        console.log({ e });
      }
      
    • Get a Conversation

      Parameters

      • conversationIdOrName: string

        the Conversation's id or conversation name

      Returns Promise<Conversation>

      the Conversation

      try {
        const conversation: Conversation = await client.getConversation(
          'conversationIdOrName'
        );
        console.log({ conversation });
      } catch (e) {
        console.log({ e });
      }
      
    • Unregister a callback for an event.

      Type Parameters

      • T extends
            | "mute"
            | "conversationEvent"
            | "callHangup"
            | "callMediaDisconnect"
            | "legStatusUpdate"
            | "rtcStatsUpdate"
            | "callInvite"
            | "callInviteCancel"
            | "sessionError"
            | "callMediaError"
            | "emergencyCallDisconnected"
            | "emergencyCallHangup"
            | "callTransfer"
            | "earmuff"
            | "dtmf"
            | "callMediaReconnecting"
            | "callMediaReconnection"
            | "reconnecting"
            | "reconnection"
            | "peerConnectionCreated"

      Parameters

      • event: T

        the event to register for (e.g. 'legStatusUpdate')

      • callbackSymbol: symbol

        the callback symbol to unregister

      Returns boolean

      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.

      Type Parameters

      • T extends
            | "mute"
            | "conversationEvent"
            | "callHangup"
            | "callMediaDisconnect"
            | "legStatusUpdate"
            | "rtcStatsUpdate"
            | "callInvite"
            | "callInviteCancel"
            | "sessionError"
            | "callMediaError"
            | "emergencyCallDisconnected"
            | "emergencyCallHangup"
            | "callTransfer"
            | "earmuff"
            | "dtmf"
            | "callMediaReconnecting"
            | "callMediaReconnection"
            | "reconnecting"
            | "reconnection"
            | "peerConnectionCreated"
      • P extends
            | ((event: ConversationEvent) => void)
            | (
                (
                    callId: string,
                    callQuality: RTCQualityJS,
                    reason: HangupReason,
                ) => void
            )
            | ((callId: string, reason: "networkChange") => void)
            | ((callId: string, legId: string, legStatus: LegStatus) => void)
            | ((stats: RTCStatsJS, callId: string) => void)
            | ((callId: string, reason: CancelReason) => void)
            | ((callId: string, from: string, channelType: VoiceChannelType) => void)
            | ((reason: SessionErrorReason) => void)
            | ((callId: string, error: VonageError) => void)
            | ((callId: string) => void)
            | ((callId: string) => void)
            | ((callId: string | null, pc: RTCPeerConnection) => void)
            | ((callId: string, legId: string, isMuted: boolean) => void)
            | ((callId: string, conversationId: string) => void)
            | ((callId: string, legId: string, earmuffStatus: boolean) => void)
            | ((callId: string, legId: string, digits: string) => void)
            | ((callId: string) => void)
            | ((callId: string) => void)
            | (() => void)
            | (() => void)

      Parameters

      • event: T

        the event to register for (e.g. 'legStatusUpdate')

      • callback: P

        the callback to register for the event

      Returns symbol

      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

      Parameters

      Returns void

      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',
        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.

      Parameters

      • conversationId: string

        the Conversation's id.

      • parameters: UpdateConversationParameters

        The properties of the conversation. These will replace existing values to the provided ones, rest will remain as they are.

      Returns Promise<Conversation>

      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

      Parameters

      Returns Promise<string>

      the cid of the conversation

      const conversationId = await client.createConversation({
        name: 'name',
        displayName: 'displayName',
        imageUrl: 'imageUrl',
        ttl: 60,
        customSortKey: 'customSortKey',
        customData: { key: 'value' }
      });
      
    • Delete a Conversation

      Parameters

      • id: string

        the Conversation's id

      Returns Promise<void>

      void

      await client.deleteConversation('CONVERSATION_ID');
      
    • Delete an Event in a Conversation

      Parameters

      • id: number

        the id for the Event to be deleted

      • conversationId: string

        the id for the conversation, the event belongs to.

      Returns Promise<void>

      void

      await client.deleteEvent(123, 'CONVERSATION_ID');
      
    • Get a Conversation's Events

      Parameters

      Returns Promise<EventsPage>

      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

      Parameters

      • cid: string

        the Conversation's id

      • mid: string

        the Member's id

      Returns Promise<Member>

      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

      Parameters

      Returns Promise<MembersPage>

      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.

      Parameters

      Returns Promise<ConversationsPage>

      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

      Parameters

      • id: string

        the Conversation's id

      • name: string

        the name of the user to invite

      Returns Promise<string>

      the memberId of the member

      const memberId = await client.inviteToConversation(
        'CONVERSATION_ID',
        'USERNAME'
      );
      
    • Join a Conversation

      Parameters

      • id: string

        the Conversation's id

      Returns Promise<string>

      the memberId of the member

      const memberId = await client.joinConversation('CONVERSATION_ID');
      
    • Leave a Conversation

      Parameters

      • id: string

        the Conversation's id

      Returns Promise<void>

      void

      await client.leaveConversation('CONVERSATION_ID');
      
    • Send a Custom event to a Conversation

      Parameters

      • id: string

        the Conversation's id

      • eventType: string
      • customData: CustomData

        the body of the event

      Returns Promise<string>

      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

      Parameters

      • id: string

        the Conversation's id

      • customData: CustomData

        the body of the event

      Returns Promise<string>

      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.

      Parameters

      • id: string

        the Conversation's id

      • audioUrl: URL

        the url of the audio resource.

      Returns Promise<string>

      the timestamp of the message

      const timestamp = await client.sendMessageAudioEvent(
        'CONVERSATION_ID',
        audioURL
      );
      
    • Send a custom message to a Conversation

      Parameters

      • id: string

        the Conversation's id

      • customData: CustomData

        the body of the message

      Returns Promise<string>

      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.

      Parameters

      • id: string

        the Conversation's id

      • fileUrl: URL

        the url of the file resource.

      Returns Promise<string>

      the timestamp of the message

      const timestamp = await client.sendMessageFileEvent(
        'CONVERSATION_ID',
        fileURL
      );
      
    • Send a Image message to a Conversation.

      Parameters

      • id: string

        the Conversation's id

      • imageUrl: URL

        the url of the image resource.

      Returns Promise<string>

      the timestamp of the message

      const timestamp = await client.sendMessageImageEvent(
        'CONVERSATION_ID',
        imageUrl
      );
      
    • Send a Location message to a Conversation.

      Parameters

      • id: string

        the Conversation's id

      • location: Location

        the description of the location.

      Returns Promise<string>

      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

      Parameters

      • id: number

        the event id

      • conversationId: string

        the conversation id

      Returns Promise<string>

      the timestamp of the message

      const eventId = 0;
      
      const timestamp = await client.sendMessageSeenEvent(
        eventId,
        'conversation_id'
      );
      
    • Send a template message to a Conversation.

      Parameters

      • id: string

        the Conversation's id

      • templateObject: Template

        the description(name and paramters) of the template.

      • whatsappObject: Whatsapp

        the description(locale and policies of business account) of the location.

      Returns Promise<string>

      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

      Parameters

      • id: string

        the Conversation's id

      • text: string

        the Body of the message

      • raw: boolean = false

        whether to send the text as raw or not (default: false, not recommended)

      Returns Promise<string>

      the timestamp of the message

      const timestamp = await client.sendMessageTextEvent(
        'CONVERSATION_ID',
        'Hello World!'
      );
      
    • Send a vcard message to a Conversation.

      Parameters

      • id: string

        the Conversation's id

      • vCardUrl: URL

        the url of the vCardUrl resource.

      Returns Promise<string>

      the timestamp of the message

      const timestamp = await client.sendMessageVCardEvent(
        'CONVERSATION_ID',
        vCardUrl
      );
      
    • Send a Vidoe message to a Conversation.

      Parameters

      • id: string

        the Conversation's id

      • videoUrl: URL

        the url of the video resource.

      Returns Promise<string>

      the timestamp of the message

      const timestamp = await client.sendMessageVideoEvent(
        'CONVERSATION_ID',
        videoURL
      );
      
    • Disable earmuff for an emergency call.

      Parameters

      • callId: string

        the callId of the call to disable earmuff for

      Returns Promise<void>

      void

    • Starts an emergency call.

      Parameters

      • token: string
      • from: string
      • to: string
      • Optionaloptions: Nullable<EmergencyCallOptionsJS>

        Optional EmergencyCallOptions containing call options

      Returns Promise<EmergencyCallDataJS>

      the result containing callId and reconnectToken

    • Enable earmuff for an emergency call.

      Parameters

      • callId: string

        the callId of the call to enable earmuff for

      Returns Promise<void>

      void

    • Hangup an emergency call.

      Parameters

      • callId: string

        the callId of the call to hangup

      Returns Promise<void>

      void

    • Mute an emergency call.

      Parameters

      • callId: string

        the callId of the call to mute

      Returns Promise<void>

      void

    • Reconnects an existing emergency call.

      Parameters

      • token: string
      • callId: string
      • reconnectToken: string

      Returns Promise<void>

      void

    • Unmute an emergency call.

      Parameters

      • callId: string

        the callId of the call to unmute

      Returns Promise<void>

      void

    • Answer a call

      Parameters

      • callId: string

        Call ID

      Returns Promise<void>

      void

      const callId = 'callId';
      await client.answer(callId);
      
    • Experimental

      Disable auto gain control on a call's audio track.

      Parameters

      • id: string

        The Call Id

      Returns Promise<void>

    • Unearmuff your leg of a call

      Parameters

      • callId: string

        Call ID

      Returns Promise<void>

      void

      const callId = 'callId';
      await client.disableEarmuff(callId);
      
    • Experimental

      Disable echo cancellation on a call's audio track.

      Parameters

      • id: string

        The Call Id

      Returns Promise<void>

    • Experimental

      Disable noise suppression on a call's audio track.

      Parameters

      • id: string

        The Call Id

      Returns Promise<void>

    • Experimental

      Enable auto gain control on a call's audio track.

      Parameters

      • id: string

        The Call Id

      Returns Promise<void>

    • Earmuff your leg of a call

      Parameters

      • callId: string

        Call ID

      Returns Promise<void>

      void

      const callId = 'callId';
      await client.enableEarmuff(callId);
      
    • Experimental

      Enable echo cancellation on a call's audio track.

      Parameters

      • id: string

        The Call Id

      Returns Promise<void>

    • Experimental

      Enable noise suppression on a call's audio track.

      Parameters

      • id: string

        The Call Id

      Returns Promise<void>

    • Experimental

      Get the HTML Audio Element for the SDK. It can be used to route output to other devices.

      Returns HTMLAudioElement | undefined

    • Get a Call's Legs

      Parameters

      Returns Promise<LegsPage>

      a LegsPage containing the legs

      const { legs, nextCursor, previousCursor } = await client.getCallLegs(
        'callId',
        {
          order: PresentingOrder.DESC,
          pageSize: 10,
          cursor: undefined
        }
      );
      
    • Get the Leg for a call

      Parameters

      • legId: string

        The Leg Id

      Returns Promise<LegJS>

    • Experimental

      Get the Peer Connection for a call

      Parameters

      • id: string

        The Call Id

      Returns RTCPeerConnection | undefined

    • Hangup a call.

      Parameters

      • callId: string

        the callId of the call to hangup

      • OptionalreasonText: string

        optional reason text to send to the other party

      • OptionalreasonCode: string

        optional reason code to send to the other party

      Returns Promise<void>

      void

      const callId = 'callId';
      await client.hangup(callId);
      
    • Mute your leg of a call

      Parameters

      • callId: string

        Call ID

      Returns Promise<void>

      void

      const callId = 'callId';
      await client.mute(callId);
      
    • Reconnect a call

      Parameters

      • callId: string

        Call ID

      Returns Promise<void>

      void

      const callId = 'callId';
      await client.reconnectCall(callId);
      
    • Reject a call

      Parameters

      • callId: string

        Call ID

      Returns Promise<void>

      void

      const callId = 'callId';
      await client.reject(callId);
      
    • Sends a TTS message to the Call

      Parameters

      • callId: string

        the callId of the call to send the message to

      • text: string

        the text to send

      Returns Promise<void>

      void

    • Sends a TTS message to the Call

      Parameters

      • callId: string

        the callId of the call to send the message to

      • params: CallSayParams

        the CallSayParams to send

      Returns Promise<void>

      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
      });
      
    • Send a string of digits to a call via DTMF

      Parameters

      • callId: string

        Call ID

      • digits: string

        DTMF digits

      Returns Promise<void>

      void

      const callId = 'callId';
      await client.sendDTMF(callId, '1234');
      
    • Make a server call to the Vonage API. This is used to initiate a call using the Voice API and NCCO.

      Parameters

      • Optionalcontext: Json

        the context to send to the server passed as Custom data to the voice answer webhook

      Returns Promise<string>

      the callId of the call

      const context = {
        callee: 'user1'
      };
      
      const callId = await client.serverCall(context);
      
    • Unmute your leg of a call

      Parameters

      • callId: string

        Call ID

      Returns Promise<void>

      void