### Example Guild Onboarding Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/guild.mdx An example JSON object representing guild onboarding configuration. ```APIDOC ## Example Guild Onboarding ### Description An example JSON object representing guild onboarding configuration. ### Request Body Example ```json { "guild_id": "960007075288915998", "prompts": [ { "id": "1067461047608422473", "title": "What do you want to do in this community?", "options": [ { "id": "1067461047608422476", "title": "Chat with Friends", "description": "", "emoji": { "id": "1070002302032826408", "name": "chat", "animated": false }, "role_ids": [], "channel_ids": [ "962007075288916001" ] }, { "id": "1070004843541954678", "title": "Get Gud", "description": "We have excellent teachers!", "emoji": { "id": null, "name": "😀", "animated": false }, "role_ids": [ "982014491980083211" ], "channel_ids": [] } ], "single_select": false, "required": false, "in_onboarding": true, "type": 0 } ], "default_channel_ids": [ "998678771706110023", "998678693058719784", "1070008122577518632", "998678764340912138", "998678704446263309", "998678683592171602", "998678699715067986" ], "enabled": true } ``` ``` -------------------------------- ### Joining a Lobby and Starting a Voice Call Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/development-guides/managing-voice-chat.mdx This example demonstrates how to join an existing lobby or create a new one, and then initiate a voice call within that lobby. The SDK handles the logic for whether to create/join or start/join automatically. ```cpp // First, create or join a lobby using a shared secret const std::string lobbySecret = "my-game-lobby-secret"; client->CreateOrJoinLobby(lobbySecret, [client](const discordpp::ClientResult& result, uint64_t lobbyId) { if (result.Successful()) { std::cout << "🎮 Successfully joined lobby!" << std::endl; // Now start or join the voice call in this lobby // StartCall returns a Call object but has no callback const auto call = client->StartCall(lobbyId); // StartCall returns null if user is already in this voice channel if (call) { std::cout << "🎤 Voice call operation initiated..." << std::endl; } else { std::cout << "â„šī¸ Already in this voice channel" << std::endl; } } else { std::cerr << "❌ Failed to join lobby: " << result.Error() << std::endl; } }); ``` -------------------------------- ### Complete Discord SDK C++ Example with Event Handling Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/getting-started/using-c++.mdx A full C++ application demonstrating Discord SDK initialization, event handling setup (logging and status callbacks), and a loop to keep the application running. Requires replacing `APPLICATION_ID` with your actual Discord Application ID. ```cpp #define DISCORDPP_IMPLEMENTATION #include "discordpp.h" #include #include #include #include #include #include // Replace with your Discord Application ID const uint64_t APPLICATION_ID = 123456789012345678; // Create a flag to stop the application std::atomic running = true; // Signal handler to stop the application void signalHandler(int signum) { running.store(false); } int main() { std::signal(SIGINT, signalHandler); std::cout << "🚀 Initializing Discord SDK...\n"; // Create Discord Client auto client = std::make_shared(); // Set up logging callback client->AddLogCallback([](auto message, auto severity) { std::cout << "[" << EnumToString(severity) << "] " << message << std::endl; }, discordpp::LoggingSeverity::Info); // Set up status callback to monitor client connection client->SetStatusChangedCallback([client](discordpp::Client::Status status, discordpp::Client::Error error, int32_t errorDetail) { std::cout << "🔄 Status changed: " << discordpp::Client::StatusToString(status) << std::endl; if (status == discordpp::Client::Status::Ready) { std::cout << "✅ Client is ready! You can now call SDK functions.\n"; } else if (error != discordpp::Client::Error::None) { std::cerr << "❌ Connection Error: " << discordpp::Client::ErrorToString(error) << " - Details: " << errorDetail << std::endl; } }); // Keep application running to allow SDK to receive events and callbacks while (running) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return 0; } ``` -------------------------------- ### Default Permissions Example Source: https://github.com/discord/discord-api-docs/blob/main/developers/interactions/application-commands.mdx Examples of setting default permissions for application commands. ```APIDOC ## Default Permissions ### Example 1: No default permissions (usable by anyone) ```json { "name": "permissions_test", "description": "A test of default permissions", "type": 1, "default_member_permissions": null } ``` ### Example 2: Usable only by admins ```json { "name": "permissions_test", "description": "A test of default permissions", "type": 1, "default_member_permissions": "0" } ``` ### Example 3: Usable only by users with `MANAGE_GUILD` permission ```python permissions = str(1 << 5) # MANAGE_GUILD permission value command = { "name": "permissions_test", "description": "A test of default permissions", "type": 1, "default_member_permissions": permissions } ``` ``` -------------------------------- ### Activity Object Example Source: https://github.com/discord/discord-api-docs/blob/main/developers/events/gateway-events.mdx A basic example of an activity object, including name, type, and URL. ```json { "details": "24H RL Stream for Charity", "state": "Rocket League", "name": "Twitch", "type": 1, "url": "https://www.twitch.tv/discord" } ``` -------------------------------- ### Example Welcome Screen Object Structure Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/guild.mdx Provides an example of a welcome screen object, showcasing the server description and an array of welcome channels with their respective details. ```json { "description": "Discord Developers is a place to learn about Discord's API, bots, and SDKs and integrations. This is NOT a general Discord support server.", "welcome_channels": [ { "channel_id": "697138785317814292", "description": "Follow for official Discord API updates", "emoji_id": null, "emoji_name": "📡" }, { "channel_id": "697236247739105340", "description": "Get help with Bot Verifications", "emoji_id": null, "emoji_name": "📸" }, { "channel_id": "697489244649816084", "description": "Create amazing things with Discord's API", "emoji_id": null, "emoji_name": "đŸ”Ŧ" }, { "channel_id": "613425918748131338", "description": "Integrate Discord into your game", "emoji_id": null, "emoji_name": "🎮" }, { "channel_id": "646517734150242346", "description": "Find more places to help you on your quest", "emoji_id": null, "emoji_name": "đŸ”Ļ" } ] } ``` -------------------------------- ### Voice Connection - Ready Payload Example Source: https://github.com/discord/discord-api-docs/blob/main/developers/topics/voice-connections.mdx An example of the 'Ready' payload received when establishing a voice connection, which contains information for UDP connection setup. ```APIDOC ## Voice Connection - Ready Payload Example ### Description This is an example of the 'Ready' payload received from the voice gateway. It contains essential information, such as the IP address and port, required to establish a UDP connection for voice transmission. ### Method N/A (Received from Server) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "op": 2, "d": { "...": "...", "modes": ["aead_aes256_gcm_rtpsize", "aead_xchacha20_poly1305_rtpsize", "xsalsa20_poly1305_lite_rtpsize"] } } ``` ### Response #### Success Response (200) N/A (This is a payload received from the server) #### Response Example ```json { "op": 2, "d": { "...": "...", "modes": ["aead_aes256_gcm_rtpsize", "aead_xchacha20_poly1305_rtpsize", "xsalsa20_poly1305_lite_rtpsize"] } } ``` ``` -------------------------------- ### Voice Gateway Connection Payloads Source: https://github.com/discord/discord-api-docs/blob/main/developers/topics/voice-connections.mdx Examples of the Ready payload used for initial connection setup and the Select Protocol payload used to define the UDP connection parameters after IP discovery. ```json { "op": 2, "d": { "modes": ["aead_aes256_gcm_rtpsize", "aead_xchacha20_poly1305_rtpsize", "xsalsa20_poly1305_lite_rtpsize"] } } ``` ```json { "op": 1, "d": { "protocol": "udp", "data": { "address": "127.0.0.1", "port": 1337, "mode": "aead_aes256_gcm_rtpsize" } } } ``` -------------------------------- ### Local Development Setup Source: https://github.com/discord/discord-api-docs/blob/main/developers/tutorials/hosting-on-cloudflare-workers.mdx Instructions for setting up a local development environment, including running the server and using ngrok for interaction tunneling. ```APIDOC ## Local Development Setup ### Running the Application Server To start the local development server, run the following command: ```bash $ npm run dev ``` ### Setting up ngrok for Local Testing `ngrok` is used to create a public HTTPS endpoint that forwards requests to your local machine. This is essential for Discord to send interaction requests to your development server. 1. **Start ngrok:** ```bash $ npm run ngrok ``` This will provide you with an HTTPS forwarding address (e.g., `https://.ngrok.io`). 2. **Update Interactions Endpoint URL:** - Go to the Discord Developer Dashboard for your application. - Navigate to the 'Bot' or 'General Information' section. - Update the 'Interactions Endpoint URL' field with the HTTPS link provided by ngrok. **Note:** Remember to update this URL to your Cloudflare Worker URL when deploying your application. ``` -------------------------------- ### Example Partial Guild Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/user.mdx An example of the partial guild object returned by the Get Current User Guilds endpoint. ```json { "id": "80351110224678912", "name": "1337 Krew", "icon": "8342729096ea3675442027381ff50dfe", "banner": "bb42bdc37653b7cf58c4c8cc622e76cb", "owner": true, "permissions": "36953089", "features": ["COMMUNITY", "NEWS", "ANIMATED_ICON", "INVITE_SPLASH", "BANNER", "ROLE_ICONS"], "approximate_member_count": 3268, "approximate_presence_count": 784 } ``` -------------------------------- ### Full Discord SDK C++ Example Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/getting-started/using-c++.mdx This comprehensive example demonstrates the complete initialization and authentication flow for the Discord SDK in C++. It includes setting up callbacks for logging and status changes, handling OAuth2 authentication, and establishing a connection to Discord. ```cpp #define DISCORDPP_IMPLEMENTATION #include "discordpp.h" #include #include #include #include #include #include // Replace with your Discord Application ID const uint64_t APPLICATION_ID = 1349146942634065960; // Create a flag to stop the application std::atomic running = true; // Signal handler to stop the application void signalHandler(int signum) { running.store(false); } int main() { std::signal(SIGINT, signalHandler); std::cout << "🚀 Initializing Discord SDK...\n"; // Create our Discord Client auto client = std::make_shared(); // Set up logging callback client->AddLogCallback([](auto message, auto severity) { std::cout << "[" << EnumToString(severity) << "] " << message << std::endl; }, discordpp::LoggingSeverity::Info); // Set up status callback to monitor client connection client->SetStatusChangedCallback([client](discordpp::Client::Status status, discordpp::Client::Error error, int32_t errorDetail) { std::cout << "🔄 Status changed: " << discordpp::Client::StatusToString(status) << std::endl; if (status == discordpp::Client::Status::Ready) { std::cout << "✅ Client is ready! You can now call SDK functions.\n"; // Access initial relationships data std::cout << "đŸ‘Ĩ Friends Count: " << client->GetRelationships().size() << std::endl; } else if (error != discordpp::Client::Error::None) { std::cerr << "❌ Connection Error: " << discordpp::Client::ErrorToString(error) << " - Details: " << errorDetail << std::endl; } }); // Generate OAuth2 code verifier for authentication auto codeVerifier = client->CreateAuthorizationCodeVerifier(); // Set up authentication arguments discordpp::AuthorizationArgs args{}; args.SetClientId(APPLICATION_ID); args.SetScopes(discordpp::Client::GetDefaultPresenceScopes()); args.SetCodeChallenge(codeVerifier.Challenge()); // Begin authentication process client->Authorize(args, [client, codeVerifier](auto result, auto code, auto redirectUri) { if (!result.Successful()) { std::cerr << "❌ Authentication Error: " << result.Error() << std::endl; return; } else { std::cout << "✅ Authorization successful! Getting access token...\n"; // Exchange auth code for access token client->GetToken(APPLICATION_ID, code, codeVerifier.Verifier(), redirectUri, [client](discordpp::ClientResult result, std::string accessToken, std::string refreshToken, discordpp::AuthorizationTokenType tokenType, int32_t expiresIn, std::string scope) { std::cout << "🔓 Access token received! Establishing connection...\n"; // Next Step: Update the token and connect client->UpdateToken(discordpp::AuthorizationTokenType::Bearer, accessToken, [client](discordpp::ClientResult result) { if(result.Successful()) { std::cout << "🔑 Token updated, connecting to Discord...\n"; client->Connect(); } }); }); } }); // Keep application running to allow SDK to receive events and callbacks while (running) { discordpp::RunCallbacks(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return 0; } ``` -------------------------------- ### Example Response for Get Target Users Job Status Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/invite.mdx An example response when checking the job status for processing target users, showing the current status, counts, and timestamps. ```json { "status": 3, "total_users": 100, "processed_users": 41, "created_at": "2025-01-08T12:00:00.000000+00:00", "completed_at": null, "error_message": "Failed to parse CSV file" } ``` -------------------------------- ### Example cloudflared tunnel output Source: https://github.com/discord/discord-api-docs/blob/main/developers/activities/development-guides/local-development.mdx An example of the output provided by the cloudflared tool after successfully creating a tunnel, which includes the public URL to be used in the Discord Developer Portal. ```text Your quick Tunnel has been created! Visit it at (it may take some time to be reachable): https://funky-jogging-bunny.trycloudflare.com ``` -------------------------------- ### Initialize Environment Configuration Source: https://github.com/discord/discord-api-docs/blob/main/developers/activities/building-an-activity.mdx Copies the example environment file to a local .env file to store sensitive application credentials. ```bash cp example.env .env ``` -------------------------------- ### Initialize Discord Core in C Source: https://github.com/discord/discord-api-docs/blob/main/developers/developer-tools/game-sdk.mdx Set up the application structure and create the Discord core instance using the provided parameters. ```c struct Application { struct IDiscordCore* core; struct IDiscordUsers* users; }; struct Application app; // Don't forget to memset or otherwise initialize your classes! memset(&app, 0, sizeof(app)); struct IDiscordCoreEvents events; memset(&events, 0, sizeof(events)); struct DiscordCreateParams params; params.client_id = CLIENT_ID; params.flags = DiscordCreateFlags_Default; params.events = &events; params.event_data = &app; DiscordCreate(DISCORD_VERSION, ¶ms, &app.core); ``` -------------------------------- ### Voice Connection - Select Protocol Payload Example Source: https://github.com/discord/discord-api-docs/blob/main/developers/topics/voice-connections.mdx An example of the 'Select Protocol' payload (Opcode 1) used to inform the voice WebSocket of the discovered IP address, port, and encryption mode. ```APIDOC ## Voice Connection - Select Protocol Payload Example ### Description This is an example of the 'Select Protocol' payload (Opcode 1). After establishing a UDP connection and potentially performing IP discovery, this payload is sent to the voice WebSocket to communicate the client's discovered IP address, UDP port, and chosen encryption mode. ### Method N/A (Sent to Server) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ```json { "op": 1, "d": { "protocol": "udp", "data": { "address": "string", "port": "integer", "mode": "string" } } } ``` ### Request Example ```json { "op": 1, "d": { "protocol": "udp", "data": { "address": "127.0.0.1", "port": 1337, "mode": "aead_aes256_gcm_rtpsize" } } } ``` ### Response #### Success Response (200) N/A (This is a payload sent to the server) #### Response Example N/A ``` -------------------------------- ### Get Guild Command Payload Source: https://github.com/discord/discord-api-docs/blob/main/developers/topics/rpc.mdx Example JSON payload for requesting details of a specific guild. Requires the guild_id argument. ```json { "nonce": "9524922c-3d32-413a-bdaa-0804f4332588", "args": { "guild_id": "199737254929760256" }, "cmd": "GET_GUILD" } ``` -------------------------------- ### Example Guild Onboarding Object Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/guild.mdx This JSON object demonstrates the structure of the Guild Onboarding configuration, including prompts, options, and default channels. It shows how to define user-facing prompts and their associated actions like assigning roles or adding to channels. ```json { "guild_id": "960007075288915998", "prompts": [ { "id": "1067461047608422473", "title": "What do you want to do in this community?", "options": [ { "id": "1067461047608422476", "title": "Chat with Friends", "description": "", "emoji": { "id": "1070002302032826408", "name": "chat", "animated": false }, "role_ids": [], "channel_ids": [ "962007075288916001" ] }, { "id": "1070004843541954678", "title": "Get Gud", "description": "We have excellent teachers!", "emoji": { "id": null, "name": "😀", "animated": false }, "role_ids": [ "982014491980083211" ], "channel_ids": [] } ], "single_select": false, "required": false, "in_onboarding": true, "type": 0 } ], "default_channel_ids": [ "998678771706110023", "998678693058719784", "1070008122577518632", "998678764340912138", "998678704446263309", "998678683592171602", "998678699715067986" ], "enabled": true } ``` -------------------------------- ### Get Guilds Command Payload Source: https://github.com/discord/discord-api-docs/blob/main/developers/topics/rpc.mdx Example JSON payload for requesting a list of guilds the client is connected to. This command takes no arguments. ```json { "nonce": "e16fcbed-8bfa-4fd4-ba09-73b72e809833", "args": {}, "cmd": "GET_GUILDS" } ``` -------------------------------- ### Example Entry Point Command Structure Source: https://github.com/discord/discord-api-docs/blob/main/developers/interactions/application-commands.mdx Defines the structure of an Entry Point command, including its name, description, type, and handler. ```json { "name": "launch", "description": "Launch Racing with Friends", "type": 4, "handler": 2 } ``` -------------------------------- ### Example Guild Response Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/guild.mdx This JSON object is an example response for the Get Guild endpoint. It includes detailed information about the guild, such as its ID, name, features, emojis, and various configuration settings. This response is returned when requesting guild details with optional counts. ```json { "id": "2909267986263572999", "name": "Mason's Test Server", "icon": "389030ec9db118cb5b85a732333b7c98", "description": null, "splash": "75610b05a0dd09ec2c3c7df9f6975ea0", "discovery_splash": null, "approximate_member_count": 2, "approximate_presence_count": 2, "features": [ "INVITE_SPLASH", "VANITY_URL", "COMMERCE", "BANNER", "NEWS", "VERIFIED", "VIP_REGIONS" ], "emojis": [ { "name": "ultrafastparrot", "roles": [], "id": "393564762228785161", "require_colons": true, "managed": false, "animated": true, "available": true } ], "banner": "5c3cb8d1bc159937fffe7e641ec96ca7", "owner_id": "53908232506183680", "application_id": null, "region": null, "afk_channel_id": null, "afk_timeout": 300, "system_channel_id": null, "widget_enabled": true, "widget_channel_id": "639513352485470208", "verification_level": 0, "roles": [ { "id": "2909267986263572999", "name": "@everyone", "permissions": "49794752", "position": 0, "color": 0, "colors": { "primary_color": 0, "secondary_color": null, "tertiary_color": null }, "hoist": false, "managed": false, "mentionable": false } ], "default_message_notifications": 1, "mfa_level": 0, "explicit_content_filter": 0, "max_presences": null, "max_members": 250000, "max_video_channel_users": 25, "vanity_url_code": "no", "premium_tier": 0, "premium_subscription_count": 0, "system_channel_flags": 0, "preferred_locale": "en-US", "rules_channel_id": null, "public_updates_channel_id": null, "safety_alerts_channel_id": null } ``` -------------------------------- ### Example Environment Configuration Source: https://github.com/discord/discord-api-docs/blob/main/developers/tutorials/configuring-app-metadata-for-linked-roles.mdx A template for the .env file containing the necessary credentials and configuration URLs for the Discord application. ```text DISCORD_CLIENT_ID: DISCORD_CLIENT_SECRET: DISCORD_TOKEN: DISCORD_REDIRECT_URI: https://.glitch.me/discord-oauth-callback COOKIE_SECRET: ``` -------------------------------- ### Start Backend Server (npm) Source: https://github.com/discord/discord-api-docs/blob/main/developers/activities/building-an-activity.mdx Starts the backend development server using npm. This command is typically used to run the Node.js application that handles server-side logic, such as API requests. ```bash npm run dev ``` -------------------------------- ### Get Guilds Response Payload Source: https://github.com/discord/discord-api-docs/blob/main/developers/topics/rpc.mdx Example JSON payload for the Discord client's response to a GET_GUILDS command. Includes an array of partial guild objects. ```json { "cmd": "GET_GUILDS", "data": { "guilds": [ { "id": "199737254929760256", "name": "test" } ] }, "nonce": "e16fcbed-8bfa-4fd4-ba09-73b72e809833" } ``` -------------------------------- ### Get Guild Response Payload Source: https://github.com/discord/discord-api-docs/blob/main/developers/topics/rpc.mdx Example JSON payload for the Discord client's response to a GET_GUILD command. Includes guild details such as ID, name, and icon URL. ```json { "cmd": "GET_GUILD", "data": { "id": "199737254929760256", "name": "test", "icon_url": null, "members": [] }, "nonce": "9524922c-3d32-413a-bdaa-0804f4332588" } ``` -------------------------------- ### Example Incoming Webhook Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/webhook.mdx This is an example of an incoming webhook object. It contains details about the webhook's configuration and associated user. ```json { "name": "test webhook", "type": 1, "channel_id": "199737254929760256", "token": "3d89bb7572e0fb30d8128367b3b1b44fecd1726de135cbe28a41f8b2f777c372ba2939e72279b94526ff5d1bd4358d65cf11", "avatar": null, "guild_id": "199737254929760256", "id": "223704706495545344", "application_id": null, "user": { "username": "test", "discriminator": "7479", "id": "190320984123768832", "avatar": "b004ec1740a63ca06ae2e14c5cee11f3", "public_flags": 131328 } } ``` -------------------------------- ### Get Guild Vanity URL Example Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/guild.mdx Returns a partial invite object for guilds with the vanity URL feature enabled. The `code` field will be null if no vanity URL is set. ```json { "code": "abc", "uses": 12 } ``` -------------------------------- ### Clone Discord Activity Starter Project Source: https://github.com/discord/discord-api-docs/blob/main/developers/activities/building-an-activity.mdx Clones the 'getting-started-activity' repository from GitHub to set up the initial project structure for a Discord Activity. This project includes separate directories for the client-side frontend and the server-side backend. ```bash git clone git@github.com:discord/getting-started-activity.git ``` -------------------------------- ### Get Guild Role Member Counts Example Response Source: https://github.com/discord/discord-api-docs/blob/main/developers/resources/guild.mdx This JSON response shows a mapping of role IDs to the number of members holding that role. It does not include the @everyone role. ```json { "613425648685547541": 1337, "1409696176629878905": 2, "697138785317814292": 67 } ``` -------------------------------- ### Game Invite and Lobby Integration Example Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/development-guides/managing-game-invites.mdx This example demonstrates a full flow for using game invites with lobbies. It covers creating a lobby, updating Rich Presence with invite secrets, sending invites, and accepting them to join a lobby. ```cpp // User A // 1. Create a lobby with secret std::string lobbySecret = "foo" uint64_t USER_B_ID = 01234567890; client->CreateOrJoinLobby(lobbySecret, [&client](discordpp::ClientResult result, uint64_t lobbyId) { // 2. Update Rich Presence with a party and join secret to enable invites discordpp::Activity activity{}; activity.SetType(discordpp::ActivityTypes::Playing); activity.SetState("In Lobby"); // Rich Presence party configuration for how many players can join discordpp::ActivityParty party{}; party.SetId("party1234"); party.SetCurrentSize(1); party.SetMaxSize(4); activity.SetParty(party); // Rich Presence secret is what is shared via invites discordpp::ActivitySecrets secrets{}; secrets.SetJoin(lobbySecret); // This connects Rich Presence to your lobby activity.SetSecrets(secrets); // Don't forget to set this Rich Presence update, otherwise SendActivityInvite won't work! client->UpdateRichPresence(std::move(activity), [&client](discordpp::ClientResult result) { // 3. NOW we can send invites because Rich Presence is configured client->SendActivityInvite(USER_B_ID, "come play with me", [](discordpp::ClientResult result) { if(result.Successful()) { std::cout << "💌 Invite sent successfully!\n"; } else { std::cerr << "❌ Invite failed - check Rich Presence configuration\n"; } }); }); }); // User B // 4. Monitor for new invites client->SetActivityInviteCreatedCallback([&client](discordpp::ActivityInvite invite) { std::cout << "💌 New invite received: " << invite.SenderId() << "\n"; // 5. When an invite is received, ask the user if they want to accept it. // If they choose to do so then go ahead and invoke AcceptActivityInvite client->AcceptActivityInvite(invite, [&client](discordpp::ClientResult result, std::string joinSecret) { if (result.Successful()) { std::cout << "🎮 Invite accepted! Joining lobby...\n"; // joinSecret came from User A's Rich Presence configuration // 6. Join the lobby using the joinSecret client->CreateOrJoinLobby(joinSecret, [=](discordpp::ClientResult result, uint64_t lobbyId) { // Successfully joined lobby! if (result.Successful()) { std::cout << "🎮 Lobby joined successfully! " << lobbyId << std::endl; } else { std::cerr << "❌ Lobby join failed\n"; } }); } }); }); ``` -------------------------------- ### Add Subcommands within Subcommand Groups Source: https://github.com/discord/discord-api-docs/blob/main/developers/interactions/application-commands.mdx This example shows how to define subcommands like 'get' and 'edit' within the previously created subcommand groups ('user' and 'role'). This allows for specific actions to be performed on the grouped resources. ```json { "name": "permissions", "description": "Get or edit permissions for a user or a role", "options": [ { "name": "user", "description": "Get or edit permissions for a user", "type": 2, // 2 is type SUB_COMMAND_GROUP "options": [ { "name": "get", "description": "Get permissions for a user", "type": 1 // 1 is type SUB_COMMAND }, { "name": "edit", "description": "Edit permissions for a user", "type": 1 } ] }, { "name": "role", "description": "Get or edit permissions for a role", "type": 2, "options": [ { "name": "get", "description": "Get permissions for a role", "type": 1 }, { "name": "edit", "description": "Edit permissions for a role", "type": 1 } ] } ] } ``` -------------------------------- ### Initialize and Connect Discord SDK in C++ Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/getting-started/using-c++.mdx This C++ snippet demonstrates how to initialize the Discord SDK, set up logging and status callbacks, handle authentication, and establish a connection. Ensure your Discord Application ID is correctly set. ```cpp #define DISCORDPP_IMPLEMENTATION #include "discordpp.h" #include #include #include #include #include #include // Replace with your Discord Application ID const uint64_t APPLICATION_ID = 1349146942634065960; // Create a flag to stop the application std::atomic running = true; // Signal handler to stop the application void signalHandler(int signum) { running.store(false); } int main() { std::signal(SIGINT, signalHandler); std::cout << "🚀 Initializing Discord SDK...\n"; // Create our Discord Client auto client = std::make_shared(); // Set up logging callback client->AddLogCallback([](auto message, auto severity) { std::cout << "[" << EnumToString(severity) << "] " << message << std::endl; }, discordpp::LoggingSeverity::Info); // Set up status callback to monitor client connection client->SetStatusChangedCallback([client](discordpp::Client::Status status, discordpp::Client::Error error, int32_t errorDetail) { std::cout << "🔄 Status changed: " << discordpp::Client::StatusToString(status) << std::endl; if (status == discordpp::Client::Status::Ready) { std::cout << "✅ Client is ready! You can now call SDK functions.\n"; } else if (error != discordpp::Client::Error::None) { std::cerr << "❌ Connection Error: " << discordpp::Client::ErrorToString(error) << " - Details: " << errorDetail << std::endl; } }); // Generate OAuth2 code verifier for authentication auto codeVerifier = client->CreateAuthorizationCodeVerifier(); // Set up authentication arguments discordpp::AuthorizationArgs args{}; args.SetClientId(APPLICATION_ID); args.SetScopes(discordpp::Client::GetDefaultPresenceScopes()); args.SetCodeChallenge(codeVerifier.Challenge()); // Begin authentication process client->Authorize(args, [client, codeVerifier](auto result, auto code, auto redirectUri) { if (!result.Successful()) { std::cerr << "❌ Authentication Error: " << result.Error() << std::endl; return; } else { std::cout << "✅ Authorization successful! Getting access token...\n"; // Exchange auth code for access token client->GetToken(APPLICATION_ID, code, codeVerifier.Verifier(), redirectUri, [client](discordpp::ClientResult result, std::string accessToken, std::string refreshToken, discordpp::AuthorizationTokenType tokenType, int32_t expiresIn, std::string scope) { std::cout << "🔓 Access token received! Establishing connection...\n"; // Next Step: Update the token and connect client->UpdateToken(discordpp::AuthorizationTokenType::Bearer, accessToken, [client](discordpp::ClientResult result) { if(result.Successful()) { std::cout << "🔑 Token updated, connecting to Discord...\n"; client->Connect(); } }); }); } }); // Keep application running to allow SDK to receive events and callbacks while (running) { discordpp::RunCallbacks(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return 0; } ``` -------------------------------- ### Get Gateway Bot Source: https://github.com/discord/discord-api-docs/blob/main/developers/events/gateway.mdx Retrieves Gateway information including a WSS URL, recommended shard count, and session start limit details. This endpoint requires authentication with a bot token and should not be cached extensively as its values can change. ```APIDOC ## Get Gateway Bot /gateway/bot This endpoint requires authentication using a valid bot token. Returns an object based on the information in Get Gateway, plus additional metadata that can help during the operation of large or sharded bots. Unlike the Get Gateway, this route should not be cached for extended periods of time as the value is not guaranteed to be the same per-call, and changes as the bot joins/leaves guilds. ### JSON Response | Field | Type | Description | |---------------------|-------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------| | url | string | WSS URL that can be used for connecting to the Gateway | | shards | integer | Recommended number of shards to use when connecting | | session_start_limit | [session_start_limit](/developers/events/gateway#session-start-limit-object) object | Information on the current session start limit | ### Example Response ```json { "url": "wss://gateway.discord.gg/", "shards": 9, "session_start_limit": { "total": 1000, "remaining": 999, "reset_after": 14400000, "max_concurrency": 1 } } ``` ``` -------------------------------- ### Install Frontend Dependencies for Discord Activity Source: https://github.com/discord/discord-api-docs/blob/main/developers/activities/building-an-activity.mdx Navigates to the 'client' directory of the cloned Discord Activity project and installs all necessary frontend dependencies using npm. This command prepares the frontend environment for local development. ```bash cd getting-started-activity/client npm install ``` -------------------------------- ### Get Gateway Bot Information Source: https://github.com/discord/discord-api-docs/blob/main/developers/events/gateway.mdx Retrieve gateway information including a WSS URL, recommended shard count, and session start limits. This endpoint requires authentication with a bot token and should not be cached extensively as values can change. ```json { "url": "wss://gateway.discord.gg/", "shards": 9, "session_start_limit": { "total": 1000, "remaining": 999, "reset_after": 14400000, "max_concurrency": 1 } } ``` -------------------------------- ### Discord Voice Resumed Payload Example Source: https://github.com/discord/discord-api-docs/blob/main/developers/topics/voice-connections.mdx This JSON payload is the response from the Voice server indicating a successful resumption of a voice connection. The 'd' field is null upon successful resumption. ```json { "op": 9, "d": null } ``` -------------------------------- ### Initialize DiscordManager Script in Unity Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/getting-started/using-unity.mdx Defines the base DiscordManager class for handling SDK client references, UI components, and client ID configuration within the Unity Inspector. ```csharp using UnityEngine; using UnityEngine.UI; using Discord.Sdk; using System.Linq; public class DiscordManager : MonoBehaviour { [SerializeField] private ulong clientId; // Set this in the Unity Inspector from the dev portal [SerializeField] private Button loginButton; [SerializeField] private Text statusText; private Client client; private string codeVerifier; } ``` -------------------------------- ### Register Launch Command for Game Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/development-guides/managing-game-invites.mdx Register a command that Discord will run to launch your game. Run this when the SDK starts up. ```cpp client->RegisterLaunchCommand(YOUR_APP_ID, "yourgame://"); ``` -------------------------------- ### Create Project Directory Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/getting-started/using-c++.mdx Sets up the basic directory structure for a C++ project intended to use the Discord Social SDK. ```bash mkdir MyGame cd MyGame mkdir lib ``` -------------------------------- ### Connect SDK via Access Token Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/getting-started/using-unity.mdx Handles the reception of an access token and triggers the SDK connection process. It updates the existing GetTokenFromCode method to include success and failure callbacks. ```C# private void OnReceivedToken(string token) { Debug.Log("Token received: " + token); client.UpdateToken(AuthorizationTokenType.Bearer, token, (ClientResult result) => { client.Connect(); }); } private void OnRetrieveTokenFailed() { statusText.text = "Failed to retrieve token"; } private void GetTokenFromCode(string code, string redirectUri) { client.GetToken(clientId, code, codeVerifier, redirectUri, (result, token, refreshToken, tokenType, expiresIn, scope) => { if (token != "") { OnReceivedToken(token); } else { OnRetrieveTokenFailed(); } }); } ``` -------------------------------- ### Install Server Dependencies (npm) Source: https://github.com/discord/discord-api-docs/blob/main/developers/activities/building-an-activity.mdx Installs the necessary dependencies for the server-side application using npm. This is a prerequisite for running the backend. ```bash # move into our server directory cd server # install dependencies npm install ``` -------------------------------- ### Initialize Discord Manager and OAuth Flow Source: https://github.com/discord/discord-api-docs/blob/main/developers/discord-social-sdk/getting-started/using-unity.mdx Sets up the Discord client, configures log callbacks, and initiates the OAuth2 authorization process. It includes methods to generate a code verifier and handle the authorization result. ```C# using UnityEngine; using UnityEngine.UI; using Discord.Sdk; using System.Linq; public class DiscordManager : MonoBehaviour { [SerializeField] private ulong clientId; [SerializeField] private Button loginButton; [SerializeField] private Text statusText; private Client client; private string codeVerifier; void Start() { client = new Client(); client.AddLogCallback(OnLog, LoggingSeverity.Error); client.SetStatusChangedCallback(OnStatusChanged); if (loginButton != null) loginButton.onClick.AddListener(StartOAuthFlow); } private void StartOAuthFlow() { var authorizationVerifier = client.CreateAuthorizationCodeVerifier(); codeVerifier = authorizationVerifier.Verifier(); var args = new AuthorizationArgs(); args.SetClientId(clientId); args.SetScopes(Client.GetDefaultPresenceScopes()); args.SetCodeChallenge(authorizationVerifier.Challenge()); client.Authorize(args, OnAuthorizeResult); } } ``` -------------------------------- ### Basic Rich Presence Setup in Unity (C#) Source: https://github.com/discord/discord-api-docs/blob/main/developers/game-development/how-to-get-your-game-seen.mdx Implement basic Rich Presence in Unity using C#. Set activity type, details, and state. Requires the Social SDK. ```csharp // An Activity is anything a player is doing in Discord Activity activity = new Activity(); activity.SetType(ActivityTypes.Playing); activity.SetDetails("Daily Run"); activity.SetState("Floor 8 - Score: 48,340"); client.UpdateRichPresence(activity, (ClientResult result) => { if (result.Successful()) { Debug.Log("Rich Presence updated!"); } else { Debug.LogError("Failed to update Rich Presence"); } }); ```