### DiscordSDK ready() usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/discord-sdk.md Shows the typical first call in an Activity's setup: create the SDK with a client ID, await ready(), then log the resolved guild and channel IDs. If the READY event never arrives (e.g. the app is not embedded in Discord), the promise never settles. ```typescript const discordSdk = new DiscordSDK(CLIENT_ID); await discordSdk.ready(); console.log('Discord client is ready', discordSdk.guildId, discordSdk.channelId); ``` -------------------------------- ### patchUrlMappings usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/patch-url-mappings.md Shows how to call patchUrlMappings when initializing the embedded-app-sdk. The example references a developer portal mapping of `/foo` to `foo.com` for a third-party library that makes an http request to foo.com. ```text `/foo` -> `foo.com` ``` -------------------------------- ### Install @discord/embedded-app-sdk Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/index.md Install the SDK as a dependency in your project. This is the standard npm command for adding the package to your package.json. ```shell npm install @discord/embedded-app-sdk ``` -------------------------------- ### Set activity example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md Example of setting a rich presence activity with type, details, and state fields. Requires the rpc.activities.write scope. ```typescript await discordSdk.commands.setActivity({ activity: { type: 0, details: 'Details', state: 'Playing', }, }); ``` -------------------------------- ### List entitlements with HTTP GET /applications/{app-id}/entitlements Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Lists entitlements for a user via the Discord HTTP API. Requires a Bot token for authorization. The example includes query parameters for user_id, sku_ids, with_payments, and limit, and shows the JSON response structure. ```bash curl https://discord.com/api/v6/applications/461618159171141643/entitlements?user_id=53908232506183680&sku_ids=53908232599983680&with_payments=true&limit=1 \ -H "Authorization: Bot " \ -H "Accept: application/json" // Returns { [ { "user_id": "53908232506183680", "sku_id": "53908232599983680", "application_id": "461618159171141643", "id": "53908232506183999", "type": 1, "payment": { "id": "538491076055400999", "currency": "usd", "amount": 999, "tax": 0, "tax_inclusive": false } } ] } ``` -------------------------------- ### startPurchase command: input interface and usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md The StartPurchaseInput interface defines the parameters for the startPurchase command: sku_id (required) and optional pid. The example shows how to call startPurchase with a SKU ID and log the number of entitlements returned. ```typescript export interface StartPurchaseInput { sku_id: string; pid?: number; } ``` ```typescript const entitlements = await discordSdk.commands.startPurchase({sku_id: '123456789'}); if (entitlements) console.log(`purchased ${entitlements.length} entitlement(s)`); ``` -------------------------------- ### PermissionUtils.can usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/utils.md Example of using PermissionUtils.can to check if the user has the CREATE_INSTANT_INVITE permission and conditionally open the invite dialog. ```typescript import {Permissions, PermissionUtils} from '@discord/embedded-app-sdk'; const {permissions} = await discordSdk.commands.getChannelPermissions(); const canInvite = PermissionUtils.can(Permissions.CREATE_INSTANT_INVITE, permissions); if (canInvite) await discordSdk.commands.openInviteDialog(); ``` -------------------------------- ### startPurchase Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md RPC command to start a purchase. Takes arguments and returns a Promise with the response data. ```APIDOC ## startPurchase ### Description RPC command to start a purchase. Takes arguments and returns a Promise with the response data. ### Method Function ### Endpoint `startPurchase(args)` ### Parameters - **args** (object) - Required - Arguments for the startPurchase command. ### Returns - **Promise** - Resolves with the response data from the Discord client. ### Example ```typescript const response = await discordSdk.commands.startPurchase(args); ``` ``` -------------------------------- ### questStartTimer usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Starts a quest timer by passing the quest_id. Returns a promise resolving to an object with a success boolean. ```typescript const {success} = await discordSdk.commands.questStartTimer({quest_id: questId}); ``` -------------------------------- ### Initiate purchase with RPCCommands.START_PURCHASE Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Starts the purchase flow in the Discord client for a given SKU. Call this after the SDK is ready; completion is signaled by the ENTITLEMENT_CREATE event, not by this command's resolution. ```javascript import {DiscordSDK} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(clientId); await discordSdk.ready(); await discordSdk.commands.startPurchase({sku_id: skuId}); ``` -------------------------------- ### RPCCommands.START_PURCHASE Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Initiates a purchase flow for a given SKU. This command only starts the purchase; completion is indicated by the ENTITLEMENT_CREATE event. ```APIDOC ## [RPC] START_PURCHASE ### Description Initiates a purchase flow for a given SKU. This command only starts the purchase; completion is indicated by the ENTITLEMENT_CREATE event. ### Method RPC Command ### Endpoint `RPCCommands.START_PURCHASE` ### Parameters #### Request Body - **sku_id** (string) - Required - The ID of the SKU to purchase. ### Request Example ```js import {DiscordSDK} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(clientId); await discordSdk.ready(); await discordSdk.commands.startPurchase({sku_id: skuId}); ``` ### Response #### Success Response (200) No response body is documented. The purchase flow is initiated asynchronously. ### Notes - Subscribe to `ENTITLEMENT_CREATE` to know when the purchase is completed. ``` -------------------------------- ### Migration diff for example files Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/activity-iframe-sdk-v2-migration.md A diff showing the changes required to migrate several example files from v1.11.0 to 2.0.0. The main change is removing `.data` from command responses, as the response is now the data itself. This diff covers files like `main.ts`, `CurrentGuild.tsx`, `EncourageHardwareAcceleration.tsx`, `InAppPurchase.tsx`, `OpenInviteDialog.tsx`, `PlatformBehaviors.tsx`, and `VoiceSettings.tsx`. ```diff examples/discord-activity-starter/packages/client/src/main.ts const {data: selectedVoiceChannel} = await discordSdk.commands.getSelectedVoiceChannel(); + const selectedVoiceChannel = await discordSdk.commands.getSelectedVoiceChannel(); examples/sdk-playground/packages/client/src/pages/CurrentGuild.tsx - const {data} = await discordSdk.commands.getSelectedVoiceChannel(); - const guildId = data?.guild_id; + const channel = await discordSdk.commands.getSelectedVoiceChannel(); + const guildId = channel?.guild_id; examples/sdk-playground/packages/client/src/pages/EncourageHardwareAcceleration.tsx - const {data} = await discordSdk.commands.encourageHardwareAcceleration(); - setHWAccEnabled(data?.enabled ?? null); + const {enabled} = await discordSdk.commands.encourageHardwareAcceleration(); + setHWAccEnabled(enabled === true); examples/sdk-playground/packages/client/src/pages/InAppPurchase.tsx - const skusResp = await discordSdk.commands.getSkus(); - setRpcSkus(skusResp.data as Sku[]); + const skus = await discordSdk.commands.getSkus(); + setRpcSkus(skus); examples/sdk-playground/packages/client/src/pages/OpenInviteDialog.tsx - const { data: {permissions} } = await discordSdk.commands.getChannelPermissions(); + const {permissions} = await discordSdk.commands.getChannelPermissions(); examples/sdk-playground/packages/client/src/pages/PlatformBehaviors.tsx - const {data} = await discordSdk.commands.getPlatformBehaviors(); - setPlatformBehaviors(data); + const behaviors = await discordSdk.commands.getPlatformBehaviors(); + setPlatformBehaviors(behaviors); examples/sdk-playground/packages/client/src/pages/VoiceSettings.tsx - const voiceSettingsResp = await discordSdk.commands.getVoiceSettings(); - setVoiceSettings(voiceSettingsResp.data); + const voiceSettings = await discordSdk.commands.getVoiceSettings(); - setVoiceSettings(voiceSettings); ``` -------------------------------- ### PriceUtils.formatPrice usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/utils.md Example of using PriceUtils.formatPrice to format SKU prices. Iterates over SKUs and logs the formatted price. ```typescript import {PriceUtils} from '@discord/embedded-app-sdk'; const {skus} = await discordSdk.commands.getSkus(); for (const sku of skus) { console.log(sku.name, PriceUtils.formatPrice(sku.price)); // => "The price is $10.99!" } ``` -------------------------------- ### attemptRemap usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/utils.md Shows how to import and call attemptRemap with a sample URL and mapping. The remapped host will be window.location.host. ```typescript import {attemptRemap} from '@discord/embedded-app-sdk'; const remapped = attemptRemap({url: new URL('https://google.com/path'), mappings: [{prefix: '/google', target: 'google.com'}]}); console.log(remapped.host); // window.location.host ``` -------------------------------- ### Initialize and authenticate DiscordSDK in TypeScript Source: https://github.com/discord/embedded-app-sdk/blob/main/README.md Minimal setup for the SDK: constructs a DiscordSDK instance, waits for READY, authorizes with scopes 'identify' and 'applications.commands', fetches an access token from your server endpoint '/.proxy/api/token', and authenticates. Replace YOUR_OAUTH2_CLIENT_ID with your OAuth2 client ID; see the linked docs for environment variables. ```typescript import {DiscordSDK} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(YOUR_OAUTH2_CLIENT_ID); async function setup() { // Wait for READY payload from the discord client await discordSdk.ready(); // Pop open the OAuth permission modal and request for access to scopes listed in scope array below const {code} = await discordSdk.commands.authorize({ client_id: YOUR_OAUTH2_CLIENT_ID, response_type: 'code', state: '', prompt: 'none', scope: ['identify', 'applications.commands'], }); // Retrieve an access_token from your application's server const response = await fetch('/.proxy/api/token', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ code, }), }); const {access_token} = await response.json(); // Authenticate with Discord client (using the access_token) auth = await discordSdk.commands.authenticate({ access_token, }); } ``` -------------------------------- ### authenticate usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Shows how to call authenticate after exchanging the authorize code. Requires discordSdk.ready() and an access_token obtained from your backend. Logs the authenticated user's username and scopes. ```typescript await discordSdk.ready(); const {code} = await discordSdk.commands.authorize({client_id, scope: ['identify', 'applications.commands']}); // exchange code on your server... const auth = await discordSdk.commands.authenticate({access_token}); console.log(`Authenticated as ${auth.user.username} with scopes`, auth.scopes); ``` -------------------------------- ### shareLink usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Example usage of the shareLink command. Shares a link with a message and logs if the message was sent. ```typescript const result = await discordSdk.commands.shareLink({message: 'Check out this activity!'}); if (result.didSendMessage) console.log('Shared via message'); ``` -------------------------------- ### Upgrade SDK packages: uninstall activity-iframe-sdk and install embedded-app-sdk Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/embedded-app-sdk-v1-migration.md Commands to upgrade from activity-iframe-sdk to embedded-app-sdk. Run these in sequence: first uninstall the old package, then install the new one. ```shell npm uninstall @discord-external/activity-iframe-sdk npm install @discord/embedded-app-sdk ``` -------------------------------- ### getUser usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Fetches a user by id and logs the username, or 'not found' if the user is null. ```typescript const user = await discordSdk.commands.getUser({id: '123456789012345678'}); console.log(user?.username ?? 'not found'); ``` -------------------------------- ### questStartTimer Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Starts a quest timer for a specified quest. ```APIDOC ## `questStartTimer` ### Description Starts a quest timer for a specified quest. ### Parameters #### Request Body - **quest_id** (string) - Required - Quest to start ### Returns `Promise<{success: boolean}>` ### Example ```typescript const {success} = await discordSdk.commands.questStartTimer({quest_id: questId}); if (!success) console.warn('Could not start quest timer'); ``` ``` -------------------------------- ### setConfig: input interface and usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md Defines the input type for the setConfig command and shows how to call it. The command enables interactive picture-in-picture mode and returns a promise resolving to an object with the same property. ```typescript export interface SetConfigInput { use_interactive_pip: boolean; } ``` ```typescript const config = await discordSdk.commands.setConfig({use_interactive_pip: true}); console.log(config.use_interactive_pip); ``` -------------------------------- ### Minimal usage of DiscordSDK Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/index.md Initializes the Discord SDK with your OAuth2 client ID, waits for the SDK to be ready, authorizes the user to get a code, and then authenticates with the access token obtained from your backend. ```typescript import {DiscordSDK} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(YOUR_OAUTH2_CLIENT_ID); async function setup() { await discordSdk.ready(); const {code} = await discordSdk.commands.authorize({ client_id: YOUR_OAUTH2_CLIENT_ID, response_type: 'code', state: '', prompt: 'none', scope: ['identify', 'applications.commands'], }); // exchange `code` for an access_token on your own backend... auth = await discordSdk.commands.authenticate({access_token}); } ``` -------------------------------- ### List SKUs with HTTP GET /api/applications/{app-id}/skus Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Use this curl command from backend servers to fetch SKUs as the source of truth. Requires a Bot token for authorization. The response is a JSON array of SKU objects. ```bash curl https://discord.com/api/v6/applications/461618159171141643/skus \ -H "Authorization: Bot " \ -H "Accept: application/json" // Returns { [ { "id": "53908232599983680", "type": 1, "flags" 8, "dependent_sku_id": null, "application_id": "461618159171141643", "manifest_labels": ["461618159171111111"], "name": "My Awesome Test SKU", "access_type": 1, "features": [1, 2, 3], "system_requirements": {}, "content_ratings": {}, "release_date": "1999-01-01", "legal_notice": {}, "price_tier": 1099, "price": {}, "premium": false, "locales": ["en-US"], "bundled_skus": null } ] } ``` -------------------------------- ### getPlatformBehaviors Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md RPC command to get platform behaviors. Takes arguments and returns a Promise with the response data. ```APIDOC ## getPlatformBehaviors ### Description RPC command to get platform behaviors. Takes arguments and returns a Promise with the response data. ### Method Function ### Endpoint `getPlatformBehaviors(args)` ### Parameters - **args** (object) - Required - Arguments for the getPlatformBehaviors command. ### Returns - **Promise** - Resolves with the response data from the Discord client. ### Example ```typescript const response = await discordSdk.commands.getPlatformBehaviors(args); ``` ``` -------------------------------- ### DiscordSDKMock usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/discord-sdk-mock.md Use this snippet to test SDK logic without network calls. It creates a mock SDK instance, awaits ready(), and calls getSkus(), which returns an empty SKU list (length 0) because no network request is made. The mock never performs postMessage calls, so it works in Node.js test environments. ```typescript import {DiscordSDKMock} from '@discord/embedded-app-sdk'; const mockSdk = new DiscordSDKMock(YOUR_OAUTH2_CLIENT_ID, 'guild_id', 'channel_id', null); async function main() { await mockSdk.ready(); const {skus} = await mockSdk.commands.getSkus(); console.log(skus.length); // 0 — no network call was made } ``` -------------------------------- ### Subscribe to SPEAKING_START with listener Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/discord-sdk.md Shows the listener function and subscribe call used with the Discord SDK. The listener receives an object with a user_id property and logs when a user starts speaking. ```typescript const listener = ({user_id}) => console.log(`${user_id} started speaking`); await discordSdk.subscribe('SPEAKING_START', listener, {channel_id: '...'}); ``` -------------------------------- ### openShareMomentDialog usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Opens the Share Moment dialog in the user's client so they can share the media as a message. The mediaUrl parameter is a Discord CDN URL (max 1024 characters) for the media to be shared. Returns Promise<{} | undefined | null>. ```typescript const {image_url} = await discordSdk.commands.initiateImageUpload(); await discordSdk.commands.openShareMomentDialog({mediaUrl: image_url}); ``` -------------------------------- ### GET /applications/{app-id}/entitlements Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Lists entitlements for a given user. Requires a Bot token for authorization. Supports optional query parameters to filter by user, SKU, payment data, and pagination. ```APIDOC ## GET /applications/{app-id}/entitlements ### Description Returns entitlements for a given user. Use this on your application backend to check entitlements of an arbitrary user, or in an administrative panel for your support team. Requires the Bot token for your application as authorization. ### Method GET ### Endpoint /applications/{app-id}/entitlements ### Parameters #### Query Parameters - **user_id** (snowflake) - Optional - The user id to look up entitlements for. - **sku_ids** (comma-delimited set of snowflakes) - Optional - The list of SKU ids to check entitlements for. - **with_payments** (bool) - Optional - Returns limited payment data for each entitlement. - **before** (snowflake) - Optional - Retrieve entitlements before this time. - **after** (snowflake) - Optional - Retrieve entitlements after this time. - **limit** (int) - Optional - Number of entitlements to return, 1-100, default 100. ### Request Example curl https://discord.com/api/v6/applications/461618159171141643/entitlements?user_id=53908232506183680&sku_ids=53908232599983680&with_payments=true&limit=1 \ -H "Authorization: Bot " \ -H "Accept: application/json" ### Response #### Success Response (200) Returns an array of entitlement objects. Each entitlement contains: - **user_id** (snowflake) - The user id. - **sku_id** (snowflake) - The SKU id. - **application_id** (snowflake) - The application id. - **id** (snowflake) - The entitlement id. - **type** (int) - The entitlement type. - **payment** (object) - Limited payment data if `with_payments` is true. Contains `id`, `currency`, `amount`, `tax`, `tax_inclusive`. #### Response Example { [ { "user_id": "53908232506183680", "sku_id": "53908232599983680", "application_id": "461618159171141643", "id": "53908232506183999", "type": 1, "payment": { "id": "538491076055400999", "currency": "usd", "amount": 999, "tax": 0, "tax_inclusive": false } } ] } ``` -------------------------------- ### getQuest command definition and usage Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Defines the getQuest command using schemaCommandFactory and shows how to call it. The command takes no input and returns a promise with quest details including external_cta_url. The example opens the external URL if the quest is not completed. ```typescript export const getQuest = schemaCommandFactory(Command.GET_QUEST); ``` ```typescript const quest = await discordSdk.commands.getQuest(); if (!quest.completed_at) window.open(quest.external_cta_url); ``` -------------------------------- ### BigFlagUtils usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/utils.md Example of using BigFlagUtils to get a flag, deserialize a value, and check if the flag is present. Note that the import path is not public API. ```typescript import BigFlagUtils, {isBigFlag} from '.../src/utils/BigFlagUtils'; // not public API const flag = BigFlagUtils.getFlag(11); // SEND_MESSAGES const value = BigFlagUtils.deserialize('34816'); console.log(BigFlagUtils.has(value, flag)); ``` -------------------------------- ### ready() Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/discord-sdk-mock.md Resolves immediately, simulating that the SDK is ready without any handshake. ```APIDOC ## ready() ### Description Always resolves immediately — there is no handshake to wait for. ### Method ready ### Endpoint `ready()` ### Parameters None ### Response #### Success Response Returns a Promise that resolves immediately. #### Response Example ```typescript await discordSdk.ready(); ``` ``` -------------------------------- ### getQuestEnrollmentStatus command definition and usage Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Defines the getQuestEnrollmentStatus command and shows how to call it with a required quest_id parameter. Returns a promise with is_enrolled and other fields. The example starts a quest timer if the user is not enrolled. ```typescript export const getQuestEnrollmentStatus = schemaCommandFactory(Command.GET_QUEST_ENROLLMENT_STATUS); ``` ```typescript const {is_enrolled} = await discordSdk.commands.getQuestEnrollmentStatus({quest_id: 'quest_123'}); if (!is_enrolled) await discordSdk.commands.questStartTimer({quest_id: 'quest_123'}); ``` -------------------------------- ### getRelationships command definition and usage Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Defines the getRelationships command and shows how to call it. Takes no input and returns a promise with a relationships array. The example filters relationships by type 1 to get friends. ```typescript export const getRelationships = schemaCommandFactory(Command.GET_RELATIONSHIPS); ``` ```typescript const {relationships} = await discordSdk.commands.getRelationships(); const friends = relationships.filter((r) => r.type === 1); ``` -------------------------------- ### startPurchase Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md Initiates a purchase for a given SKU and optional purchase ID, returning newly created entitlements or null. ```APIDOC ## `startPurchase` ### Description Initiates a purchase for a given SKU and optional purchase ID, returning newly created entitlements or null. ### Input - `sku_id` (string) - Required - SKU to purchase - `pid` (number) - Optional - Purchase ID ### Returns `Promise` - newly created entitlements, or `null`. ### Example ```typescript const entitlements = await discordSdk.commands.startPurchase({sku_id: '123456789'}); if (entitlements) console.log(`purchased ${entitlements.length} entitlement(s)`); ``` ``` -------------------------------- ### Clear activity example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md Example of clearing the rich presence by passing null as the activity parameter. ```typescript await discordSdk.commands.setActivity({activity: null}); ``` -------------------------------- ### subscribe('SPEAKING_START') Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/schema-events.md Documentation for subscribing to the SPEAKING_START event using the Discord Embedded App SDK. ```APIDOC ## [SUBSCRIBE] SPEAKING_START ### Description Subscribe to the SPEAKING_START event to receive notifications when a user starts speaking in a voice channel. The callback receives an event payload containing the user_id of the user who started talking. ### Method subscribe ### Endpoint subscribe('SPEAKING_START', callback, options) ### Parameters #### Event Name - **SPEAKING_START** (string) - Required - The name of the event to subscribe to. #### Callback - **callback** (function) - Required - A function that will be called with the event payload when the event occurs. The payload is of type `EventPayloadData<'SPEAKING_START'>` and contains a `user_id` field. #### Options - **channel_id** (string) - Optional - The ID of the channel to listen to. If not provided, the SDK will use the current channel ID from `discordSdk.channelId`. ### Request Example ```typescript import {DiscordSDK, EventPayloadData} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(CLIENT_ID); await discordSdk.ready(); type SPEAKING_START_EVENT = EventPayloadData<'SPEAKING_START'>; function handleStartTalking(event: SPEAKING_START_EVENT) { console.log(`user ${event.user_id} started talking`); } await discordSdk.subscribe('SPEAKING_START', handleStartTalking, { channel_id: discordSdk.channelId ?? undefined, }); ``` ### Response #### Success Response - **user_id** (string) - The ID of the user who started talking. #### Response Example ```typescript { user_id: '123456789012345678' } ``` ``` -------------------------------- ### shareInteraction usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands-generated.md Example usage of the shareInteraction command. Sends an interaction with a command, options, content, and a button component. ```typescript await discordSdk.commands.shareInteraction({ command: 'play', options: [{name: 'difficulty', value: 'hard'}], content: 'Come play with me!', components: [{type: 1, components: [{type: 2, style: 1, label: 'Join', custom_id: 'join_btn'}]}], }); ``` -------------------------------- ### ready() method implementation Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/discord-sdk.md Async method that resolves once the READY event has been received from the Discord client. Resolves immediately if the SDK is already ready; if the READY event never arrives (e.g. the app is not embedded in Discord), the promise never settles. ```typescript async ready() { if (this.isReady) { return; } else { await new Promise((resolve) => { this.eventBus.once(RPCEvents.READY, resolve); }); } } ``` -------------------------------- ### patchUrlMappings usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/utils.md Example usage of patchUrlMappings with two mappings and explicit options. patchFetch and patchXhr are enabled, patchWebSocket is disabled, and patchSrcAttributes is false (the default). ```typescript import {patchUrlMappings} from '@discord/embedded-app-sdk'; patchUrlMappings( [ {target: 'google.com', prefix: '/google'}, {target: 'api.example.com', prefix: '/api'}, ], { patchFetch: true, patchWebSocket: false, patchXhr: true, patchSrcAttributes: false, }, ); ``` -------------------------------- ### ready() Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/discord-sdk.md Method to wait for the Discord client READY event before proceeding with SDK operations. ```APIDOC ## `ready()` ### Description Resolves as soon as the READY event has been received from the Discord client; resolves immediately if the SDK is already ready. Typically the first call in an Activity's setup, since commands generally require the handshake to have completed. ### Method `ready()` ### Parameters No parameters. ### Returns `Promise` — resolves as soon as the READY event has been received from the Discord client; resolves immediately if the SDK is already ready. ### Example ```typescript const discordSdk = new DiscordSDK(CLIENT_ID); await discordSdk.ready(); console.log('Discord client is ready', discordSdk.guildId, discordSdk.channelId); ``` ### Notes If the READY event never arrives (e.g. the app is not embedded in Discord), the promise never settles. ``` -------------------------------- ### HANDSHAKE frame example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/endpoints.md Example HANDSHAKE frame sent by the SDK to the client. The payload includes the protocol version, encoding, client ID, frame ID, and optional SDK version. The target origin is document.referrer. ```javascript window.parent.postMessage( [0, {v: 1, encoding: 'json', client_id: '123456789', frame_id: '...', sdk_version: '2.5.0'}], document.referrer, ); ``` -------------------------------- ### encourageHardwareAcceleration Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md RPC command to encourage hardware acceleration. Takes arguments and returns a Promise with the response data. ```APIDOC ## encourageHardwareAcceleration ### Description RPC command to encourage hardware acceleration. Takes arguments and returns a Promise with the response data. ### Method Function ### Endpoint `encourageHardwareAcceleration(args)` ### Parameters - **args** (object) - Required - Arguments for the encourageHardwareAcceleration command. ### Returns - **Promise** - Resolves with the response data from the Discord client. ### Example ```typescript const response = await discordSdk.commands.encourageHardwareAcceleration(args); ``` ``` -------------------------------- ### encourageHardwareAcceleration Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md Encourages hardware acceleration and returns whether it is enabled. ```APIDOC ## encourageHardwareAcceleration ### Description Encourages hardware acceleration and returns whether it is enabled. ### Method N/A (SDK command) ### Endpoint N/A (SDK command) ### Parameters #### Request Body - **Input:** none (`void`) ### Request Example ```typescript const {enabled} = await discordSdk.commands.encourageHardwareAcceleration(); if (enabled) console.log('Hardware acceleration enabled'); ``` ### Response #### Success Response - **Returns:** `Promise<{enabled: boolean}>` #### Response Example ```json { "enabled": true } ``` ``` -------------------------------- ### setOrientationLockState: input types, factory, and usage example Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md Defines the input types and factory for the setOrientationLockState command, and shows a usage example. The command locks the orientation and optionally grid mode. Built with compatCommandFactory, it automatically retries with a fallback payload (dropping grid_lock_state) if the client rejects with RPCErrorCodes.INVALID_PAYLOAD (4000). ```typescript export interface SetOrientationLockStateInputFallback { lock_state: zod.infer; picture_in_picture_lock_state?: zod.infer | null; } export interface SetOrientationLockStateInput extends SetOrientationLockStateInputFallback { grid_lock_state?: zod.infer | null; } const fallbackTransform = (args: SetOrientationLockStateInput) => { return { lock_state: args.lock_state, picture_in_picture_lock_state: args.picture_in_picture_lock_state, }; }; export const setOrientationLockState = (sendCommand: TSendCommand) => compatCommandFactory({ sendCommand, cmd: Commands.SET_ORIENTATION_LOCK_STATE, response: EmptyResponse, fallbackTransform, }); ``` ```typescript await discordSdk.commands.setOrientationLockState({ lock_state: 2, // PORTRAIT grid_lock_state: 2, }); // Older clients automatically get the fallback: {lock_state: 2, picture_in_picture_lock_state: undefined} ``` -------------------------------- ### constructor(clientId: string, configuration?: SdkConfiguration) Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/discord-sdk.md Creates a new DiscordSDK instance. The constructor performs a handshake with the Discord client and initializes the communication channel. ```APIDOC ## constructor(clientId: string, configuration?: SdkConfiguration) ### Description Creates a new DiscordSDK instance. The constructor performs a handshake with the Discord client and initializes the communication channel. ### Method Constructor ### Endpoint `new DiscordSDK(clientId, configuration?)` ### Parameters #### Parameters - **clientId** (string) - Required - OAuth2 client ID of the Discord application - **configuration** (SdkConfiguration) - Optional - Optional SDK configuration. Defaults to `getDefaultSdkConfiguration()` → `{disableConsoleLogOverride: false}` ### SdkConfiguration Interface ```typescript interface SdkConfiguration { readonly disableConsoleLogOverride: boolean; } ``` ### Constructor Behavior - Adds a `window.addEventListener('message', this.handleMessage)` listener. - In a non-browser environment (`typeof window === 'undefined'`), the instance is initialized with empty `frameId`/`instanceId`, `null` IDs, and `platform = Platform.DESKTOP`, then returns early. - Reads required URL query parameters — missing params throw `Error`: - `frame_id` — missing → `Error('frame_id query param is not defined')` - `instance_id` — missing → `Error('instance_id query param is not defined')` - `platform` — missing → `Error('platform query param is not defined')`; invalid value → `Error('Invalid query param "platform" of "". Valid values are "desktop" or "mobile"')` - Reads optional URL query params: `custom_id`, `referrer_id`, `guild_id`, `channel_id`, `location_id`, `mobile_app_version`. - Resolves the RPC server source: `window.parent.opener ?? window.parent` with the `document.referrer` as origin (or `'*'`). - Registers an on-ready listener and immediately sends the handshake. ### Throws | Error | Condition | |-------|-----------| | `Error` | `frame_id`, `instance_id`, or `platform` query param missing | | `Error` | `platform` query param is not `"desktop"` or `"mobile"` | ``` -------------------------------- ### getSkus Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md RPC command to get SKUs. Takes arguments and returns a Promise with the response data. ```APIDOC ## getSkus ### Description RPC command to get SKUs. Takes arguments and returns a Promise with the response data. ### Method Function ### Endpoint `getSkus(args)` ### Parameters - **args** (object) - Required - Arguments for the getSkus command. ### Returns - **Promise** - Resolves with the response data from the Discord client. ### Example ```typescript const response = await discordSdk.commands.getSkus(args); ``` ``` -------------------------------- ### getEntitlements Source: https://github.com/discord/embedded-app-sdk/blob/main/_autodocs/api-reference/commands.md RPC command to get entitlements. Takes arguments and returns a Promise with the response data. ```APIDOC ## getEntitlements ### Description RPC command to get entitlements. Takes arguments and returns a Promise with the response data. ### Method Function ### Endpoint `getEntitlements(args)` ### Parameters - **args** (object) - Required - Arguments for the getEntitlements command. ### Returns - **Promise** - Resolves with the response data from the Discord client. ### Example ```typescript const response = await discordSdk.commands.getEntitlements(args); ``` ```