Options
All
  • Public
  • Public/Protected
  • All
Menu

Class SDK

The Muxy Extensions SDK, used to communicate with Muxy's Extension Backend Service.

Instances of this class created through the global Muxy object can be used to easily interact with Muxy's Extension Backend Service. It includes functionality to aggregate and persist user data, set extension configuration, send analytics events and authenticate broadcasters across servers and applications.

To begin using the SDK, create a new instance by calling const sdk = Muxy.SDK().

Note for Overlay App Developers: An instance of the Muxy SDK is automatically created for you that is namespaced to your app id. You can access it in any app that imports AppMixin as this.muxy.<method>. The methods described below behave similarly to how they would in an extension context, however all data is exclusive to your app. Differences are noted in the comments to the individual methods.

Hierarchy

  • SDK

Index

Properties

SKUs

SKUs: any[]

analytics

analytics: Analytics

client

client: StateClient

contextObservers

contextObservers: Observer<TwitchContext>

debug

identifier

identifier: string

loadPromise

loadPromise: Promise<void>

messenger

messenger: Messenger

timeOffset

timeOffset: number

user

user: User

userObservers

userObservers: Observer<User>

Methods

accumulate

  • accumulate(accumulationID: string, data: object): Promise<any>
  • Sends data to be accumulated by the server.

    since

    1.0.0

    example

    sdk.accumulate('awesomeness_level', { awesomeness_level: { great: 10, good: 2.5, poor: 'dank' } });

    Parameters

    • accumulationID: string

      The identifier that this datum is accumulated with.

    • data: object

      Any JSON serializable JavaScript object.

    Returns Promise<any>

    Will resolve on successful server-send. Rejects on failure.

addExtensionTriviaOptionToQuestion

  • Add an option to a trivia question. Requires extension admin permissions.

    async

    Parameters

    Returns Promise<TriviaQuestion>

addExtensionTriviaQuestion

  • Add a trivia question to the extension. Requires extension admin permissions.

    async

    Parameters

    Returns Promise<any>

beginPurchase

  • beginPurchase(sku: any): void
  • Begins the purchase flow for a given product's SKU.

    Parameters

    • sku: any

      The SKU of the digital good that the user has indicated they want to buy.

    Returns void

clearRankData

  • clearRankData(rankID: string): Promise<any>
  • Clear all rank data associated with the rank identifier.

    Broadcaster-only functionality.

    async
    since

    1.0.0

    throws

    {TypeError} Will throw an error if rankID is not a string.

    Parameters

    • rankID: string

      The identifer to fetch associated rank data.

    Returns Promise<any>

    Will resolve on success. Rejects on failure.

clearRanking

  • clearRanking(rankID: any): any
  • deprecated

    Deprecated in 1.0.0. Use clearRankData instead.

    Parameters

    • rankID: any

    Returns any

getAccumulateData

  • getAccumulateData(accumulationID: string, start: number): Promise<AccumulateData>
  • Fetches the accumulated user data for a given id received by the backend since start.

    Broadcaster-only functionality.

    async
    since

    1.0.0

    throws

    {TypeError} Will throw an error if accumulationID is not a string.

    example

    const oneMinuteAgo = (new Date().getTime()) - (1000 * 60); sdk.getAccumulation('awesomeness_level', oneMinuteAgo).then((resp) => { console.log(${resp.data.length}: ${resp.latest}); console.log(resp.data); // A list of all accumulate values since oneMinuteAgo. });

    Parameters

    • accumulationID: string

      The identifier of the accumulated data to fetch.

    • start: number

      A Unix timestamp in milliseconds of the earliest accumulation record to fetch.

    Returns Promise<AccumulateData>

    Resolves with requested accumulation data on server response.

getAccumulation

  • getAccumulation(accumulationID: any, start: any): Promise<AccumulateData>
  • deprecated

    Use getAccumulateData instead.

    Parameters

    • accumulationID: any
    • start: any

    Returns Promise<AccumulateData>

getAllState

  • Returns the current state object as set for the current extension, channel and viewer combination.

    async
    since

    1.0.0

    example

    sdk.getAllState().then((state) => { if (state.channel.broadcasters_mood) { console.log(Broadcaster set their mood as: ${state.channel.broadcasters_mood}); } if (state.viewer.favorite_movie) { console.log(But your favorite movie is: ${state.viewer.favorite_movie}); } });

    Returns Promise<AllState>

    Resolves on successful server request with a populated AllState object.

getChannelState

  • getChannelState(): Promise<any>
  • Returns the current channel state object

    async

    Returns Promise<any>

    Resolves on successful server request with a populated channel state object.

getEligibleCodes

  • Fetches information about which codes a user is eligible for

    async

    Returns Promise<EligibleCodes>

    Will resolve on success. Rejects on failure.

getExtensionSecretState

  • getExtensionSecretState(): Promise<any>
  • Returns the current extension secret state if the requesting user has access to the secret state.

    async

    Returns Promise<any>

    Resolves on successful server request with a populated extension secret state object.

getExtensionState

  • getExtensionState(): Promise<any>
  • Returns the current extension state object

    async

    Returns Promise<any>

    Resolves on successful server request with a populated extension state object.

getExtensionTriviaJoinedTeam

  • getExtensionTriviaJoinedTeam(): Promise<TriviaTeam>
  • Return the user's stored trivia team.

    async

    Returns Promise<TriviaTeam>

getExtensionTriviaLeaderboard

  • Return the trivia leaderboard

    async

    Returns Promise<TriviaLeaderboard>

getExtensionTriviaQuestion

  • getExtensionTriviaQuestion(questionID: string): Promise<TriviaQuestion>
  • Get information about a specific trivia question

    async

    Parameters

    • questionID: string

    Returns Promise<TriviaQuestion>

getExtensionTriviaQuestions

  • Returns all of the current trivia questions

    async

    Returns Promise<TriviaQuestionResponse>

getExtensionUsers

  • Fetches a list of all users who have shared their identity with the extension.

    This function takes an optional next value which should match that returned from previous invocations to iterate through the response. If the returned next value is 0, all available values have been returned and iteration can be stopped.

    At most 1000 entries will be returned in a single call.

    Note that because of the asynchronous nature, duplicate entries may be returned and should be uniqued on the client.

    Admin-only function.

    async

    Parameters

    • Optional next: string

    Returns Promise<ExtensionUsersResult>

    Will resolve on success. Rejects on failure.

getExtensionViewerState

  • getExtensionViewerState(): Promise<any>
  • Returns the current extension viewer state object

    async

    Returns Promise<any>

    Resolves on successful server request with a populated extension viewer state object.

getFullVoteLogs

  • getFullVoteLogs(voteID: string): Promise<VoteLog>
  • Gets the vote logs for a given vote ID. This endpoint may only be called by an admin.

    async
    example

    const sdk = new Muxy.SDK(); sdk.getFullVoteLogs('global-12345').then((logs) => { const audit = logs.result;

    // ... process the audit logs ... const valueToUsersMapping = {}; for (const i = 0; i < audit.length; ++i) { const value = audit[i].value; const identifier = audit[i].identifier;

    const list = valueToUsersMapping[value] || [];
    list.append(identifier);
    
    valueTousersMapping[value] = list;

    } });

    Parameters

    • voteID: string

      the identifier to fetch the vote logs for.

    Returns Promise<VoteLog>

    Resolves with the logs on server response. Rejects on server error.

getJSONStore

  • getJSONStore(key?: string): Promise<any>
  • The JSON store is used similarly to the channel state, in that a broadcaster can use it to store arbitrary JSON data that is accessible to all viewers. The stored data is specific to a particular channel and cannot be accessed by viewers of a different channel.

    Unlike channel state however, each channel can have several JSON stores, accessed by different keys. The data associated with each key must be under 2KB, but there is no limit to the number of keys in use.

    Also, when pushing new data to the JSON store, a messenger event is automatically sent to all active viewers of the associated channel and the broadcaster's live and config pages. This event will have the format json_store_update:${key}. See listen for details on receiving this event.

    async
    since

    1.0.0

    throws

    {TypeError} Will throw an error if key is provided but is not a string.

    example

    sdk.getJSONStore('basecamp').then((basecamp) => { if (basecamp && basecamp.tanks) { deploy(basecamp.tanks); } });

    Parameters

    • Optional key: string

      The lookup key for data in the JSON store. Uses 'default' if no value is provided.

    Returns Promise<any>

    Resolves with the stored JSON parsed to a JS Object associated with the key. Rejects on server error or if the key has no associated data.

getOffsetDate

  • getOffsetDate(): Date
  • Returns a date object that is based on the Muxy server time. This method only returns valid results after .loaded() resolves.

    Returns Date

getPrices

  • getPrices(): Promise<Object>
  • Gets the current price for each item offered.

    async

    Returns Promise<Object>

    An object with the SKU codes as keys.

getRankData

  • getRankData(rankID: string): Promise<RankData>
  • Fetches the current ranked data associated with the rank identifier.

    async
    since

    1.0.0

    throws

    {TypeError} Will throw an error if rankID is not a string.

    example

    sdk.getRankData('favorite_color').then((colors) => { if (colors.length > 0) { colors.forEach((color) => { console.log(${color.key}: ${color.score}); }); } });

    Parameters

    • rankID: string

      The identifier to fetch associated rank data.

    Returns Promise<RankData>

    Resolves with requested rank data on server response. Rejects on server error.

getRankingData

  • getRankingData(rankID: any): Promise<RankData>
  • deprecated

    Deprecated in 1.0.0. Use getRankData instead.

    Parameters

    • rankID: any

    Returns Promise<RankData>

getRedeemedCodes

  • Fetches all codes that the user has redeemed for this extension.

    async

    Returns Promise<RedeemedCodes>

    Will resolve on success. Rejects on failure.

getUser

  • getUser(): Promise<User>
  • Returns a promise to get the user object. This automatically waits for .loaded() to resolve.

    Returns Promise<User>

getViewerState

  • getViewerState(): Promise<any>
  • Returns the current viewer state object

    async

    Returns Promise<any>

    Resolves on successful server request with a populated viewer state object.

getVoteData

  • getVoteData(voteID: string): Promise<VoteData>
  • Fetches the current stored vote data for a given vote identifier.

    async
    since

    1.0.0

    throws

    {TypeError} Will throw an error if voteID is not a string.

    example

    sdk.getVoteData('poll-number-1').then((voteData) => { console.log(voteData.sum); });

    Parameters

    • voteID: string

      The identifer to fetch associated vote data.

    Returns Promise<VoteData>

    Resolves with requested vote data on server response. Rejects on server error.

joinExtensionTriviaTeam

  • joinExtensionTriviaTeam(): Promise<any>
  • Sets the user's trivia team to the current channel.

    async

    Returns Promise<any>

listen

  • listen(inEvent: any, inUserID: any, inCallback: any): CallbackHandle
  • Registers a callback to listen for events. In general, events are named in the form event[:identifier], where the identifier is the event parameter to send.

    You can listen to wildcards by using * instead of an event or identifier name.

    Some methods also automatically send special namespaced events. See vote and getJSONStore for examples.

    You can listen for these events by using vote_update:next_game or vote_update:* to receive vote updates for specifically the next_game vote id, or all vote updates respectively.

    since

    1.0.0

    example

    sdk.listen('new_song', (track) => { console.log(${track.artist} - {track.title} (${track.year})); });

    Parameters

    • inEvent: any

      The event name to listen on. May include wildcards *.

    • inUserID: any

      An optional opaque user id, used to limit the scope of this listen to that user only.

    • inCallback: any

    Returns CallbackHandle

    A listener handle that can be passed to {@see unlisten} to unbind this callback.

loaded

  • loaded(): Promise<void>
  • Returns a Promise that will resolve once this SDK instance is ready for use. Will reject if an error occurs communicating with the backend server.

    since

    1.0.0

    example

    const sdk = new Muxy.SDK(); sdk.loaded().then(() => { sdk.send('Hello World'); }).catch((err) => { console.error(err); });

    Returns Promise<void>

onContextUpdate

onPositionChanged

  • onPositionChanged(callback: function): void
  • Sets a function to be used as a callback that is triggered when the extension changes position in the player This occurs only for video-component extensions.

    Parameters

    • callback: function

    Returns void

onReloadEntitlements

  • onReloadEntitlements(callback: any): void
  • Sets a function to be used as a callback when entitlements need to be reloaded, i.e. after a purchase has been made.

    Parameters

    • callback: any

      A function to be called to update user entitlements.

    Returns void

onUserUpdate

  • Registers a new callback for when the current user's info is updated.

    Parameters

    • callback: function
        • (user: User): void
        • Parameters

          Returns void

    Returns UserUpdateCallbackHandle

onVisibilityChanged

  • onVisibilityChanged(callback: function): void
  • Sets a function to be used as a callback that is triggered when the extension visibility changes (This occurs only for mobile or component extensions.)

    Parameters

    Returns void

pinTokenExists

  • pinTokenExists(): Promise<any>
  • Checks to see if the broadcaster has validated an auth token in the current context. It does not return information about the PIN used or auth token that is valid.

    Broadcaster-only functionality.

    async
    since

    1.0.0

    property

    {boolean} exists - True if an auth token has been validated, false otherwise.

    example

    sdk.pinTokenExists().then((resp) => { if (!resp.exists) { showBroadcasterPINInput(); } else { console.log('Already authorized'); } });

    Returns Promise<any>

rank

  • rank(rankID: string, value: string): Promise<RankResponse>
  • Submit user rank data associated with a rank identifier.

    async
    since

    1.0.0

    throws

    {TypeError} Will throw an error if rankID or value are not strings.

    example

    const usersFavoriteColor = 'rebeccapurple'; this.muxy.rank('favorite_color', usersFavoriteColor);

    Parameters

    • rankID: string

      The identifer to fetch associated rank data.

    • value: string

      Any string value to represent this user's rank data. Will be returned as the key field when rank data is requested.

    Returns Promise<RankResponse>

    Will resolve on success. Rejects on failure.

redeemCode

  • Attempt to exchange one eligibility status for a single prize code. If a code is redeemed, the returned body will have a code member, which is the code that was redeemed.

    async
    throws

    {TypeError} Will throw an error if prizeIndex is not a valid number

    Parameters

    • prizeIndex: number

    Returns Promise<RedeemResult>

removeExtensionTriviaOptionFromQuestion

  • removeExtensionTriviaOptionFromQuestion(questionID: string, optionID: string): Promise<any>
  • Remove an option from a trivia question. Requires extension admin permissions.

    async

    Parameters

    • questionID: string
    • optionID: string

    Returns Promise<any>

removeExtensionTriviaQuestion

  • removeExtensionTriviaQuestion(triviaQuestionID: string): Promise<any>
  • Removes a trivia question from the extension. Requires extension admin permissions.

    async

    Parameters

    • triviaQuestionID: string

    Returns Promise<any>

revokeAllPINCodes

  • revokeAllPINCodes(): Promise<any>
  • Revokes all auth tokens ever generated for this channel and identifier. After calling this method, tokens currently in use by external apps will cease to function.

    Broadcaster-only functionality.

    async
    since

    1.0.0

    example

    sdk.revokeAllPINCodes().then(() => { console.log('No more data coming in!'); });

    Returns Promise<any>

    Resolves on sucess, rejects with an error otherwise.

send

  • send(event: any, userID: any, data: any): void
  • Sends a message to all listening clients. And viewers or broadcaters listening for the event name will be automatically notified. See listen for receiving events.

    Broadcaster-only functionality.

    async
    since

    1.0.0

    example

    sdk.send('new_song', { artist: 'Celine Dion', title: 'My Heart Will Go On', album: 'Let's Talk About Love', year: 1997 });

    Parameters

    • event: any

      An event name, in the form [a-z0-9_]+

    • userID: any

      An optional opaque user id, used to limit the scope of send to that user only.

    • data: any

    Returns void

sendAnalyticsEvent

  • sendAnalyticsEvent(name: string, value?: number, label?: string): void
  • Sends an arbitrary event to the analytics backend.

    async
    since

    1.0.0

    Parameters

    • name: string

      A unique identifier for this event.

    • Default value value: number = 1
    • Default value label: string = ""

    Returns void

setChannelState

  • setChannelState(state: object): Promise<any>
  • Sets the channel-specific state to a JS object. Future calls to getAllState by any user on this channel will have a clone of this object in the channel field.

    Broadcaster-only functionality.

    async
    since

    1.0.0

    example

    sdk.setChannelState({ broadcasters_mood: 'sanguine, my brother', chats_mood: 'kreygasm' }).then(() => { // Let viewers know that new channel state is available. }).catch((err) => { console.error(Failed saving channel state: ${err}); });

    Parameters

    • state: object

      A complete JS object representing the current channel state.

    Returns Promise<any>

    Will resolve on successful server-send. Rejects on failure.

setExtensionSecretState

  • setExtensionSecretState(state: object): Promise<any>
  • Sets the extension-wide secret state to a JS object, this may only be called by an extension owner. This state object will never be returned to the broadcaster or viewers.

    async
    since

    2.0.0

    example

    sdk.setExtensionSecretState({ favorite_movie: 'Twilight: New Moon' }).then(() => { console.log('Extension secrets saved!'); }).catch((err) => { console.error(Failed saving secret state: ${err}); });

    Parameters

    • state: object

      A complete JS object

    Returns Promise<any>

    Will resolve on successful server-send. Rejects on failure.

setExtensionState

  • setExtensionState(state: object): Promise<any>
  • Sets the extension wide state to a JS object, this may only be called in a broadcaster context for the extension owner. Extension owner may be configured through the development portal. Future calls to getAllState by all users will have a clone of this object in the extension field.

    async
    since

    1.1.0

    example

    sdk.setExtensionState({ favorite_movie: 'Jaws: The Revenge' }).then(() => { console.log('Extension state saved!'); }).catch((err) => { console.error(Failed saving viewer state: ${err}); });

    Parameters

    • state: object

      A complete JS object representing the current extension's state.

    Returns Promise<any>

    Will resolve on successful server-send. Rejects on failure.

setExtensionTriviaQuestionState

  • Change the state of a extension trivia question. Requires extension admin permissions.

    async

    Parameters

    Returns Promise<TriviaStateResponse>

setExtensionTriviaQuestionVote

  • setExtensionTriviaQuestionVote(questionID: string, optionID: string): Promise<any>
  • As a user place a vote on a trivia question

    async

    Parameters

    • questionID: string
    • optionID: string

    Returns Promise<any>

setExtensionViewerState

  • setExtensionViewerState(state: object): Promise<any>
  • Sets the extension wide viewer-specific state to a JS object, this is only a valid call for a user that has shared their identity. Future calls to getAllState by this user will have a clone of this object in the extension_viewer field.

    async
    since

    1.1.0

    example

    sdk.setExtensionViewerState({ favorite_movie: 'Jaws: The Revenge' }).then(() => { console.log('Viewer state saved!'); }).catch((err) => { console.error(Failed saving viewer state: ${err}); });

    Parameters

    • state: object

      A complete JS object representing the current viewer state.

    Returns Promise<any>

    Will resolve on successful server-send. Rejects on failure.

setViewerState

  • setViewerState(state: object): Promise<any>
  • Sets the channel specific viewer-specific state to a JS object, this can be called by any viewer. Future calls to getAllState by this user will have a clone of this object in the viewer field.

    async
    since

    1.0.0

    example

    sdk.setViewerState({ favorite_movie: 'Jaws: The Revenge' }).then(() => { console.log('Viewer state saved!'); }).catch((err) => { console.error(Failed saving viewer state: ${err}); });

    Parameters

    • state: object

      A complete JS object representing the current viewer state.

    Returns Promise<any>

    Will resolve on successful server-send. Rejects on failure.

signedRequest

  • signedRequest(method: any, endpoint: any, data: any): Promise<any>
  • Invokes a request to the backend.

    Parameters

    • method: any
    • endpoint: any
    • data: any

    Returns Promise<any>

unlisten

  • unlisten(handle: any): void
  • Unbinds a callback from the event system.

    since

    1.0.0

    Parameters

    • handle: any

      An event handle as returned from {@see listen}.

    Returns void

updateUser

  • updateUser(user: User): void
  • Updates the internally stored user object with the provided value. Also calls any stored user update callbacks with the new user object.

    since

    1.5

    example

    const sdk = new Muxy.SDK(); sdk.loaded().then(() => { sdk.updateUser({}); });

    Parameters

    Returns void

validateCode

  • validateCode(pin: string): Promise<any>
  • Attempts to validate a broadcaster's PIN with Muxy's Two-Factor auth system. For this to work, the broadcaster must have initiated a Two-Factor request for this channel within the auth window.

    Broadcaster-only functionality.

    async
    since

    1.0.0

    throws

    {TypeError} Will throw an error if pin is not a string.

    example

    sdk.validateCode('MUXY').then(() => { console.log('Validated! Go go go!'); });

    Parameters

    • pin: string

      The broadcaster's PIN to validate the associated auth token.

    Returns Promise<any>

    Resolves if the auth token associated with this PIN can now be used to make requests on behalf of this broadcaster, rejects with an error otherwise.

vote

  • vote(voteID: string, value: number): Promise<VoteData>
  • Submit a user vote associated with a vote identifier.

    async
    since

    1.0.0

    throws

    {TypeError} Will throw an error if voteID is not a string or if value is not a Number.

    example

    sdk.vote('poll-number-1', 1);

    Parameters

    • voteID: string

      The identifer to fetch associated vote data.

    • value: number

      Any numeric value to represent this user's vote. Note that only values of 0-5 will be included in the specific field returned from getVoteData.

    Returns Promise<VoteData>

    Will resolve on successful server-send. Rejects on failure.

Generated using TypeDoc