### Initialize DiscordSDK and Get Basic Info Source: https://context7.com/discord/embedded-app-sdk/llms.txt Instantiate the DiscordSDK with your client ID and call `ready()` to establish the RPC handshake. This example logs basic information about the Discord environment. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_OAUTH2_CLIENT_ID', { disableConsoleLogOverride: false, // set true to prevent console logs being forwarded to Discord }); async function setup() { // Wait for Discord to complete the RPC handshake await discordSdk.ready(); console.log('Platform:', discordSdk.platform); // 'desktop' | 'mobile' console.log('Instance ID:', discordSdk.instanceId); // unique activity instance console.log('Channel ID:', discordSdk.channelId); // voice/text channel the activity is in console.log('Guild ID:', discordSdk.guildId); // null in DMs console.log('SDK Version:', discordSdk.sdkVersion); // e.g. "2.5.0" } setup(); ``` -------------------------------- ### Install @discord/embedded-app-sdk Source: https://github.com/discord/embedded-app-sdk/blob/main/README.md Install the package using npm. This is the first step to integrating the SDK into your project. ```shell npm install @discord/embedded-app-sdk ``` -------------------------------- ### Start Purchase Flow Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Initiates the purchase flow within the Discord client for a given SKU. The actual completion of the purchase should be monitored via the `ENTITLEMENT_CREATE` event. ```APIDOC ### RPCCommands.START_PURCHASE #### Description To initiate a purchase, call the RPC command. This will begin the purchase flow within the Discord client. #### Method Signature `discordSdk.commands.startPurchase({sku_id: skuId})` #### Parameters - **sku_id** (string) - Required - The ID of the SKU to purchase. #### Request Example ```javascript import {DiscordSDK} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(clientId); await discordSdk.ready(); await discordSdk.commands.startPurchase({sku_id: skuId}); ``` #### Notes This command only initiates the purchase flow; subscribe to `ENTITLEMENT_CREATE` to know it has been completed. ``` -------------------------------- ### Uninstall Old SDK and Install New SDK Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/embedded-app-sdk-v1-migration.md Use npm to uninstall the old activity-iframe-sdk and install the new embedded-app-sdk. ```bash npm uninstall @discord-external/activity-iframe-sdk npm install @discord/embedded-app-sdk ``` -------------------------------- ### Start Discord In-App Purchase Source: https://context7.com/discord/embedded-app-sdk/llms.txt Initiates the Discord in-app purchase flow. Listen for 'ENTITLEMENT_CREATE' to detect successful completion. Ensure you have your client ID configured. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function purchaseItem(skuId: string) { await discordSdk.ready(); // Subscribe to purchase completion before initiating discordSdk.subscribe('ENTITLEMENT_CREATE', async ({ entitlement }) => { console.log('Purchase complete! Entitlement:', entitlement.id); // Verify with your backend: // await fetch('/api/verify-entitlement', { method: 'POST', body: JSON.stringify({ entitlement }) }); }); await discordSdk.commands.startPurchase({ sku_id: skuId }); } ``` -------------------------------- ### Initialize and Authenticate Discord SDK Source: https://github.com/discord/embedded-app-sdk/blob/main/README.md Minimal example for setting up the SDK, waiting for the READY payload, authorizing scopes, and authenticating with the Discord client. Ensure YOUR_OAUTH2_CLIENT_ID is replaced with your actual client ID. Visit the provided documentation for more details on environment variables and OAuth2 credentials. ```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, }); } ``` -------------------------------- ### Initiate Purchase Flow with RPC Command Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Call this RPC command to start the purchase flow within the Discord client. Subscribe to the ENTITLEMENT_CREATE event to be notified when the purchase is completed. ```javascript import {DiscordSDK} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(clientId); await discordSdk.ready(); await discordSdk.commands.startPurchase({sku_id: skuId}); ``` -------------------------------- ### Full Activity Bootstrap Pattern Source: https://context7.com/discord/embedded-app-sdk/llms.txt This pattern covers SDK setup, OAuth, authentication, URL proxying, and event subscription. Use the mock SDK in local development and the real SDK within a Discord iframe. Ensure 'YOUR_CLIENT_ID' is replaced with your actual client ID. ```typescript import { DiscordSDK, DiscordSDKMock, Events, patchUrlMappings, Platform, } from '@discord/embedded-app-sdk'; // Use mock in local dev, real SDK inside Discord iframe const isDiscordIframe = new URLSearchParams(window.location.search).has('frame_id'); const discordSdk = isDiscordIframe ? new DiscordSDK('YOUR_CLIENT_ID') : new DiscordSDKMock('YOUR_CLIENT_ID', null, null, null); let auth: Awaited>; async function bootstrap() { await discordSdk.ready(); // Patch network requests through Discord proxy patchUrlMappings([{ prefix: '/api', target: 'your-api.example.com' }]); // OAuth2 authorization const { code } = await discordSdk.commands.authorize({ client_id: 'YOUR_CLIENT_ID', response_type: 'code', state: '', prompt: 'none', scope: ['identify', 'guilds', 'rpc.activities.write'], }); // Exchange code for token on your backend const { access_token } = await fetch('/api/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }).then((r) => r.json()); // Authenticate with Discord auth = await discordSdk.commands.authenticate({ access_token }); console.log(`Hello, ${auth.user.username}!`); // Update rich presence await discordSdk.commands.setActivity({ activity: { details: 'Playing the game', state: 'In lobby', timestamps: { start: Math.floor(Date.now() / 1000) }, }, }); // Lock orientation on mobile if (discordSdk.platform === Platform.MOBILE) { await discordSdk.commands.setOrientationLockState({ lock_state: 'LANDSCAPE' }); } // Subscribe to participant changes await discordSdk.subscribe('ACTIVITY_INSTANCE_PARTICIPANTS_UPDATE', ({ participants }) => { console.log('Players in session:', participants.length); }); // Subscribe to voice events if (discordSdk.channelId) { await discordSdk.subscribe( 'VOICE_STATE_UPDATE', (vs) => console.log('Voice update:', vs.user?.username), { channel_id: discordSdk.channelId }, ); } console.log('Activity ready on', discordSdk.platform, '| instance:', discordSdk.instanceId); } bootstrap().catch(console.error); ``` -------------------------------- ### DiscordSDK Constructor and Initialization Source: https://context7.com/discord/embedded-app-sdk/llms.txt Instantiate the DiscordSDK with your OAuth2 client ID and call `ready()` to initialize the SDK and wait for the RPC handshake to complete. This example also shows how to access basic SDK properties like platform and instance ID. ```APIDOC ## DiscordSDK Constructor and Initialization Instantiate `DiscordSDK` with your OAuth2 client ID. The constructor reads required query parameters (`frame_id`, `instance_id`, `platform`) injected by Discord into the iframe URL. Call `ready()` before issuing any commands. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_OAUTH2_CLIENT_ID', { disableConsoleLogOverride: false, // set true to prevent console logs being forwarded to Discord }); async function setup() { // Wait for Discord to complete the RPC handshake await discordSdk.ready(); console.log('Platform:', discordSdk.platform); // 'desktop' | 'mobile' console.log('Instance ID:', discordSdk.instanceId); // unique activity instance console.log('Channel ID:', discordSdk.channelId); // voice/text channel the activity is in console.log('Guild ID:', discordSdk.guildId); // null in DMs console.log('SDK Version:', discordSdk.sdkVersion); // e.g. "2.5.0" } setup(); ``` ``` -------------------------------- ### Get SKUs from Application Client Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Use this RPC command from the Application client to retrieve a list of available SKUs. The client must be authenticated by the user. SKUs without prices are automatically filtered out. ```javascript import {DiscordSDK} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(clientId); await discordSdk.ready(); const skus = await discordSdk.commands.getSkus(); console.log(`SKUs: ${skus}`); ``` -------------------------------- ### Get SKUs via HTTP API Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md This HTTP API endpoint retrieves SKUs for a given application. It requires your application's Bot token for authorization and should be called from your application's backend servers. This serves as the source of truth for SKU data. ```bash curl https://discord.com/api/v6/applications/461618159171141643/skus \ -H "Authorization: Bot " \ -H "Accept: application/json" ``` ```json { "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 } ``` -------------------------------- ### Get User Entitlements via HTTP API Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Use this API on your application backend to check entitlements for a given user. Requires your application's Bot token for authorization. You can optionally filter by SKU IDs and include payment data. ```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" ``` -------------------------------- ### Manage Discord Quests Source: https://context7.com/discord/embedded-app-sdk/llms.txt Interact with Discord Quests, including fetching quest details, checking enrollment status, and starting the quest timer. Subscribe to 'QUEST_ENROLLMENT_STATUS_UPDATE' for real-time changes. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function handleQuest(questId: string) { await discordSdk.ready(); // Fetch quest details const quest = await discordSdk.commands.getQuest({ quest_id: questId }); console.log('Quest ID:', quest.quest_id); console.log('CTA URL:', quest.external_cta_url); console.log('Enrolled at:', quest.enrolled_at); console.log('Completed at:', quest.completed_at); // Check enrollment const enrollment = await discordSdk.commands.getQuestEnrollmentStatus({ quest_id: questId }); console.log('Enrolled:', enrollment.is_enrolled); // Start the quest timer if enrolled if (enrollment.is_enrolled) { const { success } = await discordSdk.commands.questStartTimer({ quest_id: questId }); console.log('Timer started:', success); } // Listen for enrollment changes discordSdk.subscribe('QUEST_ENROLLMENT_STATUS_UPDATE', (data) => { console.log('Quest enrollment updated:', data.quest_id, 'enrolled:', data.is_enrolled); }); } ``` -------------------------------- ### Get Platform Behaviors with Discord SDK Source: https://context7.com/discord/embedded-app-sdk/llms.txt Retrieves platform-specific behaviors that influence activity rendering and behavior, such as whether the iOS keyboard resizes the view. Useful for adapting the UI to different platforms. ```typescript import { DiscordSDK, Platform } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function configurePlatform() { await discordSdk.ready(); const behaviors = await discordSdk.commands.getPlatformBehaviors(); if (discordSdk.platform === Platform.MOBILE) { console.log('iOS keyboard resizes view:', behaviors.iosKeyboardResizesView); // Adjust layout accordingly } } ``` -------------------------------- ### commands.startPurchase Source: https://context7.com/discord/embedded-app-sdk/llms.txt Initiates the Discord in-app purchase flow for a given SKU ID. Listen for `ENTITLEMENT_CREATE` to detect successful completion. ```APIDOC ## commands.startPurchase ### Description Initiates the Discord in-app purchase flow for the given SKU ID. Listen for `ENTITLEMENT_CREATE` to detect successful completion. ### Method Signature ```typescript await discordSdk.commands.startPurchase({ sku_id: string }) ``` ### Parameters #### Request Body - **sku_id** (string) - Required - The SKU ID of the item to purchase. ### Request Example ```typescript await discordSdk.commands.startPurchase({ sku_id: 'example_sku_id' }); ``` ### Response This command does not return a value directly. Successful completion is indicated by the `ENTITLEMENT_CREATE` event. ``` -------------------------------- ### commands.initiateImageUpload Source: https://context7.com/discord/embedded-app-sdk/llms.txt Opens the Discord media picker and returns a CDN URL for the image the user selects or captures. ```APIDOC ## commands.initiateImageUpload ### Description Opens the Discord media picker and returns a CDN URL for the image the user selects or captures. ### Method POST (assumed, as it's a command that modifies state/opens UI) ### Endpoint /initiateImageUpload ### Parameters (No parameters required) ### Request Example ```json {} ``` ### Response #### Success Response (200) - **image_url** (string) - A Discord CDN URL for the uploaded image. ### Response Example ```json { "image_url": "DISCORD_CDN_IMAGE_URL" } ``` ``` -------------------------------- ### Get User Locale with Discord SDK Source: https://context7.com/discord/embedded-app-sdk/llms.txt Retrieves the user's current locale setting from Discord, which is useful for localizing the activity's user interface. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function getLocale() { await discordSdk.ready(); const { locale } = await discordSdk.commands.userSettingsGetLocale(); console.log('User locale:', locale); // e.g. "en-US", "fr", "ja" return locale; } ``` -------------------------------- ### Get SKUs for In-App Purchases Source: https://context7.com/discord/embedded-app-sdk/llms.txt Retrieves published SKUs (in-app purchase items) for the application. SKUs without prices are automatically filtered out. Use `PriceUtils.formatPrice` for display. ```typescript import { DiscordSDK, PriceUtils } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function listStoreItems() { await discordSdk.ready(); const { skus } = await discordSdk.commands.getSkus(); skus.forEach((sku) => { const displayPrice = PriceUtils.formatPrice(sku.price, 'en-US'); console.log(`${sku.name} (${sku.id}): ${displayPrice}`); console.log(' Type:', sku.type); // 2 = DURABLE, 3 = CONSUMABLE }); return skus; } ``` -------------------------------- ### Initiate Image Upload with Discord SDK Source: https://context7.com/discord/embedded-app-sdk/llms.txt Opens the Discord media picker to allow the user to select or capture an image. Returns a Discord CDN URL for the uploaded image. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function uploadImage() { await discordSdk.ready(); const { image_url } = await discordSdk.commands.initiateImageUpload(); console.log('Uploaded image URL:', image_url); // image_url is a Discord CDN URL ready to use in openShareMomentDialog return image_url; } ``` -------------------------------- ### Get Connected Participants with commands.getActivityInstanceConnectedParticipants Source: https://context7.com/discord/embedded-app-sdk/llms.txt Returns all users currently connected to this specific activity instance across all channels. Useful for building participant lists and managing game state. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function getParticipants() { await discordSdk.ready(); const { participants } = await discordSdk.commands.getActivityInstanceConnectedParticipants(); console.log(`${participants.length} participant(s) in this instance:`); participants.forEach((p) => { console.log(` - ${p.username} (${p.id})`); }); return participants; } ``` -------------------------------- ### Get Entitlements Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Retrieves entitlements for a given user. This API can be used on your application backend to check entitlements of an arbitrary user or for administrative purposes. It requires the Bot token for authorization. ```APIDOC ## HTTP GET /applications/{app-id}/entitlements ### Description This HTTP API returns entitlements for a given user. You can use this on your application backend to check entitlements of an arbitrary user, or perhaps in an administrative panel for your support team. This API requires using the Bot token for your application as authorization. ### Method GET ### Endpoint `/applications/{app-id}/entitlements` ### Parameters #### Query Parameters - **user_id?** (snowflake) - Required - the user id to look up entitlements for - **sku_ids?** (comma-delimited set of snowflakes) - Optional - the list 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 ```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" ``` ### Response #### Success Response (200) - **Array of Entitlement objects** #### Response Example ```json [ { "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 } } ] ``` ``` -------------------------------- ### commands.encourageHardwareAcceleration Source: https://context7.com/discord/embedded-app-sdk/llms.txt Prompts the user to enable hardware acceleration in their Discord client if it is currently disabled. Returns whether it is now enabled. ```APIDOC ## commands.encourageHardwareAcceleration ### Description Prompts the user to enable hardware acceleration in their Discord client if it is currently disabled. Returns whether it is now enabled. ### Method POST ### Endpoint /encourageHardwareAcceleration ### Response #### Success Response (200) - **enabled** (boolean) - Indicates if hardware acceleration is now enabled. ``` -------------------------------- ### Migrate Event Subscriptions to Define Event Shape Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/embedded-app-sdk-v1-migration.md Update event type definitions to use `EventPayloadData` from the embedded-app-sdk for better type safety. This example shows migrating the `ACTIVITY_INSTANCE_PARTICIPANTS_UPDATE` event. ```typescript import {Events, EventPayloadData} from '@discord/embedded-app-sdk'; type UpdateEvent = EventPayloadData<'ACTIVITY_INSTANCE_PARTICIPANTS_UPDATE'>; ``` -------------------------------- ### discordSdk.ready() Source: https://context7.com/discord/embedded-app-sdk/llms.txt Waits for the `READY` event from the Discord RPC server, signaling that the handshake is complete and commands can be issued. This method resolves immediately if the SDK is already ready. ```APIDOC ## discordSdk.ready() Waits for the `READY` event from the Discord RPC server, which signals that the handshake is complete and commands can be issued. Resolves immediately if the SDK is already ready. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function main() { await discordSdk.ready(); // must be awaited before any command console.log('Discord SDK is ready'); } main(); ``` ``` -------------------------------- ### Get User Entitlements with Discord SDK Source: https://context7.com/discord/embedded-app-sdk/llms.txt Retrieves current entitlements (completed purchases) for the authenticated user. It's recommended to validate entitlements against your backend for security-critical use cases. Excludes test mode purchases. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function checkOwnership(skuId: string) { await discordSdk.ready(); const { entitlements } = await discordSdk.commands.getEntitlements({}); const TEST_MODE_PURCHASE = 4; const owns = entitlements.some( (e) => e.sku_id === skuId && !e.consumed && e.type !== TEST_MODE_PURCHASE, ); console.log(`User owns SKU ${skuId}:`, owns); return owns; } ``` -------------------------------- ### Sync RPC Schema Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/schema-gen.md Run this command from the root of the GitHub repository to sync the RPC schema. Ensure you provide the correct path to the schema file within your monorepo. ```bash npm run sync -- --path path/to/monorepo/discord_common/js/packages/rpc-schema/generated/schema.json ``` -------------------------------- ### Initialize and Use DiscordSDKMock Source: https://context7.com/discord/embedded-app-sdk/llms.txt Initialize the mock with necessary IDs and override specific command responses for testing. Use the mock in tests instead of the real SDK. ```typescript import { DiscordSDKMock } from '@discord/embedded-app-sdk'; // Initialize the mock with clientId, guildId, channelId, locationId const discordSdkMock = new DiscordSDKMock( 'YOUR_CLIENT_ID', '123456789012345678', // guildId '987654321098765432', // channelId '111222333444555666', // locationId ); // Override specific command responses discordSdkMock._updateCommandMocks({ authenticate: () => Promise.resolve({ access_token: 'test_token', user: { id: 'user-123', username: 'TestPlayer', discriminator: '0', avatar: null, public_flags: 0, }, scopes: ['identify'], expires: '2099-01-01T00:00:00Z', application: { id: 'app-456', name: 'Test App', description: '', icon: null }, }), getChannel: () => Promise.resolve({ id: '987654321098765432', name: 'general', type: 2, // GUILD_VOICE voice_states: [], messages: [], }), }); // In tests, use the mock instead of the real SDK async function runTest() { await discordSdkMock.ready(); // resolves immediately const auth = await discordSdkMock.commands.authenticate({ access_token: 'test_token' }); console.log('Mock user:', auth.user.username); // "TestPlayer" // Manually emit events to test subscription handlers discordSdkMock.subscribe('VOICE_STATE_UPDATE', (data) => { console.log('Voice event received in test:', data); }); discordSdkMock.emitEvent('VOICE_STATE_UPDATE', { user: { id: 'u1', username: 'Alice' }, voice_state: { mute: true, deaf: false, self_mute: false, self_deaf: false, suppress: false }, nick: 'Alice', volume: 100, mute: false, pan: { left: 0, right: 0 }, }); // Trigger READY manually in advanced mock scenarios discordSdkMock.emitReady(); } runTest(); ``` -------------------------------- ### commands.setConfig Source: https://context7.com/discord/embedded-app-sdk/llms.txt Configures interactive picture-in-picture (PiP) mode for the activity. ```APIDOC ## commands.setConfig ### Description Configures interactive picture-in-picture (PiP) mode for the activity. ### Method POST ### Endpoint /setConfig ### Parameters #### Request Body - **use_interactive_pip** (boolean) - Required - Whether to enable interactive PiP mode. ``` -------------------------------- ### Configure URL Mappings with Network Shim Options Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/embedded-app-sdk-v1-migration.md Migrate from initializeNetworkShims to patchUrlMappings. This utility allows for URL mapping configuration and provides options to patch fetch, WebSocket, XHR, and HTML src attributes. ```typescript import {patchUrlMappings} from '@discord/embedded-app-sdk'; patchUrlMappings( [ { target: 'google.com', prefix: '/google', }, ], { patchFetch: true, // Defaults to true patchWebSocket: true, // Defaults to true patchXhr: true, // Defaults to true patchSrcAttributes: true, // Defaults to false (potentially compute expensive for your UI) } ); ``` -------------------------------- ### commands.authenticate Source: https://context7.com/discord/embedded-app-sdk/llms.txt Authenticates the activity with an access token obtained from your backend. This command returns the authenticated user's profile, granted scopes, and application details. ```APIDOC ## commands.authenticate Authenticates the activity with an access token obtained from your backend. Returns the authenticated user's profile, granted scopes, and application details. ### Method POST ### Endpoint /oauth2/authenticate ### Parameters #### Request Body - **access_token** (string) - Required - The access token obtained from your backend after exchanging the authorization code. ### Request Example ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function authenticate(access_token: string) { await discordSdk.ready(); const auth = await discordSdk.commands.authenticate({ access_token }); console.log('User ID:', auth.user.id); console.log('Username:', auth.user.username); console.log('Scopes:', auth.scopes); console.log('Expires:', auth.expires); console.log('App Name:', auth.application.name); return auth; } ``` ### Response #### Success Response (200) - **access_token** (string) - The access token. - **user** (object) - The authenticated user's profile. - **id** (string) - User ID. - **username** (string) - Username. - **discriminator** (string) - User discriminator. - **avatar** (string) - User avatar hash. - **public_flags** (number) - User's public flags. - **scopes** (array of strings) - The scopes granted to the access token. - **expires** (string) - The expiration date of the access token in ISO 8601 format. - **application** (object) - Details about the application. - **id** (string) - Application ID. - **name** (string) - Application name. - **description** (string) - Application description. - **icon** (string) - Application icon hash. ### Response Example ```json { "access_token": "abc123", "user": { "id": "123", "username": "alice", "discriminator": "0", "avatar": "hash", "public_flags": 0 }, "scopes": ["identify", "guilds"], "expires": "2025-01-01T00:00:00.000Z", "application": { "id": "456", "name": "My Activity", "description": "...", "icon": "hash" } } ``` ``` -------------------------------- ### commands.openInviteDialog Source: https://context7.com/discord/embedded-app-sdk/llms.txt Opens the generic invite dialog allowing the user to invite others to the current activity channel. ```APIDOC ## commands.openInviteDialog ### Description Opens the generic invite dialog allowing the user to invite others to the current activity channel. ### Method POST (assumed, as it's a command that modifies state/opens UI) ### Endpoint /openInviteDialog ### Parameters (No parameters required) ### Request Example ```json {} ``` ### Response (No specific response details provided in source, typically indicates success or failure of the command execution itself.) ``` -------------------------------- ### Listing SKUs via RPC Command Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md This RPC command is used from the Application client to retrieve a list of available SKUs. The Application client must be authenticated by the user to call this command. SKUs without prices are automatically filtered out. ```APIDOC ## `RPCCommands.GET_SKUS` ### Description Retrieves a list of SKUs available for the application. ### Method `discordSdk.commands.getSkus()` ### Parameters None ### Request Example ```javascript import {DiscordSDK} from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK(clientId); await discordSdk.ready(); const skus = await discordSdk.commands.getSkus(); console.log(`SKUs: ${skus}`); ``` ### Response #### Success Response - **skus** (Array): A list of Sku objects. #### Response Example ```json [ { "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 } ] ``` ``` -------------------------------- ### Migrate initializeNetworkShims to patchUrlMappings Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/embedded-app-sdk-v1-migration.md Replaces the `initializeNetworkShims` method with the `patchUrlMappings` function for configuring network shims. ```typescript import {DiscordSDK, DiscordSDKMock, IDiscordSDK, patchUrlMappings} from '@discord/embedded-app-sdk'; patchUrlMappings(mappings); ``` -------------------------------- ### Open Generic Invite Dialog with Discord SDK Source: https://context7.com/discord/embedded-app-sdk/llms.txt Opens the generic Discord invite dialog to allow users to invite others to the current activity channel. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function showInvite() { await discordSdk.ready(); await discordSdk.commands.openInviteDialog(); } ``` -------------------------------- ### Listing SKUs via HTTP API Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md This HTTP API returns SKUs for a given application. It requires the Bot token for authorization and should be called from application backend servers. This serves as the source of truth for SKUs. ```APIDOC ## `HTTP GET /api/applications/{app-id}/skus` ### Description Retrieves a list of SKUs for a specific application. ### Method GET ### Endpoint `/api/applications/{app-id}/skus` ### Parameters #### Path Parameters - **app-id** (string) - Required - The ID of the application. #### Query Parameters None #### Request Body None ### Authorization Requires Bot token in the `Authorization` header: `Bot ` ### Request Example ```bash curl https://discord.com/api/v6/applications/461618159171141643/skus \ -H "Authorization: Bot " \ -H "Accept: application/json" ``` ### Response #### Success Response (200) - **skus** (Array): A list of Sku objects. #### Response Example ```json [ { "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 } ] ``` ``` -------------------------------- ### Encourage Hardware Acceleration with Discord SDK Source: https://context7.com/discord/embedded-app-sdk/llms.txt Prompts the user to enable hardware acceleration in their Discord client if it is currently disabled. Returns whether it is now enabled. Use this to improve performance. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function ensureHardwareAcceleration() { await discordSdk.ready(); const { enabled } = await discordSdk.commands.encourageHardwareAcceleration(); if (!enabled) { console.warn('Hardware acceleration is disabled. Performance may be degraded.'); } } ``` -------------------------------- ### Await Discord SDK Ready State Source: https://context7.com/discord/embedded-app-sdk/llms.txt Ensure the Discord SDK is ready before issuing any commands by awaiting the `discordSdk.ready()` promise. This is crucial for a stable connection. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function main() { await discordSdk.ready(); // must be awaited before any command console.log('Discord SDK is ready'); } main(); ``` -------------------------------- ### commands.getPlatformBehaviors Source: https://context7.com/discord/embedded-app-sdk/llms.txt Returns platform-specific behaviors that affect how the activity should render or behave, such as whether the iOS keyboard resizes the view. ```APIDOC ## commands.getPlatformBehaviors ### Description Returns platform-specific behaviors that affect how the activity should render or behave, such as whether the iOS keyboard resizes the view. ### Method GET (assumed, as it retrieves information) ### Endpoint /getPlatformBehaviors ### Parameters (No parameters required) ### Request Example ```json {} ``` ### Response #### Success Response (200) - **iosKeyboardResizesView** (boolean) - Indicates if the iOS keyboard resizes the view. ### Response Example ```json { "iosKeyboardResizesView": true } ``` ``` -------------------------------- ### Formatting Price with PriceUtils Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md A utility provided by the Discord SDK to help format prices, considering different currencies and their expected display units. ```APIDOC ## `PriceUtils.formatPrice` ### Description Formats a SKU price object into a human-readable string, localized for the user's currency. ### Method `PriceUtils.formatPrice(priceObject)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **priceObject** (object) - Required - The price object from a SKU, containing `amount` and `currency`. - **amount** (number) - The price amount. - **currency** (string) - The currency code (e.g., "USD"). ### Request Example ```typescript import {PriceUtils} from '@discord/embedded-app-sdk'; const sku = { /* ... sku object ... */ }; // Assume sku.price is available const displayPrice = PriceUtils.formatPrice(sku.price); console.log(`The price is ${displayPrice}!`); ``` ### Response #### Success Response - **formattedPrice** (string): The price formatted as a string (e.g., "$10.99"). #### Response Example ``` The price is $10.99! ``` ``` -------------------------------- ### commands.authorize Source: https://context7.com/discord/embedded-app-sdk/llms.txt Requests OAuth2 authorization from the user. This command should be called immediately after `ready()`. It opens a Discord OAuth modal if the user hasn't granted the requested scopes and returns an authorization code. ```APIDOC ## commands.authorize Requests OAuth2 authorization from the user. Should be called immediately after `ready()`. ### Method POST ### Endpoint /oauth2/authorize ### Parameters #### Query Parameters - **client_id** (string) - Required - Your application's OAuth2 client ID. - **response_type** (string) - Required - Must be set to `code`. - **state** (string) - Optional - An opaque value used to maintain state between the request and the callback. - **prompt** (string) - Optional - Controls whether the user is prompted for authorization. Common values include `consent` or `none`. - **scope** (array of strings) - Required - A space-separated list of scopes your application is requesting. ### Request Example ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function authorize() { await discordSdk.ready(); const { code } = await discordSdk.commands.authorize({ client_id: 'YOUR_CLIENT_ID', response_type: 'code', state: '', prompt: 'none', scope: ['identify', 'guilds', 'applications.commands'], }); // Exchange code for access_token on your backend const response = await fetch('/.proxy/api/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }); const { access_token } = await response.json(); return access_token; } ``` ``` -------------------------------- ### Configure Interactive Picture-in-Picture Mode Source: https://context7.com/discord/embedded-app-sdk/llms.txt Configures interactive picture-in-picture (PiP) mode for the activity. This enables a more interactive PiP experience for users. ```typescript import { DiscordSDK } from '@discord/embedded-app-sdk'; const discordSdk = new DiscordSDK('YOUR_CLIENT_ID'); async function enablePiP() { await discordSdk.ready(); const { use_interactive_pip } = await discordSdk.commands.setConfig({ use_interactive_pip: true, }); console.log('Interactive PiP enabled:', use_interactive_pip); } ``` -------------------------------- ### commands.openExternalLink Source: https://context7.com/discord/embedded-app-sdk/llms.txt Opens an external URL in the user's browser. Discord may prompt the user to confirm before navigating. ```APIDOC ## commands.openExternalLink ### Description Opens an external URL in the user's browser. Discord may prompt the user to confirm before navigating. ### Method POST ### Endpoint /openExternalLink ### Parameters #### Request Body - **url** (string) - Required - The URL to open. ### Request Example ```json { "url": "https://docs.discord.com/developers/activities/overview" } ``` ### Response #### Success Response (200) - **opened** (boolean) - Indicates if the link was successfully opened. ``` -------------------------------- ### commands.openShareMomentDialog Source: https://context7.com/discord/embedded-app-sdk/llms.txt Opens a Discord share dialog so the user can share a media URL (Discord CDN) as a message in any channel. ```APIDOC ## commands.openShareMomentDialog ### Description Opens a Discord share dialog so the user can share a media URL (Discord CDN) as a message in any channel. ### Method POST (assumed, as it's a command that modifies state/opens UI) ### Endpoint /openShareMomentDialog ### Parameters #### Request Body - **mediaUrl** (string) - Required - A Discord CDN URL for the media to share. Must be a Discord CDN URL, max 1024 chars. ### Request Example ```json { "mediaUrl": "DISCORD_CDN_IMAGE_URL" } ``` ### Response (No specific response details provided in source, typically indicates success or failure of the command execution itself.) ``` -------------------------------- ### V1 Command Return Shapes Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/activity-iframe-sdk-v2-migration.md Illustrates the different return shapes ('Data' vs. 'Payload') for commands in v1 of the SDK. Use this to identify how your v1 code handles command responses. ```typescript // V1 // "Data" command const {code} = await sdk.commands.authorize(); // "Payload" command const { cmd, data: {permissions}, evt, nonce, } = await discordSdk.commands.getChannelPermissions(); ``` -------------------------------- ### commands.getSkus Source: https://context7.com/discord/embedded-app-sdk/llms.txt Retrieves published SKUs (in-app purchase items) for the application. SKUs without prices are filtered out automatically. ```APIDOC ## commands.getSkus ### Description Retrieves published SKUs (in-app purchase items) for the application. SKUs without prices are filtered out automatically. ### Method GET ### Endpoint /getSkus ### Response #### Success Response (200) - **skus** (array) - An array of SKU objects. Each object contains: - **id** (string) - The SKU ID. - **name** (string) - The SKU name. - **type** (integer) - The SKU type (2 for DURABLE, 3 for CONSUMABLE). - **price** (object) - The SKU price. Contains currency and amount. ``` -------------------------------- ### Format Localized Price Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/in-app-purchases.md Utilize the PriceUtils provided by the Discord SDK to easily format SKU prices, including currency, for display to users. This utility handles the complexities of different currency formats. ```typescript import {PriceUtils} from '@discord/embedded-app-sdk'; const displayPrice = PriceUtils.formatPrice(sku.price); console.log(`The price is ${displayPrice}!`); ``` -------------------------------- ### Migrate getVoiceSettings Response Structure Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/activity-iframe-sdk-v2-migration.md In v1, voice settings were nested under a 'data' property. In v2, the voice settings are returned directly. ```typescript const voiceSettingsResp = await discordSdk.commands.getVoiceSettings(); setVoiceSettings(voiceSettingsResp.data); const voiceSettings = await discordSdk.commands.getVoiceSettings(); setVoiceSettings(voiceSettings); ``` -------------------------------- ### commands.getEntitlements Source: https://context7.com/discord/embedded-app-sdk/llms.txt Retrieves current entitlements (completed purchases) for the authenticated user. Validate against your backend for security-critical use cases. ```APIDOC ## commands.getEntitlements ### Description Retrieves current entitlements (completed purchases) for the authenticated user. Validate against your backend for security-critical use cases. ### Method GET ### Endpoint /getEntitlements ### Parameters #### Query Parameters - **sku_id** (string) - Optional - Filter entitlements by a specific SKU ID. ### Response #### Success Response (200) - **entitlements** (array) - An array of entitlement objects. Each object contains: - **sku_id** (string) - The ID of the SKU purchased. - **consumed** (boolean) - Whether the entitlement has been consumed. - **type** (integer) - The type of entitlement (e.g., 4 for TEST_MODE_PURCHASE). ``` -------------------------------- ### commands.shareLink Source: https://context7.com/discord/embedded-app-sdk/llms.txt Opens a modal allowing the user to share the activity's join link. Returns whether the link was successfully shared. ```APIDOC ## commands.shareLink ### Description Opens a modal allowing the user to share the activity's join link. Returns whether the link was successfully shared. ### Method POST (assumed, as it's a command that modifies state/opens UI) ### Endpoint /shareLink ### Parameters #### Request Body - **message** (string) - Optional - A message to accompany the shared link. - **custom_id** (string) - Optional - A custom identifier for the shared link. - **referrer_id** (string) - Optional - An identifier for the referrer, often the instance ID. ### Request Example ```json { "message": "Come join my game!", "custom_id": "game-room-42", "referrer_id": "YOUR_INSTANCE_ID" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the link was successfully shared. - **didSendMessage** (boolean) - Indicates if the link was sent as a message. - **didCopyLink** (boolean) - Indicates if the link was copied to the clipboard. ### Response Example ```json { "success": true, "didSendMessage": true, "didCopyLink": false } ``` ``` -------------------------------- ### Type Signature Comparison: V1 vs V2 Source: https://github.com/discord/embedded-app-sdk/blob/main/docs/activity-iframe-sdk-v2-migration.md Compares the v1 and v2 type signatures for the `getChannelPermissions` command. The v2 signature offers clearer type inference, directly indicating the return type without complex SDK-internal references. ```typescript - (property) getChannelPermissions: TPayloadCommand // v1 + (property) getChannelPermissions: (args: void) => Promise<{ permissions: string | bigint;}> // v2 ``` -------------------------------- ### Format SKU Prices with PriceUtils Source: https://context7.com/discord/embedded-app-sdk/llms.txt Formats a SKU price (in minor currency units) into a human-readable, locale-aware string using `Intl.NumberFormat`. Useful for displaying prices in a storefront. ```typescript import { PriceUtils } from '@discord/embedded-app-sdk'; // Format prices for display in a storefront const price1 = PriceUtils.formatPrice({ amount: 999, currency: 'USD' }, 'en-US'); console.log(price1); // "$9.99" const price2 = PriceUtils.formatPrice({ amount: 1099, currency: 'EUR' }, 'de-DE'); console.log(price2); // "10,99 €" const price3 = PriceUtils.formatPrice({ amount: 500, currency: 'JPY' }, 'ja-JP'); console.log(price3); // "¥500" // Use directly with a SKU from getSkus() async function renderStore(discordSdk: any) { const { skus } = await discordSdk.commands.getSkus(); const { locale } = await discordSdk.commands.userSettingsGetLocale(); skus.forEach((sku: any) => { console.log(`${sku.name}: ${PriceUtils.formatPrice(sku.price, locale)}`); }); } ```