### Install Frontend Dependencies and Start Development Server Source: https://docs.discord.com/developers/activities/building-an-activity Install the necessary project dependencies for the frontend and start the development server using npm. ```bash # install project dependencies npm install # start frontend npm run dev ``` -------------------------------- ### Server Output Example Source: https://docs.discord.com/developers/activities/building-an-activity This is an example of the expected output when the backend server starts successfully. ```bash > server@1.0.0 dev > node server.js Server listening at http://localhost:3001 ``` -------------------------------- ### Example Welcome Screen Object Structure Source: https://docs.discord.com/developers/resources/guild Provides an example of a Discord guild's welcome screen configuration. This includes a server description and a list of up to five channels with their own descriptions and optional emojis, used to guide new members. ```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": "🔦" } ] } ``` -------------------------------- ### Clone Discord Example App Repository Source: https://docs.discord.com/developers/quick-start/getting-started Clone the sample application repository to your local machine to begin development. Ensure you have Git installed. ```bash git clone https://github.com/discord/discord-example-app.git ``` -------------------------------- ### Navigate and Install Dependencies Source: https://docs.discord.com/developers/quick-start/getting-started Navigate into the cloned project directory and install the necessary Node.js dependencies using npm. This prepares your project for development. ```bash # navigate to directory cd discord-example-app # install dependencies npm install ``` -------------------------------- ### Start Backend Server Source: https://docs.discord.com/developers/activities/building-an-activity Run the backend server using npm. This command starts the Node.js application. ```bash npm run dev ``` -------------------------------- ### Complete Rich Presence Setup for Game Invites Source: https://docs.discord.com/developers/discord-social-sdk/development-guides/managing-game-invites A comprehensive example combining Rich Presence, party information, join secrets, and supported platforms to fully enable game invites. ```cpp // Create discordpp::Activity - This Rich Presence Activity is your invite configuration discordpp::Activity activity; activity.SetType(discordpp::ActivityTypes::Playing); // Set the game state and details activity.SetState("In Competitive Match"); activity.SetDetails("Valhalla"); // Set the party information discordpp::ActivityParty party; party.SetId("party1234"); party.SetCurrentSize(1); // current party size party.SetMaxSize(5); // max party size // Set the party information in the Activity, to inform the invite about the party size and how many players can join activity.SetParty(party); // Create ActivitySecrets discordpp::ActivitySecrets secrets; secrets.SetJoin("joinsecret1234"); // Rich Presence secret will be in the invite payload activity.SetSecrets(secrets); // Set supported platforms that can join the game // See discordpp::ActivityGamePlatforms for available platforms activity.SetSupportedPlatforms(discordpp::ActivityGamePlatforms::Desktop); // Update Rich Presence presence client.UpdateRichPresence(activity, [](discordpp::ClientResult result) { if(result.Successful()) { std::cout << "🎮 Rich Presence updated successfully!\n"; // ✅ Rich Presence updated = Game invites now available! } else { std::cerr << "❌ Rich Presence update failed"; // ❌ No Rich Presence = No invites possible } }); ``` -------------------------------- ### Example .env File Configuration Source: https://docs.discord.com/developers/tutorials/configuring-app-metadata-for-linked-roles This is an example of how your .env file should be configured with your Discord application credentials and secrets. ```env DISCORD_CLIENT_ID: DISCORD_CLIENT_SECRET: DISCORD_TOKEN: DISCORD_REDIRECT_URI: https://.glitch.me/discord-oauth-callback COOKIE_SECRET: ``` -------------------------------- ### Install Dependencies Source: https://docs.discord.com/developers/activities/building-an-activity Install the necessary Node.js dependencies for your project. ```bash npm install ``` -------------------------------- ### Clone the Sample Project Source: https://docs.discord.com/developers/activities/building-an-activity Clone the 'getting-started-activity' repository to your local development environment. ```bash git clone git@github.com:discord/getting-started-activity.git ``` -------------------------------- ### Rich Presence Guide Card Source: https://docs.discord.com/developers/guides/platform An example of using the ImageCard component to link to the Rich Presence best practices guide. This card includes a title and a short summary of the guide's content. ```html Best practices for using Rich Presence to create engaging game integrations on Discord. ``` -------------------------------- ### Example Guild Response Source: https://docs.discord.com/developers/resources/guild Provides an example response for the Get Guild API endpoint, including guild details, features, emojis, and role information. ```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 } ``` -------------------------------- ### Create Project Directory Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c%2B%2B Sets up a new project directory and a subdirectory for the SDK. ```bash mkdir MyGame cd MyGame mkdir lib ``` -------------------------------- ### Account Linking Guide Card Source: https://docs.discord.com/developers/guides/platform An example of using the ImageCard component to link to the Account Linking guide. This card provides a title and a brief description of the linked content. ```html An introduction to account linking and its benefits for your game or app. ``` -------------------------------- ### Get Gateway Endpoint Response Source: https://docs.discord.com/developers/events/gateway Example response from the Get Gateway endpoint, providing the WSS URL for connecting to the Gateway. Cache this URL and only re-fetch if connection fails. ```json { "url": "wss://gateway.discord.gg/" } ``` -------------------------------- ### Get Guild Role Member Counts Example Response Source: https://docs.discord.com/developers/resources/guild Example response showing a map of role IDs to the number of members with that role. Does not include the @everyone role. ```json { "613425648685547541": 1337, "1409696176629878905": 2, "697138785317814292": 67 } ``` -------------------------------- ### Cloning the Sample App Repository Source: https://docs.discord.com/developers/tutorials/developing-a-user-installable-app Command-line instruction to download the project code from the GitHub repository. This is the first step in setting up the development environment. ```bash git clone https://github.com/discord/user-install-example.git ``` -------------------------------- ### Navigate to Server Directory Source: https://docs.discord.com/developers/activities/building-an-activity This command moves you into the server directory to begin backend setup. ```shell # move into our server directory cd server ``` -------------------------------- ### Example Response for Get Target Users Job Status Source: https://docs.discord.com/developers/resources/invite This JSON snippet illustrates a successful response from the 'Get Target Users Job Status' endpoint, detailing the job's progress and any potential errors. ```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" } ``` -------------------------------- ### Get Guild Widget Image Example (Shield Style) Source: https://docs.discord.com/developers/resources/guild Fetches a PNG image widget for a guild. This example shows the 'shield' style, displaying the Discord icon and guild members online count. No permissions are required. ```url https://discord.com/api/guilds/81384788765712384/widget.png?style=shield ``` -------------------------------- ### Initialize Discord SDK and Handle Connection in Unreal Engine Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-unreal-engine Set up the Discord SDK by getting the subsystem and registering callbacks for log messages and status changes. This is typically done in the BeginPlay function of your character class. ```cpp // Copyright Epic Games, Inc. All Rights Reserved. #include "DiscordSocialUnrealCharacter.h" #include "Engine/LocalPlayer.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/SpringArmComponent.h" #include "GameFramework/Controller.h" #include "EnhancedInputComponent.h" #include "EnhancedInputSubsystems.h" #include "InputActionValue.h" DEFINE_LOG_CATEGORY(LogTemplateCharacter); #define APPLICATION_ID 1111111111111111111 void ADiscordSocialUnrealCharacter::BeginPlay() { auto PlayerController = Cast(GetController()); auto LocalPlayer = PlayerController->GetLocalPlayer(); Discord = ULocalPlayer::GetSubsystem(LocalPlayer); auto LogCallback = FDiscordClientLogCallback::CreateUObject(this, &ADiscordSocialUnrealCharacter::OnLogMessage); FScriptDelegate StatusChanged; StatusChanged.BindUFunction(this, "OnStatusChanged"); Discord->Client->AddLogCallback(LogCallback, EDiscordLoggingSeverity::Info); Discord->OnStatusChanged.Add(StatusChanged); } void ADiscordSocialUnrealCharacter::DiscordConnect() { CodeVerifier = Discord->Client->CreateAuthorizationCodeVerifier(); auto AuthArgs = NewObject(); AuthArgs->Init(); AuthArgs->SetClientId(APPLICATION_ID); AuthArgs->SetScopes(UDiscordClient::GetDefaultPresenceScopes()); AuthArgs->SetCodeChallenge(CodeVerifier->Challenge()); Discord->Client->Authorize(AuthArgs, FDiscordClientAuthorizationCallback::CreateUObject(this, &ADiscordSocialUnrealCharacter::OnAuthorizeCompleted)); } void ADiscordSocialUnrealCharacter::OnLogMessage(FString Message, EDiscordLoggingSeverity Severity) { UE_LOG(LogTemplateCharacter, Log, TEXT("[%s] %s"), *UEnum::GetValueAsString(Severity), *Message); } void ADiscordSocialUnrealCharacter::OnStatusChanged(EDiscordClientStatus Status, EDiscordClientError Error, int32 ErrorDetail) { UE_LOG(LogTemplateCharacter, Log, TEXT("Connection status: %s"), *UEnum::GetValueAsString(Status)); if (Status == EDiscordClientStatus::Ready) { UE_LOG(LogTemplateCharacter, Log, TEXT("Connected to Discord! Ready to go! You can now start using Discord features.")); UE_LOG(LogTemplateCharacter, Log, TEXT("Number of Relationships: %d"), Discord->Client->GetRelationships().Num()); UDiscordActivity activity; activity.SetDetails("In competitive"); activity.SetState("Diamond II"); } else if (Error != EDiscordClientError::None) { UE_LOG(LogTemplateCharacter, Log, TEXT("Connection error: %s (Detail: %d)"), *UEnum::GetValueAsString(Error), ErrorDetail); } } void ADiscordSocialUnrealCharacter::OnAuthorizeCompleted(UDiscordClientResult* Result, FString Code, FString RedirectUri) { if (!Result->Successful()) { UE_LOG(LogTemplateCharacter, Error, TEXT("Discord authorization failed: %s"), *Result->Error()); return; } UE_LOG(LogTemplateCharacter, Log, TEXT("Authorization successful! Getting access token...")); Discord->Client->GetToken(APPLICATION_ID, Code, CodeVerifier->Verifier(), RedirectUri, FDiscordClientTokenExchangeCallback::CreateUObject(this, &ADiscordSocialUnrealCharacter::OnTokenExchange)); } void ADiscordSocialUnrealCharacter::OnTokenExchange(UDiscordClientResult* Result, FString AccessToken, FString RefreshToken, EDiscordAuthorizationTokenType TokenType, int32 ExpiresIn, FString Scope) { if (!Result->Successful()) { UE_LOG(LogTemplateCharacter, Error, TEXT("Discord token exchange failed: %s"), *Result->Error()); } Discord->Client->UpdateToken(TokenType, AccessToken, FDiscordClientUpdateTokenCallback::CreateUObject(this, &ADiscordSocialUnrealCharacter::OnTokenUpdated)); } void ADiscordSocialUnrealCharacter::OnTokenUpdated(UDiscordClientResult* Result) { Discord->Client->Connect(); } ////////////////////////////////////////////////////////////////////////// // ADiscordSocialUnrealCharacter ``` -------------------------------- ### Example Entry Point Command Source: https://docs.discord.com/developers/interactions/application-commands This JSON defines an Entry Point command for an application. It specifies the command's name, description, type, and handler. ```json { "name": "launch", "description": "Launch Racing with Friends", "type": 4, "handler": 2 } ``` -------------------------------- ### Example Get Channel Command Payload Source: https://docs.discord.com/developers/topics/rpc This JSON payload is used to request detailed information about a specific Discord channel. ```json { "nonce": "f682697e-d257-4a17-ac0a-7e4b84e66663", "args": { "channel_id": "199737254929760257" }, "cmd": "GET_CHANNEL" } ``` -------------------------------- ### Initialize and Connect Discord Client in C++ Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c%2B%2B This snippet demonstrates how to initialize the Discord SDK, set up logging and status callbacks, authenticate, and connect to Discord. It includes signal handling for graceful shutdown. ```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; } ``` -------------------------------- ### Example Get Channels Response Payload Source: https://docs.discord.com/developers/topics/rpc This JSON payload contains a list of channels belonging to a guild, including their IDs, names, and types. ```json { "cmd": "GET_CHANNELS", "data": { "channels": [ { "id": "199737254929760256", "name": "general", "type": 0 }, { "id": "199737254929760257", "name": "General", "type": 2 } ] }, "nonce": "0dee7bd4-8f62-4ecc-9e0f-1b1839a4fa93" } ``` -------------------------------- ### Example Get Channels Command Payload Source: https://docs.discord.com/developers/topics/rpc This JSON payload is used to request a list of all channels within a specific Discord guild that the client is a part of. ```json { "nonce": "0dee7bd4-8f62-4ecc-9e0f-1b1839a4fa93", "args": { "guild_id": "199737254929760256" }, "cmd": "GET_CHANNELS" } ``` -------------------------------- ### Copy Example Environment File Source: https://docs.discord.com/developers/activities/building-an-activity Copies the example environment file to a new .env file in the project root. This is used to store sensitive credentials. ```bash cp example.env .env ``` -------------------------------- ### Example Activity Spectate Dispatch Payload Source: https://docs.discord.com/developers/topics/rpc This JSON payload is for the ACTIVITY_SPECTATE event, used when a user starts spectating an activity. It requires a spectate secret. ```json { "cmd": "DISPATCH", "data": { "secret": "e7eb30d2ee025ed05c71ea495f770b76454ee4e0" }, "evt": "ACTIVITY_SPECTATE" } ``` -------------------------------- ### Initialize, Authenticate, and Connect with Discord SDK (C++) Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c%2B%2B This snippet shows how to set up the Discord SDK in C++, including initialization, setting up logging and status callbacks, handling authentication, and connecting to Discord. It retrieves the initial friend count upon successful connection. ```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 Get Channel Response Payload Source: https://docs.discord.com/developers/topics/rpc This JSON payload represents the response received after requesting channel details, including channel properties and associated voice states. ```json { "cmd": "GET_CHANNEL", "data": { "id": "199737254929760257", "name": "General", "type": 2, "bitrate": 64000, "user_limit": 0, "guild_id": "199737254929760256", "position": 0, "voice_states": [ { "voice_state": { "mute": false, "deaf": false, "self_mute": false, "self_deaf": false, "suppress": false }, "user": { "id": "190320984123768832", "username": "test 2", "discriminator": "7479", "avatar": "b004ec1740a63ca06ae2e14c5cee11f3", "bot": false }, "nick": "test user 2", "volume": 110, "mute": false, "pan": { "left": 1.0, "right": 1.0 } } ] }, "nonce": "f682697e-d257-4a17-ac0a-7e4b84e66663" } ``` -------------------------------- ### Initialize Discord SDK Client Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c%2B%2B Includes necessary headers, defines the application ID, sets up a signal handler for graceful shutdown, and initializes the Discord client. This is a basic setup for the SDK. ```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 our Discord Client auto client = std::make_shared(); // Keep application running to allow SDK to receive events and callbacks while (running) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return 0; } ``` -------------------------------- ### Main Application with Event Handling Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c%2B%2B A complete C++ example demonstrating the initialization of the Discord SDK, setting up logging and status callbacks, and maintaining the application loop. This code is intended to be run as a standalone application. ```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; } ``` -------------------------------- ### Get Guild Vanity URL Example Source: https://docs.discord.com/developers/resources/guild Retrieves a partial invite object for a guild's vanity URL. This object contains the vanity code and its usage count. ```json { "code": "abc", "uses": 12 } ``` -------------------------------- ### Get Gateway Bot Source: https://docs.discord.com/developers/events/gateway Retrieves an object containing information for operating large or sharded bots, including the WSS URL, recommended shards, and session start limit. ```APIDOC ## GET /gateway/bot ### Description Returns an object with information to help operate large or sharded bots, including the WSS URL, recommended shards, and session start limits. This route should not be cached for extended periods. ### Method GET ### Endpoint /gateway/bot ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **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** (object) - Information on the current session start limit ##### Session Start Limit Object - **total** (integer) - Total number of session starts the current user is allowed - **remaining** (integer) - Remaining number of session starts the current user is allowed - **reset_after** (integer) - Number of milliseconds after which the limit resets - **max_concurrency** (integer) - Number of identify requests allowed per 5 seconds ### Request Example None ### Response Example ```json { "url": "wss://gateway.discord.gg/", "shards": 9, "session_start_limit": { "total": 1000, "remaining": 999, "reset_after": 14400000, "max_concurrency": 1 } } ``` ``` -------------------------------- ### Game Invite with Lobby Example Source: https://docs.discord.com/developers/discord-social-sdk/development-guides/managing-game-invites This C++ example demonstrates the full flow of creating a lobby, updating Rich Presence to enable invites, sending an invite, and accepting an invite to join a lobby. Ensure Rich Presence is configured correctly before sending invites. ```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"; } }); } }); }); ``` -------------------------------- ### Example Guild Onboarding Configuration Source: https://docs.discord.com/developers/resources/guild This JSON object demonstrates the structure of a guild onboarding configuration, including prompts with options, default channel IDs, and enablement status. It's useful for understanding how to set up onboarding for a Discord server. ```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 } ``` -------------------------------- ### Shard ID and Rate Limit Key Example (16 Shards) Source: https://docs.discord.com/developers/events/gateway Illustrates shard ID to rate limit key mapping when max_concurrency is 16, showing how all shards can start concurrently. ```text shard_id: 0, rate limit key (0 % 16): 0 shard_id: 1, rate limit key (1 % 16): 1 shard_id: 2, rate limit key (2 % 16): 2 shard_id: 3, rate limit key (3 % 16): 3 shard_id: 4, rate limit key (4 % 16): 4 shard_id: 5, rate limit key (5 % 16): 5 shard_id: 6, rate limit key (6 % 16): 6 shard_id: 7, rate limit key (7 % 16): 7 shard_id: 8, rate limit key (8 % 16): 8 shard_id: 9, rate limit key (9 % 16): 9 shard_id: 10, rate limit key (10 % 16): 10 shard_id: 11, rate limit key (11 % 16): 11 shard_id: 12, rate limit key (12 % 16): 12 shard_id: 13, rate limit key (13 % 16): 13 shard_id: 14, rate limit key (14 % 16): 14 shard_id: 15, rate limit key (15 % 16): 15 ``` -------------------------------- ### Example Discord Provided Link Source: https://docs.discord.com/developers/resources/application A basic Discord Provided Link for authorizing an application. This link directs users to a flow where scopes and permissions are determined by the app's Default Install Settings. ```url https://discord.com/oauth2/authorize?client_id=1234567895647001626 ``` -------------------------------- ### Navigating to Project Directory and Installing Dependencies Source: https://docs.discord.com/developers/tutorials/developing-a-user-installable-app Commands to change the current directory to the cloned project and install all necessary Node.js dependencies. Essential for running the application. ```bash # navigate to directory cd user-install-example # install dependencies npm install ``` -------------------------------- ### Make Rich Presence Dynamic Source: https://docs.discord.com/developers/game-development/how-to-get-your-game-seen Update Rich Presence dynamically as the player progresses through the game to create curiosity and keep information fresh. Examples show updates from starting a game to fighting a boss. ```cpp // Starting a new game activity.SetDetails("Story Mode"); activity.SetState("Choosing Items"); // Playing through the first level activity.SetDetails("Dungeon"); activity.SetState("Floor 1"); // Fighting the boss activity.SetDetails("Dungeon"); activity.SetState("VS. Grave Digger"); // The story continues! activity.SetDetails("Lost Jungle"); activity.SetState("Floor ?"); ``` -------------------------------- ### Create CMakeLists.txt Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c%2B%2B Creates a CMakeLists.txt file for project configuration. ```bash touch CMakeLists.txt ``` -------------------------------- ### Shard ID and Rate Limit Key Example (32 Shards) Source: https://docs.discord.com/developers/events/gateway Demonstrates shard ID to rate limit key mapping when max_concurrency is 16 and there are 32 shards, highlighting the need to start buckets in order. ```text shard_id: 0, rate limit key (0 % 16): 0 shard_id: 1, rate limit key (1 % 16): 1 shard_id: 2, rate limit key (2 % 16): 2 shard_id: 3, rate limit key (3 % 16): 3 shard_id: 4, rate limit key (4 % 16): 4 shard_id: 5, rate limit key (5 % 16): 5 shard_id: 6, rate limit key (6 % 16): 6 shard_id: 7, rate limit key (7 % 16): 7 shard_id: 8, rate limit key (8 % 16): 8 shard_id: 9, rate limit key (9 % 16): 9 shard_id: 10, rate limit key (10 % 16): 10 shard_id: 11, rate limit key (11 % 16): 11 shard_id: 12, rate limit key (12 % 16): 12 shard_id: 13, rate limit key (13 % 16): 13 shard_id: 14, rate limit key (14 % 16): 14 shard_id: 15, rate limit key (15 % 16): 15 shard_id: 16, rate limit key (16 % 16): 0 shard_id: 17, rate limit key (17 % 16): 1 shard_id: 18, rate limit key (18 % 16): 2 shard_id: 19, rate limit key (19 % 16): 3 shard_id: 20, rate limit key (20 % 16): 4 shard_id: 21, rate limit key (21 % 16): 5 shard_id: 22, rate limit key (22 % 16): 6 shard_id: 23, rate limit key (23 % 16): 7 shard_id: 24, rate limit key (24 % 16): 8 shard_id: 25, rate limit key (25 % 16): 9 shard_id: 26, rate limit key (26 % 16): 10 shard_id: 27, rate limit key (27 % 16): 11 shard_id: 28, rate limit key (28 % 16): 12 shard_id: 29, rate limit key (29 % 16): 13 shard_id: 30, rate limit key (30 % 16): 14 shard_id: 31, rate limit key (31 % 16): 15 ``` -------------------------------- ### Create Discord Instance (C++ and C#) Source: https://docs.discord.com/developers/developer-tools/game-sdk Initializes the Discord SDK with your application's client ID and creation flags. The C++ example uses a pointer to DiscordCore, while the C# example directly instantiates the Discord class. ```cpp // c++ land discord::Core* core{}; discord::Core::Create(53908232506183680, DiscordCreateFlags_Default, &core); ``` ```csharp // c# land var discord = new Discord(53908232506183680, (UInt64)Discord.CreateFlags.Default); ``` -------------------------------- ### Navigate to Client Directory Source: https://docs.discord.com/developers/activities/building-an-activity Change your current directory to the 'client' folder within the cloned project. ```bash cd getting-started-activity/client ``` -------------------------------- ### Modify Incoming Voice Data In-Place Source: https://docs.discord.com/developers/discord-social-sdk/development-guides/managing-voice-chat Starts a call with audio callbacks enabled, allowing for real-time manipulation of incoming audio samples. This example demonstrates dampening the volume of incoming audio by modifying the data in-place. ```cpp const auto call = client->StartCallWithAudioCallbacks( lobbyId, [](uint64_t userId, int16_t *data, const size_t samplesPerChannel, int sampleRate, const size_t channels, bool &outShouldMuteData) { // Dampen volume of incoming audio by modifying data's samples // in-place for (int i = 0; i < samplesPerChannel * channels; i++) { data[i] *= 0.5; // Reduce volume by 50% } }, [](int16_t *data, uint64_t samplesPerChannel, int32_t sampleRate, uint64_t channels) {}); ``` -------------------------------- ### Gateway Bot API Example Response Source: https://docs.discord.com/developers/events/gateway This JSON response provides the WSS URL for connecting to the Discord Gateway, the recommended number of shards, and details about the session start limit. Use this information to configure your bot's connection. ```json { "url": "wss://gateway.discord.gg/", "shards": 9, "session_start_limit": { "total": 1000, "remaining": 999, "reset_after": 14400000, "max_concurrency": 1 } } ```