### Discord Client Constructor Examples Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Provides examples of how to construct a discordpp::Client object. This includes a move constructor, a default constructor, a constructor allowing customization of Discord API and web URLs, and a constructor using discordpp::ClientCreateOptions for advanced configuration. ```cpp // Move constructor Client(Client &&_other_) noexcept; // Default constructor explicit Client(); // Constructor with custom URLs explicit Client(std::string _apiBase, std::string _webBase); // Constructor with create options explicit Client(discordpp::ClientCreateOptions _options); ``` -------------------------------- ### Invites Code Example Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Activity Provides a comprehensive C++ code example demonstrating the entire process of sending and accepting activity invites using the Discord SDK. ```APIDOC ## Invites Code Example ### Description This code example illustrates the flow of creating, sending, and accepting Discord activity invites. ### User A: Sending an Invite ```cpp // User A // 1. Create a lobby with secret std::string lobbySecret = "foo"; client->CreateOrJoinLobby(lobbySecret, [=](discordpp::ClientResult result, uint64_t lobbyId) { // 2. Update rich presence with join secret discordpp::Activity activity{}; // set name, state, party size ... discordpp::ActivitySecrets secrets{}; secrets.SetJoin(lobbySecret); activity.SetSecrets(secrets); client->UpdateRichPresence(std::move(activity), [](discordpp::ClientResult result) {}); }); // 3. Some time later, send an invite client->SendActivityInvite(USER_B_ID, "come play with me", [](auto result) {}); ``` ### User B: Receiving and Accepting an Invite ```cpp // User B // 4. Monitor for new invites. Alternatively, you can use // Client::SetActivityInviteUpdatedCallback to get updates on existing invites. client->SetActivityInviteCreatedCallback([client](auto invite) { // 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 secret) { if (result.Successful()) { // 5. Join the lobby using the joinSecret client->CreateOrJoinLobby(secret, [](discordpp::ClientResult result, uint64_t lobbyId) { // Successfully joined lobby! }); } }); }); ``` ### Relevant Discord SDK Components: * `discordpp::ActivitySecrets` * `discordpp::ActivitySecrets::SetJoin` * `discordpp::Activity` * `discordpp::ClientResult` * `discordpp::ClientResult::Successful` ``` -------------------------------- ### Start Call (C++) Source: https://discord.com/developers/docs/social-sdk/release_notes Initiates a voice call. Returns null if attempting to start a call in a lobby while already in a call for that same lobby. ```cpp discordpp::Call* Client::StartCall(discordpp::LobbyID lobby_id); ``` -------------------------------- ### Initiating OAuth2 Authorization Flow Source: https://discord.com/developers/docs/social-sdk/authentication Details on starting the authorization process using the SDK. ```APIDOC ## discordpp::Client::Authorize ### Description This method initiates the OAuth2 authorization flow, prompting the user to connect their Discord account. ### Method `discordpp::Client::Authorize` ### Parameters - **scopes** (array of strings) - Required - The set of permissions your application is requesting. Recommended to use `discordpp::Client::GetDefaultCommunicationScopes()` or `discordpp::Client::GetDefaultPresenceScopes()`. ### Usage This method will interact with the Discord client or a browser to request user authorization. ``` -------------------------------- ### Example Invites Flow Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Activity Illustrates a typical flow for using Discord lobbies for game invites, from creating a lobby to updating presence information. ```APIDOC ## Example Invites Flow ### Description Demonstrates a common workflow for integrating Discord lobbies with rich presence for game invites. ### Steps 1. **User Starts Game**: Creates a lobby with a random secret string using `Client::CreateOrJoinLobby`. 2. **Publish Rich Presence**: Publishes their Rich Presence with the join secret and party size information. 3. **Another User Sees Presence**: Another user can see the Rich Presence and choose to join. 4. **Join Accepted**: The new user receives the join secret and uses `CreateOrJoinLobby(joinSecret)` to join the lobby. 5. **Update Presence**: The original user detects the lobby membership change and updates their Rich Presence with the new party size. ``` -------------------------------- ### Initialize Discord SDK on Android Source: https://discord.com/developers/docs/social-sdk/md_pages_2mobile This Java snippet demonstrates how to initialize the Discord Social SDK within the `onCreate` method of your main Android Activity. It requires passing the Activity context to `DiscordSocialSdkInit.setEngineActivity()` for proper SDK setup. ```java import com.discord.socialsdk.DiscordSocialSdkInit; public class YourGameActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ... other setup ... DiscordSocialSdkInit.setEngineActivity(this); // ... rest of onCreate ... } } ``` -------------------------------- ### Handle Voice Call Events and Start Calls Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Functions to manage voice call participation and initiate calls. Includes setting callbacks for participant changes and starting/joining calls with or without audio callbacks. ```cpp void | SetVoiceParticipantChangedCallback (discordpp::Client::VoiceParticipantChangedCallback cb) | Callback invoked whenever a user in a lobby joins or leaves a voice call. discordpp::Call | StartCall (uint64_t channelId) | Starts or joins a call in the lobby specified by channelId (For a lobby, simply pass in the lobbyId). discordpp::Call | StartCallWithAudioCallbacks (uint64_t lobbyId, discordpp::Client::UserAudioReceivedCallback receivedCb, discordpp::Client::UserAudioCapturedCallback capturedCb) | Starts or joins a call in the specified lobby. ``` -------------------------------- ### SetStart Method for ActivityTimestamps C++ Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1ActivityTimestamps A setter method to configure the start time for an activity. It takes a uint64_t representing the time in milliseconds since the Unix epoch. ```cpp void discordpp::ActivityTimestamps::SetStart( uint64_t _Start ) ``` -------------------------------- ### Discord Social SDK - Functions Source: https://discord.com/developers/docs/social-sdk/functions_func_p This section details the available functions within the Discord Social SDK, categorized by their starting letter. ```APIDOC ## Discord Social SDK Functions ### Description Documentation for functions available in the Discord Social SDK, grouped by their initial letter. ### Method N/A (These are function calls within the SDK, not HTTP requests) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Functions starting with 'p' ### ParentApplicationId() - **Description**: Retrieves the Parent Application ID associated with an Activity or Activity Invite. - **Returns**: `discordpp::Activity` or `discordpp::ActivityInvite` ### ParentId() - **Description**: Retrieves the Parent ID for a Guild Channel. - **Returns**: `discordpp::GuildChannel` ### Party() - **Description**: Retrieves the Party associated with an Activity. - **Returns**: `discordpp::Activity` ### PartyId() - **Description**: Retrieves the Party ID from an Activity Invite. - **Returns**: `discordpp::ActivityInvite` ### Position() - **Description**: Retrieves the position of a Guild Channel. - **Returns**: `discordpp::GuildChannel` ### Privacy() - **Description**: Retrieves the privacy setting of an Activity Party. - **Returns**: `discordpp::ActivityParty` ### ProviderId() - **Description**: Retrieves the Provider ID from a User Application Profile Handle. - **Returns**: `discordpp::UserApplicationProfileHandle` ### ProviderIssuedUserId() - **Description**: Retrieves the Provider Issued User ID from a User Application Profile Handle. - **Returns**: `discordpp::UserApplicationProfileHandle` ### ProviderType() - **Description**: Retrieves the Provider Type from a User Application Profile Handle. - **Returns**: `discordpp::UserApplicationProfileHandle` ### ProvisionalUserMergeCompleted() - **Description**: Checks if a provisional user merge has been completed for the Client. - **Returns**: `discordpp::Client` ``` -------------------------------- ### StartCallWithAudioCallbacks Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Starts or joins a voice call in a specified lobby, providing callbacks for receiving and capturing audio. Allows for in-place modification of audio data. ```APIDOC ## StartCallWithAudioCallbacks() ### Description Initiates or joins a voice call in a given lobby, while also setting up callbacks for handling incoming audio (`receivedCb`) and outgoing captured audio (`capturedCb`). The `receivedCb` allows modification of audio data before playback, and `capturedCb` allows processing of local audio before transmission. ### Method `discordpp::Call` ### Endpoint `discordpp::Client::StartCallWithAudioCallbacks(uint64_t _lobbyId_, discordpp::Client::UserAudioReceivedCallback _receivedCb_, discordpp::Client::UserAudioCapturedCallback _capturedCb_) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **_lobbyId_** (uint64_t) - Required - The ID of the lobby to start or join a call in. - **_receivedCb_** (discordpp::Client::UserAudioReceivedCallback) - Required - Callback invoked when incoming audio is received. Can mute audio by setting `outShouldMute` to `true`. - **_capturedCb_** (discordpp::Client::UserAudioCapturedCallback) - Required - Callback invoked when local audio is captured before transmission. Useful for voice moderation or effects. ### Request Example ```cpp client.StartCallWithAudioCallbacks(123456789012345678, [](uint64_t userId, const discordpp::AudioData& data, bool& outShouldMute) { // Process received audio }, [](discordpp::AudioData& data) { // Process captured audio }); ``` ### Response #### Success Response (discordpp::Call) - **return value** (discordpp::Call) - An object representing the active call. Returns null if the user is already in the specified voice channel. #### Response Example `// A valid discordpp::Call object or null` ``` -------------------------------- ### Handle In-Discord Authentication Flow with C++ SDK Source: https://discord.com/developers/docs/social-sdk/release_notes Enables handling authentication requests that originate from Discord entry points, allowing users to start account linking directly from Discord. Uses C++. ```cpp class Client { public: // Registers a callback for authorize requests originating from Discord. DiscordResult RegisterAuthorizeRequestCallback(std::function callback); // Removes the registered authorize request callback. DiscordResult RemoveAuthorizeRequestCallback(); }; ``` -------------------------------- ### Discord Social SDK: ActivityTimestamps Class Members Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1ActivityTimestamps-members This section lists all members of the discordpp::ActivityTimestamps class, including inherited members. It details constructors, member functions like SetStart, SetEnd, Start, End, and operators. ```cpp ActivityTimestamps(ActivityTimestamps &&other) noexcept ActivityTimestamps(const ActivityTimestamps &arg0) ActivityTimestamps() End() const nullobj operator bool() const operator=(ActivityTimestamps &&other) noexcept operator=(const ActivityTimestamps &arg0) SetEnd(uint64_t End) SetStart(uint64_t Start) Start() const ``` -------------------------------- ### Optional: Remove Unused Android Permissions Source: https://discord.com/developers/docs/social-sdk/md_pages_2mobile This example demonstrates how to conditionally remove permissions from the `AndroidManifest.xml` if they are not needed, such as voice permissions when voice functionality is not used. The `tools:node="remove"` attribute helps in selectively pruning the manifest. ```xml ``` -------------------------------- ### Integration Type Enumeration Source: https://discord.com/developers/docs/social-sdk/namespacediscordpp Represents the type of integration the application will be installed as. It can be a guild install or a user install. ```cpp enum class | IntegrationType { GuildInstall = 0 , UserInstall = 1 } ``` -------------------------------- ### ClientCreateOptions: Experimental Audio System Configuration (C++) Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1ClientCreateOptions This section details how to retrieve and set the experimental audio system for the Discord client. The `ExperimentalAudioSystem` option allows for selection of different audio handling mechanisms, with a default of `AudioSystem::Standard`. Proper configuration is essential for audio-related features. ```cpp discordpp::AudioSystem discordpp::ClientCreateOptions::ExperimentalAudioSystem () const // The audio system to use. Defaults to AudioSystem::Standard. void discordpp::ClientCreateOptions::SetExperimentalAudioSystem (discordpp::AudioSystem ExperimentalAudioSystem) // Setter for ClientCreateOptions::ExperimentalAudioSystem. ``` -------------------------------- ### Discord Social SDK: Client Initialization and Connection Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client-members Demonstrates various ways to initialize and connect the discordpp::Client in the Discord Social SDK. This includes default constructors, constructors with API base URLs, and constructors utilizing client creation options. Proper initialization is key to establishing a connection with Discord services. ```cpp Client()| discordpp::Client| explicit Client(std::string apiBase, std::string webBase)| discordpp::Client| explicit Client(discordpp::ClientCreateOptions options)| discordpp::Client| explicit Connect()| discordpp::Client| ``` -------------------------------- ### Start Getter for ActivityTimestamps C++ Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1ActivityTimestamps A getter method that returns the start time of an activity in milliseconds since the Unix epoch. The SDK attempts to convert seconds to milliseconds for small values. If provided, the Discord client displays a timer. ```cpp uint64_t discordpp::ActivityTimestamps::Start() const ``` -------------------------------- ### Client Constructors Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Provides details on the different ways to construct and initialize a `discordpp::Client` object. ```APIDOC ## Constructors: discordpp::Client::Client ### 1. Move Constructor ```cpp Client(Client && _other_) noexcept ``` Move constructor for `Client`. ### 2. Default Constructor ```cpp explicit Client() ``` Creates a new instance of the `Client`. ### 3. Base URL Constructor ```cpp explicit Client(std::string _apiBase, std::string _webBase) ``` Creates a new instance of the `Client` allowing customization of the Discord URL. ### 4. Options Constructor ```cpp explicit Client(discordpp::ClientCreateOptions _options) ``` Creates a new instance of the `Client` with custom options. ``` -------------------------------- ### Client Initialization Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Functions for creating and managing instances of the Discord Client. ```APIDOC ## Client Initialization ### Description Functions for creating and managing instances of the Discord Client. ### Method Constructor/Destructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (N/A) N/A #### Response Example None ``` -------------------------------- ### discordpp::LobbyHandle::Id Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1LobbyHandle Gets the unique identifier of the lobby. ```APIDOC ## discordpp::LobbyHandle::Id ### Description Returns the id of the lobby. ### Method GET (Conceptual - this is a method, not a typical HTTP endpoint) ### Endpoint N/A (Class method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None (Method call) ### Response #### Success Response - **Id** (uint64_t) - The unique identifier of the lobby. #### Response Example ```json { "lobbyId": "9876543210" } ``` ``` -------------------------------- ### Discord Social SDK - ClientCreateOptions Class Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1ClientCreateOptions Documentation for the ClientCreateOptions class, which allows setting advanced initialization-time options for the Discord Client. ```APIDOC ## Class: ClientCreateOptions ### Description Options for creating a new Client instance. This class may be used to set advanced initialization-time options on Client. ### Public Member Functions * **ClientCreateOptions (ClientCreateOptions &&other) noexcept** Move constructor for ClientCreateOptions. * **ClientCreateOptions & operator= (ClientCreateOptions &&other) noexcept** Move assignment operator for ClientCreateOptions. * **operator bool () const** Returns true if the instance contains a valid object. * **ClientCreateOptions (const ClientCreateOptions &arg0)** Copy constructor for ClientCreateOptions. * **ClientCreateOptions & operator= (const ClientCreateOptions &arg0)** Copy assignment operator for ClientCreateOptions. * **std::string WebBase () const** The base URL for the Discord web application. * **void SetWebBase (std::string WebBase)** Setter for ClientCreateOptions::WebBase. * **std::string ApiBase () const** The base URL for the Discord API. * **void SetApiBase (std::string ApiBase)** Setter for ClientCreateOptions::ApiBase. * **discordpp::AudioSystem ExperimentalAudioSystem () const** The audio system to use. Defaults to AudioSystem::Standard. * **void SetExperimentalAudioSystem (discordpp::AudioSystem ExperimentalAudioSystem)** Setter for ClientCreateOptions::ExperimentalAudioSystem. * **bool ExperimentalAndroidPreventCommsForBluetooth () const** Whether to prevent communications mode on Android when Bluetooth is connected. * **void SetExperimentalAndroidPreventCommsForBluetooth (bool ExperimentalAndroidPreventCommsForBluetooth)** Setter for ClientCreateOptions::ExperimentalAndroidPreventCommsForBluetooth. * **std::optional< uint64_t > CpuAffinityMask () const** CPU affinity mask hint for certain platforms. Depending on platform support, may or may not be ignored. * **void SetCpuAffinityMask (std::optional< uint64_t > CpuAffinityMask)** Setter for ClientCreateOptions::CpuAffinityMask. ### Static Public Attributes * **static const ClientCreateOptions nullobj** Uninitialized instance of ClientCreateOptions. ### Constructor & Destructor Documentation * **◆ ClientCreateOptions() [1/2]** discordpp::ClientCreateOptions::ClientCreateOptions ( ClientCreateOptions && _other_) noexcept Move constructor for ClientCreateOptions. ``` -------------------------------- ### Disclosure Types Enumeration Source: https://discord.com/developers/docs/social-sdk/namespacediscordpp Represents types of disclosures, with MessageDataVisibleOnDiscord being a specific example. ```cpp enum class | DisclosureTypes { MessageDataVisibleOnDiscord = 3 } ``` -------------------------------- ### Include Discord SDK Headers (C++/ObjC++) Source: https://discord.com/developers/docs/social-sdk/md_pages_2mobile This code illustrates how to include the Discord SDK's header file in C++ or Objective-C++ (.mm) source files. It also shows the necessary `#define DISCORDPP_IMPLEMENTATION` directive that must be placed in exactly one source file to ensure the implementation code is generated. ```cpp #define DISCORDPP_IMPLEMENTATION // Define this in exactly one .cpp or .mm file #include ``` -------------------------------- ### SetLobbyUpdatedCallback Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Sets a callback to be invoked when a lobby is edited, for example if the lobby's metadata is changed. ```APIDOC ## SetLobbyUpdatedCallback() ### Description Sets a callback to be invoked when a lobby is edited, for example if the lobby's metadata is changed. ### Method void ### Endpoint discordpp::Client::SetLobbyUpdatedCallback ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **_cb_** (discordpp::Client::LobbyUpdatedCallback) - The callback function to set. ``` -------------------------------- ### GET /lobbies/{lobby_id} Source: https://discord.com/developers/docs/social-sdk/server_apis Retrieves the Lobby object for a specified lobby if it exists. ```APIDOC ## GET /lobbies/ ### Description Returns the Lobby object for the specified lobby if it exists. ### Method GET ### Endpoint `/lobbies/` ### Parameters #### Path Parameters - **lobby_id** (string) - Required - The unique identifier of the lobby to retrieve. ### Response #### Success Response (200) - **Lobby object** - The lobby object, including its members and metadata. #### Response Example ```json { "id": "", "metadata": { "game_mode": "team_deathmatch" }, "members": [ { "user_id": "", "metadata": {}, "flags": 0 }, { "user_id": "", "metadata": {}, "flags": 0 } ], "idle_timeout_seconds": 1800 } ``` ``` -------------------------------- ### Voice Call Management API Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Endpoints for managing voice calls, including starting, joining, and handling participant changes. ```APIDOC ## SetVoiceParticipantChangedCallback ### Description Callback invoked whenever a user in a lobby joins or leaves a voice call. ### Method void ### Endpoint Client::SetVoiceParticipantChangedCallback ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cb** (discordpp::Client::VoiceParticipantChangedCallback) - The callback function to be invoked. ### Request Example ```json { "cb": "" } ``` ### Response #### Success Response (200) No specific return value documented, assumed void. #### Response Example N/A ``` ```APIDOC ## ShowAudioRoutePicker ### Description On iOS devices, show the system audio route picker. ### Method bool ### Endpoint Client::ShowAudioRoutePicker ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response (200) - **returnValue** (bool) - Indicates if the audio route picker was successfully shown. #### Response Example ```json { "returnValue": true } ``` ``` ```APIDOC ## StartCall ### Description Starts or joins a call in the lobby specified by channelId (For a lobby, simply pass in the lobbyId). ### Method discordpp::Call ### Endpoint Client::StartCall ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **channelId** (uint64_t) - The ID of the lobby or channel to start/join a call in. ### Request Example ```json { "channelId": 1234567890 } ``` ### Response #### Success Response (200) - **returnValue** (discordpp::Call) - An object representing the active call. #### Response Example ```json { "returnValue": { "id": "", "state": "connected" } } ``` ``` ```APIDOC ## StartCallWithAudioCallbacks ### Description Starts or joins a call in the specified lobby, with custom audio callbacks. ### Method discordpp::Call ### Endpoint Client::StartCallWithAudioCallbacks ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **lobbyId** (uint64_t) - The ID of the lobby to start/join a call in. - **receivedCb** (discordpp::Client::UserAudioReceivedCallback) - Callback for received audio data. - **capturedCb** (discordpp::Client::UserAudioCapturedCallback) - Callback for captured audio data. ### Request Example ```json { "lobbyId": 1234567890, "receivedCb": "", "capturedCb": "" } ``` ### Response #### Success Response (200) - **returnValue** (discordpp::Call) - An object representing the active call. #### Response Example ```json { "returnValue": { "id": "", "state": "connected" } } ``` ``` -------------------------------- ### Discord Overlay Configuration Source: https://discord.com/developers/docs/social-sdk/authentication Information on how to enable and test the Discord overlay within your game. ```APIDOC ## Discord Overlay ### Description The Discord overlay allows for in-game features like chat and voice communication. It is disabled by default for stability and can be manually enabled for testing. ### Enabling for Testing 1. Go to your Discord **Settings**. 2. Navigate to the **Games** tab. 3. Manually add your game and enable the overlay. ### Verifying and Enabling by Default Once testing is complete, your game will be added to a list of overlay-supported games, enabling the overlay by default for users. Improvements are underway to remove this manual verification step. ### Window PID Requirement If your game's main window process is different from the integration process, you may need to set the window PID using the `discordpp::Client::SetGameWindowPid` method. ``` -------------------------------- ### Linux: Register Launch Command/Steam Application (C++) Source: https://discord.com/developers/docs/social-sdk/release_notes Fixes issues with `Client::RegisterLaunchCommand` and `Client::RegisterLaunchSteamApplication` on Linux, including hangs and ensuring they work correctly from within the Steam Runtime. This improves the integration of the SDK with game launching mechanisms. ```cpp Client::RegisterLaunchCommand Client::RegisterLaunchSteamApplication ``` -------------------------------- ### Get Discord SDK Access Token from Device (Console) Source: https://discord.com/developers/docs/social-sdk/getting_started This C++ snippet illustrates how to obtain an access token for the Discord SDK on console platforms using device authorization. It configures `discordpp::DeviceAuthorizationArgs` with the client ID and desired scopes, then initiates the process to get tokens. Upon successful retrieval of access and refresh tokens, the client's token is updated, and the client connects to Discord. This method is suitable for environments where a direct user interaction for OAuth2 might be cumbersome. ```cpp discordpp::DeviceAuthorizationArgs args{}; args.SetClientId(APPLICATION_ID); args.SetScopes(discordpp::Client::GetDefaultPresenceScopes()); client->GetTokenFromDevice(args, [client](auto result, auto accessToken, auto refreshToken, auto, auto, auto) { printf("Received access token, connecting to Discord\n"); client->UpdateToken(discordpp::AuthorizationTokenType::Bearer, accessToken, [client](auto result) { client->Connect(); }); }); ``` -------------------------------- ### Discord SDK ClientCreateOptions Constructor (C++) Source: https://discord.com/developers/docs/social-sdk/functions_w This snippet shows the constructor for the discordpp::ClientCreateOptions class within the Discord Social SDK. It's used for initializing client creation settings. No external dependencies are required beyond the SDK itself. ```cpp discordpp::ClientCreateOptions::ClientCreateOptions() ``` -------------------------------- ### Audio Event Callbacks Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Functions for setting up callback functions for audio-related events. ```APIDOC ## Audio Event Callbacks ### Description Functions for setting up callback functions for audio-related events. ### Method POST ### Endpoint `/audio/events/device_change`, `/audio/events/no_audio_input` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **callback** (function pointer) - The callback function to be invoked. - **dBFSThreshold** (float) - The threshold for detecting no audio input. ### Request Example None (callbacks are registered, not sent in a request body) ### Response #### Success Response (200) N/A (void function) #### Response Example None ``` -------------------------------- ### Get User by User ID Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Fetches the UserHandle associated with a given user ID. This function allows retrieval of specific user details based on their unique identifier. ```cpp std::optional< discordpp::UserHandle > GetUser (uint64_t userId) const ``` -------------------------------- ### Register Launch Command Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Registers a command that Discord will run to launch your game when a user accepts an activity invite. This is crucial for allowing users to join your game directly from Discord. ```APIDOC ## POST /registerLaunchCommand ### Description Registers a command that Discord will run to launch your game when a user accepts an activity invite. This function should be invoked when the SDK starts up to ensure the game can be launched for future invites. ### Method POST ### Endpoint /registerLaunchCommand ### Parameters #### Query Parameters - **_applicationId** (uint64_t) - Required - The unique identifier for your Discord application. - **_command** (std::string) - Required - The command to execute for launching the game. On Windows/Linux, this is typically a path to an executable with optional launch parameters. On macOS, this should be a .app bundle or a custom protocol. An empty string registers the current running executable/bundle. ### Request Example ```json { "applicationId": 123456789012345678, "command": "C:\\Program Files\\MyGame\\MyGame.exe" } ``` ### Response #### Success Response (200) - **success** (bool) - True if the command was successfully registered, false otherwise. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Call Management API Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Call This section covers the core functions for managing a Discord voice call, including getting and setting audio modes, mute states, and call status. ```APIDOC ## Call Management API ### GetAudioMode Returns whether the call is configured to use voice auto detection or push to talk for the current user. ### Method GET ### Endpoint N/A (Member function) ### Parameters None ### Response - **audioMode** (discordpp::AudioModeType) - The current audio mode (Voice Activity Detection or Push-to-Talk). ## SetAudioMode Sets whether to use voice auto detection or push to talk for the current user on this call. ### Method POST ### Endpoint N/A (Member function) ### Parameters #### Request Body - **audioMode** (discordpp::AudioModeType) - The desired audio mode (Voice Activity Detection or Push-to-Talk). ## GetLocalMute Returns whether the current user has locally muted the given userId for themselves. ### Method GET ### Endpoint N/A (Member function) ### Parameters #### Path Parameters - **userId** (uint64_t) - The ID of the user to check. ### Response - **muteStatus** (bool) - True if the user is locally muted, false otherwise. ## SetLocalMute Locally mutes the given userId, so that the current user cannot hear them anymore. ### Method POST ### Endpoint N/A (Member function) ### Parameters #### Request Body - **userId** (uint64_t) - The ID of the user to mute. - **mute** (bool) - True to mute, false to unmute. ## GetPTTActive Returns whether push to talk is currently active, meaning the user is currently pressing their configured push to talk key. ### Method GET ### Endpoint N/A (Member function) ### Parameters None ### Response - **active** (bool) - True if PTT is active, false otherwise. ## SetPTTActive When push to talk is enabled, this should be called whenever the user pushes or releases their configured push to talk key. This key must be configured in the game, the SDK does not handle keybinds itself. ### Method POST ### Endpoint N/A (Member function) ### Parameters #### Request Body - **active** (bool) - True if the PTT key is pressed, false if released. ## GetPTTReleaseDelay Returns the time that PTT is active after the user releases the PTT key and SetPTTActive(false) is called. ### Method GET ### Endpoint N/A (Member function) ### Parameters None ### Response - **delayMs** (uint32_t) - The PTT release delay in milliseconds. ## SetPTTReleaseDelay If set, extends the time that PTT is active after the user releases the PTT key and SetPTTActive(false) is called. ### Method POST ### Endpoint N/A (Member function) ### Parameters #### Request Body - **releaseDelayMs** (uint32_t) - The desired PTT release delay in milliseconds. ## GetSelfDeaf Returns whether the current user is deafened. ### Method GET ### Endpoint N/A (Member function) ### Parameters None ### Response - **deafStatus** (bool) - True if the current user is deafened, false otherwise. ## SetSelfDeaf Mutes all audio from the currently active call for the current user. They will not be able to hear any other participants, and no other participants will be able to hear the current user either. ### Method POST ### Endpoint N/A (Member function) ### Parameters #### Request Body - **deaf** (bool) - True to deafen, false to undeafen. ## GetSelfMute Returns whether the current user's microphone is muted. ### Method GET ### Endpoint N/A (Member function) ### Parameters None ### Response - **muteStatus** (bool) - True if the current user is muted, false otherwise. ## SetSelfMute Mutes the current user's microphone so that no other participant in their active calls can hear them. ### Method POST ### Endpoint N/A (Member function) ### Parameters #### Request Body - **mute** (bool) - True to mute, false to unmute. ## GetStatus Returns the current call status. ### Method GET ### Endpoint N/A (Member function) ### Parameters None ### Response - **status** (discordpp::Call::Status) - The current status of the call. ## GetVADThreshold Returns the current configuration for void auto detection thresholds. See the description of the VADThreshold struct for specifics. ### Method GET ### Endpoint N/A (Member function) ### Parameters None ### Response - **settings** (discordpp::VADThresholdSettings) - The current VAD threshold settings. ## SetVADThreshold Customizes the void auto detection thresholds for picking up activity from a user's mic. ### Method POST ### Endpoint N/A (Member function) ### Parameters #### Request Body - **automatic** (bool) - Whether to use automatic VAD threshold adjustment. - **threshold** (float) - The VAD threshold value (if automatic is false). ``` -------------------------------- ### Retrieve Discord Relationships Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Retrieves information about user relationships. This includes getting a specific relationship handle, a list of all relationships, or relationships filtered by group type (e.g., online, in-game). ```cpp discordpp::RelationshipHandle GetRelationshipHandle (uint64_t userId) const ``` ```cpp std::vector< discordpp::RelationshipHandle > GetRelationships () const ``` ```cpp std::vector< discordpp::RelationshipHandle > GetRelationshipsByGroup (discordpp::RelationshipGroupType groupType) const ``` -------------------------------- ### Set Up Discord SDK Logging and Status Callbacks Source: https://discord.com/developers/docs/social-sdk/getting_started This C++ snippet demonstrates how to attach callbacks to the discordpp::Client to receive log messages and monitor status changes. It's crucial for knowing when the client is ready to accept SDK function calls. The `AddLogCallback` function registers a handler for log messages, while `SetStatusChangedCallback` handles transitions between client states, including the 'Ready' state. ```cpp client->AddLogCallback([](auto message, auto severity) { printf("[%s] %s", discordpp::LoggingSeverityToString(severity).c_str(), message.c_str()); }, discordpp::LoggingSeverity::Info); client->SetStatusChangedCallback([client](auto status, auto error, auto details) { printf("Status has changed to %s\n", discordpp::Client::StatusToString(status).c_str()); if (status == discordpp::Client::Status::Ready) { printf("Client is ready, you can now call SDK functions. For example:\n"); printf("You have %d friends\n", static_cast(client->GetRelationships().size())); } else if (error != discordpp::Client::Error::None) { printf("Error connecting: %s %d\n", discordpp::Client::ErrorToString(error).c_str(), details); } }); ``` -------------------------------- ### Connect Discord SDK with Access Token (C++) Source: https://discord.com/developers/docs/social-sdk/getting_started This snippet demonstrates how to update the SDK's authorization token and initiate a connection. It assumes an existing accessToken and uses a callback to handle the connection result. The SDK connects asynchronously, requiring a status check for readiness. ```cpp client->UpdateToken(discordpp::AuthorizationTokenType::Bearer, accessToken, [client](auto result) { client->Connect(); }); ``` -------------------------------- ### Get PTT Release Delay (C++) Source: https://discord.com/developers/docs/social-sdk/release_notes Retrieves the delay for releasing Push-to-Talk (PTT). This controls how long audio is transmitted after the PTT key is released. ```cpp uint32_t discordpp::Call::GetPTTReleaseDelay(); ``` -------------------------------- ### ClientCreateOptions: WebBase and ApiBase Configuration (C++) Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1ClientCreateOptions These functions allow you to get and set the base URLs for the Discord web application and API, respectively. This is crucial for directing client communications to the correct endpoints. The `WebBase` typically points to the web application, while `ApiBase` targets the actual API services. ```cpp std::string discordpp::ClientCreateOptions::WebBase () const // The base URL for the Discord web application. void discordpp::ClientCreateOptions::SetWebBase (std::string WebBase) // Setter for ClientCreateOptions::WebBase. std::string discordpp::ClientCreateOptions::ApiBase () const // The base URL for the Discord API. void discordpp::ClientCreateOptions::SetApiBase (std::string ApiBase) // Setter for ClientCreateOptions::ApiBase. ``` -------------------------------- ### Get VAD Threshold (C++) Source: https://discord.com/developers/docs/social-sdk/release_notes Retrieves the Voice Activity Detection (VAD) threshold for the voice engine. This value determines the sensitivity for detecting speech. ```cpp float discordpp::Call::GetVADThreshold(); ``` -------------------------------- ### Define DISCORDPP_IMPLEMENTATION for Standalone C++ SDK Source: https://discord.com/developers/docs/social-sdk/installation To include the implementation code for the standalone C++ SDK, you must define DISCORDPP_IMPLEMENTATION in exactly one C++ file before including 'discordpp.h'. This ensures the underlying C API is linked correctly. Ensure you also link the shared C library. ```cpp #define DISCORDPP_IMPLEMENTATION // Include discordpp.h after the define ``` -------------------------------- ### Get Discord Client Connected User Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Retrieves the user currently logged into the Discord client, provided the Discord app is running and the SDK is connected to it. Requires the application ID and a callback function. ```cpp void GetDiscordClientConnectedUser (uint64_t applicationId, discordpp::Client::GetDiscordClientConnectedUserCallback callback) const ``` -------------------------------- ### Logging and Status Callbacks Source: https://discord.com/developers/docs/social-sdk/getting_started This section details how to set up logging callbacks to view SDK messages and status changes. It emphasizes the importance of the `SetStatusChangedCallback` to know when the client is ready for SDK function calls. ```APIDOC ## POST /api/websites/discord_developers_social-sdk/logging ### Description Attach callbacks to `discordpp::Client` to view logs and monitor its status. It's crucial to know when the client is ready for SDK operations. ### Method POST ### Endpoint `/api/websites/discord_developers_social-sdk/logging` ### Parameters #### Request Body - **client** (discordpp::Client*) - Required - The client instance to attach callbacks to. - **severity** (discordpp::LoggingSeverity) - Optional - The minimum severity level for logs to be captured. Defaults to `Info`. ### Request Example ```json { "client": "", "severity": "Info" } ``` ### Response #### Success Response (200) - **message** (string) - The log message. - **severity** (string) - The severity level of the log message. #### Response Example ```json { "message": "Client is ready, you can now call SDK functions.", "severity": "Info" } ``` ## Utility Functions ### `discordpp::Client::StatusToString(discordpp::Client::Status type)` Converts the `Status` enum to a string. ### `discordpp::Client::ErrorToString(discordpp::Client::Error type)` Converts the `Error` enum to a string. ### `discordpp::LoggingSeverity::Info` Represents informational log messages. ``` -------------------------------- ### Run Discord SDK Callbacks Source: https://discord.com/developers/docs/social-sdk/md_pages_2mobile This C++ code snippet shows the essential call to `discordpp::RunCallbacks()` which must be executed within your application's main loop. This function processes events and updates the SDK's state, ensuring seamless integration with Discord services. ```cpp // Inside your main game loop: discordpp::RunCallbacks(); ``` -------------------------------- ### Get Current User V2 Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1Client Retrieves the current authenticated user's information. Unlike GetCurrentUser(), this method returns std::nullopt if no user is authenticated, providing a clearer indication of user availability. ```cpp std::optional< discordpp::UserHandle > GetCurrentUserV2 () const ``` -------------------------------- ### ActivityInvite Class Source: https://discord.com/developers/docs/social-sdk/classdiscordpp_1_1ActivityInvite Documentation for the ActivityInvite class and its member functions. ```APIDOC ## ActivityInvite Class Overview This class represents an activity invite within the Discord Social SDK. It provides methods to access and manage information related to an invite, such as sender ID, channel ID, message ID, invite type, application IDs, party ID, session ID, and validation status. ### Constructors * **`ActivityInvite(ActivityInvite &&other) noexcept`**: Move constructor. * **`ActivityInvite(const ActivityInvite &rhs)`**: Copy constructor. ### Assignment Operators * **`ActivityInvite &operator=(ActivityInvite &&other) noexcept`**: Move assignment operator. * **`ActivityInvite &operator=(const ActivityInvite &rhs)`**: Copy assignment operator. ### Member Functions * **`uint64_t SenderId() const`**: Returns the user ID of the user who sent the invite. * **`void SetSenderId(uint64_t SenderId)`**: Setter for `ActivityInvite::SenderId`. * **`uint64_t ChannelId() const`**: Returns the ID of the Discord channel in which the invite was sent. * **`void SetChannelId(uint64_t ChannelId)`**: Setter for `ActivityInvite::ChannelId`. * **`uint64_t MessageId() const`**: Returns the ID of the Discord message that contains the invite. * **`void SetMessageId(uint64_t MessageId)`**: Setter for `ActivityInvite::MessageId`. * **`discordpp::ActivityActionTypes Type() const`**: Returns the type of invite that was sent. * **`void SetType(discordpp::ActivityActionTypes Type)`**: Setter for `ActivityInvite::Type`. * **`uint64_t ApplicationId() const`**: Returns the target application of the invite. * **`void SetApplicationId(uint64_t ApplicationId)`**: Setter for `ActivityInvite::ApplicationId`. * **`uint64_t ParentApplicationId() const`**: Returns the application ID of the parent. This is applicable if there is a parent for a publisher's suite of applications. * **`void SetParentApplicationId(uint64_t ParentApplicationId)`**: Setter for `ActivityInvite::ParentApplicationId`. * **`std::string PartyId() const`**: Returns the ID of the party the invite was sent for. * **`void SetPartyId(std::string PartyId)`**: Setter for `ActivityInvite::PartyId`. * **`std::string SessionId() const`**: Returns the session ID of the user who sent the invite. * **`void SetSessionId(std::string SessionId)`**: Setter for `ActivityInvite::SessionId`. * **`bool IsValid() const`**: Returns `true` if the invite is currently joinable. An invite becomes invalid if it was sent more than 6 hours ago or if the sender is no longer playing the game the invite is for. * **`void SetIsValid(bool IsValid)`**: Setter for `ActivityInvite::IsValid`. * **`explicit operator bool() const`**: Returns `true` if the instance contains a valid object. ``` -------------------------------- ### Open API Spec Integration Source: https://discord.com/developers/docs/social-sdk/server_apis Information on utilizing Discord's published Open API Spec to generate clients for easier API interaction, with a Python example provided. ```APIDOC ## Open API Spec Discord publishes an Open API Spec at https://github.com/discord/discord-api-spec, and this can be used to generate a client in your preferred backend language to make it easier to call the various APIs. A good tool for that is https://openapi-generator.tech/ For Python for example that might look like this: ```python import openapi_client import os from pprint import pprint configuration = openapi_client.Configuration(host = "https://discord.com/api/v10") configuration.api_key['BotToken'] = 'Bot ' + os.environ["API_KEY"] with openapi_client.ApiClient(configuration) as api_client: api_instance = openapi_client.DefaultApi(api_client) request = openapi_client.CreateLobbyRequest() request.metadata={'foo':'bar'} pprint(api_instance.create_lobby(request)) ``` ``` -------------------------------- ### Running Callbacks Source: https://discord.com/developers/docs/social-sdk/getting_started Explains the necessity of periodically executing registered callbacks within your application's main loop to ensure proper functioning of the SDK. For Unity or Unreal plugins, this is handled automatically. ```APIDOC ## POST /api/websites/discord_developers_social-sdk/run_callbacks ### Description Periodically execute registered callbacks in your application's main loop. This function is essential for the SDK to process events and updates. ### Method POST ### Endpoint `/api/websites/discord_developers_social-sdk/run_callbacks` ### Parameters This endpoint does not require any parameters. ### Request Example ```json { "message": "Executing callbacks." } ``` ### Response #### Success Response (200) - **status** (string) - Indicates that callbacks were executed successfully. #### Response Example ```json { "status": "Callbacks executed." } ``` ### `discordpp::RunCallbacks()` **Definition** discordpp.h:29 Calls all pending callbacks. ```