### Install and Run Frontend Dependencies
Source: https://docs.discord.com/developers/activities/building-an-activity
Install project dependencies and start the frontend development server for the sample Activity.
```bash
# install project dependencies
npm install
# start frontend
npm run dev
```
--------------------------------
### Start Local Development Server
Source: https://docs.discord.com/developers/tutorials/hosting-on-cloudflare-workers
Starts the local development server for the Discord bot. Assumes dependencies are installed and commands are registered.
```bash
$ npm run dev
```
--------------------------------
### Example Discord Provided Install Link
Source: https://docs.discord.com/developers/resources/application
This is a basic example of a Discord Provided Link. It directs users to the authorization endpoint with only the client ID specified. Scopes and permissions are determined by the app's default install settings.
```url
https://discord.com/oauth2/authorize?client_id=1234567895647001626
```
--------------------------------
### Navigate to Project Directory and Install Dependencies
Source: https://docs.discord.com/developers/quick-start/getting-started
After cloning the repository, navigate into the project directory and run 'npm install' to download and install all necessary project dependencies. Ensure Node.js is installed beforehand.
```bash
# navigate to directory
cd discord-example-app
# install dependencies
npm install
```
--------------------------------
### Clone Discord Example App Repository
Source: https://docs.discord.com/developers/quick-start/getting-started
Use this command to clone the sample application repository from GitHub to your local machine. This repository contains the code examples used throughout the guide.
```bash
git clone https://github.com/discord/discord-example-app.git
```
--------------------------------
### Start Client-Side App
Source: https://docs.discord.com/developers/activities/building-an-activity
Navigate to the client directory and start the development server for your Activity. This command is used during local development.
```bash
cd client
npm run dev
```
--------------------------------
### Example Usage of ImageCard and CardGroup
Source: https://docs.discord.com/developers/guides/communities
Demonstrates how to use the ImageCard and CardGroup components to create a layout for community guides. This includes creating a card for a game development community guide and another for community invites.
```javascript
Creating a community for your game involves establishing a Discord server to foster direct communication with players, gather feedback, and keep engagement alive between updates.
}>
Learn how to create and manage community invites to grow your community.
```
--------------------------------
### Start Backend Server
Source: https://docs.discord.com/developers/activities/building-an-activity
Starts the backend development server for your Discord Activity.
```bash
npm run dev
```
--------------------------------
### Get Activity Instance - Found
Source: https://docs.discord.com/developers/activities/development-guides/multiplayer-experience
This example shows the curl command to fetch an existing activity instance. It demonstrates a successful response containing details about the activity session.
```curl
curl https://discord.com/api/applications/1215413995645968394/activity-instances/i-1276580072400224306-gc-912952092627435520-912954213460484116 -H 'Authorization: Bot '
{"application_id":"1215413995645968394","instance_id":"i-1276580072400224306-gc-912952092627435520-912954213460484116","launch_id":"1276580072400224306","location":{"id":"gc-912952092627435520-912954213460484116","kind":"gc","channel_id":"912954213460484116","guild_id":"912952092627435520"},"users":["205519959982473217"]}
```
--------------------------------
### Install Project Dependencies
Source: https://docs.discord.com/developers/tutorials/developing-a-user-installable-app
Install all necessary Node.js dependencies for the project using npm.
```bash
npm install
```
--------------------------------
### Install Server Dependencies
Source: https://docs.discord.com/developers/activities/building-an-activity
Installs the necessary dependencies for the server-side of your Discord Activity.
```bash
# move into our server directory
cd server
# install dependencies
npm install
```
--------------------------------
### Example Partial Invite Object
Source: https://docs.discord.com/developers/resources/guild
An example of the partial invite object returned for a guild's vanity URL.
```json
{
"code": "abc",
"uses": 12
}
```
--------------------------------
### Get Gateway Bot Example Response
Source: https://docs.discord.com/developers/events/gateway
This JSON response provides gateway information for bots, including a WSS URL, the recommended number of shards, and session start limit details. It is returned by the GET /gateway/bot endpoint and requires authentication with a bot token. This response should not be cached for extended periods.
```json
{
"url": "wss://gateway.discord.gg/",
"shards": 9,
"session_start_limit": {
"total": 1000,
"remaining": 999,
"reset_after": 14400000,
"max_concurrency": 1
}
}
```
--------------------------------
### Example Welcome Screen Object Structure
Source: https://docs.discord.com/developers/resources/guild
Demonstrates the structure of a welcome screen object, including the server description and a list of welcome channels. This is used to configure how new users are introduced to a server.
```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": "🔦"
}
]
}
```
--------------------------------
### Example: Putting It All Together
Source: https://docs.discord.com/developers/discord-social-sdk/development-guides/linked-channels
Demonstrates the integration of all previously shown functions to manage Discord channel linking and communication within a game application. This serves as a high-level usage example.
```cpp
// filepath: your_game/main.cpp
int main() {
auto client = std::make_shared();
// Set up handlers
SetupMessageHandlers(client);
// When user wants to link a channel:
FetchDiscordServers(client);
// After user selects a guild:
FetchChannelsForGuild(client, selectedGuildId);
// After user selects a channel:
LinkChannelToLobby(
client,
currentLobbyId,
selectedChannelId,
isPrivateChannel
);
// When sending a message:
SendLobbyMessage(client, currentLobbyId, "Hello from the game!");
// When done with the channel:
UnlinkChannel(client, currentLobbyId);
return 0;
}
```
--------------------------------
### Full Discord SDK Integration Example in C++
Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c++
This comprehensive example demonstrates initializing the Discord SDK, setting up callbacks for logging and status changes, handling OAuth2 authentication, and connecting to Discord. It includes accessing the friends 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 Authorization Information Response
Source: https://docs.discord.com/developers/topics/oauth2
An example JSON response structure for the 'Get Current Authorization Information' endpoint, detailing application, scopes, expiration, and user information.
```json
{
"application": {
"id": "159799960412356608",
"name": "AIRHORN SOLUTIONS",
"icon": "f03590d3eb764081d154a66340ea7d6d",
"description": "",
"hook": true,
"bot_public": true,
"bot_require_code_grant": false,
"verify_key": "c8cde6a3c8c6e49d86af3191287b3ce255872be1fff6dc285bdb420c06a2c3c8"
},
"scopes": [
"guilds.join",
"identify"
],
"expires": "2021-01-23T02:33:17.017000+00:00",
"user": {
"id": "268473310986240001",
"username": "discord",
"avatar": "f749bb0cbeeb26ef21eca719337d20f1",
"discriminator": "0",
"global_name": "Discord",
"public_flags": 131072
}
}
```
--------------------------------
### Example Guild Onboarding Configuration
Source: https://docs.discord.com/developers/resources/guild
This JSON object demonstrates a complete guild onboarding configuration, including prompts, options, and default channels. It shows how to structure the data for enabling onboarding features.
```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
}
```
--------------------------------
### Project Structure Overview
Source: https://docs.discord.com/developers/tutorials/developing-a-user-installable-app
This outlines the file structure of the sample user-installable app. It helps understand the organization of the project files.
```text
├── .env.sample -> sample .env file
├── app.js -> main entrypoint for the app
├── commands.js -> slash command payloads + helpers
├── game.js -> logic specific to the fake game
├── utils.js -> utility functions and enums
├── package.json
├── README.md
└── .gitignore
```
--------------------------------
### React Card Component Example
Source: https://docs.discord.com/developers/platform/game-profiles
Example of a React Card component used to link to a specific page, featuring an icon, title, and descriptive text. This is used to guide users to related documentation or actions.
```javascript
}>
Learn how to claim your game on Discord and customize your game's profile.
```
--------------------------------
### Get Gateway URL Example Response
Source: https://docs.discord.com/developers/events/gateway
This JSON response provides a WSS URL for connecting to the Discord Gateway. It is returned by the GET /gateway endpoint and does not require authentication. Apps should cache this URL and only fetch a new one if a connection fails.
```json
{
"url": "wss://gateway.discord.gg/"
}
```
--------------------------------
### Example Hello Event
Source: https://docs.discord.com/developers/events/gateway
This is an example of the Hello event received upon connecting to the Gateway. It contains the heartbeat interval in milliseconds that should be used for maintaining the connection.
```json
{
"op": 10,
"d": {
"heartbeat_interval": 45000
}
}
```
--------------------------------
### Project Structure Overview
Source: https://docs.discord.com/developers/tutorials/configuring-app-metadata-for-linked-roles
This tree outlines the key files and directories within the example project, highlighting the purpose of each component.
```tree
├── assets -> images used in this tutorial
├── src
├──├── config.js -> Parsing of local configuration
├──├── discord.js -> Discord specific auth & API wrapper
├──├── register.js -> Tool to register the metadata schema
├──├── server.js -> Main entry point for the application
├──├── storage.js -> Provider for storing OAuth2 tokens
├── .env -> your credentials and IDs
├── .gitignore
├── package.json
└── README.md
```
--------------------------------
### Get Channels Response Payload
Source: https://docs.discord.com/developers/topics/rpc
This is an example response when requesting guild channels. It includes a list of partial channel objects, each with an ID, name, and type.
```json
{
"cmd": "GET_CHANNELS",
"data": {
"channels": [
{
"id": "199737254929760256",
"name": "general",
"type": 0
},
{
"id": "199737254929760257",
"name": "General",
"type": 2
}
]
},
"nonce": "0dee7bd4-8f62-4ecc-9e0f-1b1839a4fa93"
}
```
--------------------------------
### 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 your project's root. This is used to store sensitive credentials.
```bash
cp example.env .env
```
--------------------------------
### Get Activity Instance - Not Found
Source: https://docs.discord.com/developers/activities/development-guides/multiplayer-experience
This example shows the curl command to fetch an activity instance that does not exist. It demonstrates the expected 404 response from the API.
```curl
curl https://discord.com/api/applications/1215413995645968394/activity-instances/i-1234567890-gc-912952092627435520-912954213460484116 -H 'Authorization: Bot '
{"message": "404: Not Found", "code": 0}
```
--------------------------------
### Example Get Guilds Response Payload
Source: https://docs.discord.com/developers/topics/rpc
This JSON payload represents the response containing a list of guilds the client is in. Each guild object includes its ID and name.
```json
{
"cmd": "GET_GUILDS",
"data": {
"guilds": [
{
"id": "199737254929760256",
"name": "test"
}
]
},
"nonce": "e16fcbed-8bfa-4fd4-ba09-73b72e809833"
}
```
--------------------------------
### Example Get Guilds Command Payload
Source: https://docs.discord.com/developers/topics/rpc
This JSON payload is used to request a list of guilds the client is currently a member of. It requires a nonce and an empty arguments object.
```json
{
"nonce": "e16fcbed-8bfa-4fd4-ba09-73b72e809833",
"args": {},
"cmd": "GET_GUILDS"
}
```
--------------------------------
### Get Guild Role Member Counts Example Response
Source: https://docs.discord.com/developers/resources/guild
This JSON response maps role IDs to the number of members possessing that role. It excludes the @everyone role.
```json
{
"613425648685547541": 1337,
"1409696176629878905": 2,
"697138785317814292": 67
}
```
--------------------------------
### Initialize and Connect Discord Client in C++
Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c++
This snippet demonstrates the complete process of initializing the Discord SDK client, setting up logging and status callbacks, performing OAuth2 authentication, and connecting to Discord. Ensure your APPLICATION_ID is correctly set. The client remains running via a loop that calls RunCallbacks.
```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;
}
```
--------------------------------
### Clone Sample App Repository
Source: https://docs.discord.com/developers/tutorials/developing-a-user-installable-app
Use this command to clone the user-installable app's sample code from GitHub.
```bash
git clone https://github.com/discord/user-install-example.git
```
--------------------------------
### Setting Timestamps for Rich Presence
Source: https://docs.discord.com/developers/discord-social-sdk/development-guides/setting-rich-presence
Include timestamps to show the duration of a player's current activity or countdowns for timed events. This example sets the start time of the activity.
```cpp
// Setting Timestamps
discordpp::ActivityTimestamps timestamps;
timestamps.SetStart(time(nullptr));
// timestamps.SetEnd(time(nullptr) + 3600);
activity.SetTimestamps(timestamps);
```
--------------------------------
### Create Project Directory
Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c++
Sets up the basic folder structure for a new C++ project intended to use the Discord Social SDK.
```bash
mkdir MyGame
cd MyGame
mkdir lib
```
--------------------------------
### Example Get Channel Command Payload
Source: https://docs.discord.com/developers/topics/rpc
This JSON payload is used to request information about a specific channel using the GET_CHANNEL command. It requires a channel ID and a nonce for tracking.
```json
{
"nonce": "f682697e-d257-4a17-ac0a-7e4b84e66663",
"args": {
"channel_id": "199737254929760257"
},
"cmd": "GET_CHANNEL"
}
```
--------------------------------
### Example Entry Point Command Structure
Source: https://docs.discord.com/developers/interactions/application-commands
This JSON object defines the structure of an example Entry Point command. It includes the command's name, description, type (4 for a command), and handler (2 for DISCORD_LAUNCH_ACTIVITY).
```json
{
"name": "launch",
"description": "Launch Racing with Friends",
"type": 4,
"handler": 2
}
```
--------------------------------
### Complete main.cpp for Discord SDK Integration
Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c++
This C++ code demonstrates the complete setup for the Discord SDK, including client initialization, logging, status callbacks, authentication, and updating rich presence. Ensure you replace the placeholder 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 = 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;
// Configure rich presence details
discordpp::Activity activity;
activity.SetType(discordpp::ActivityTypes::Playing);
activity.SetState("In Competitive Match");
activity.SetDetails("Rank: Diamond II");
// Update rich presence
client->UpdateRichPresence(activity, [](discordpp::ClientResult result) {
if(result.Successful()) {
std::cout << "🎮 Rich Presence updated successfully!\n";
} else {
std::cerr << "❌ Rich Presence update failed";
}
});
} 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 Guild Command Payload
Source: https://docs.discord.com/developers/topics/rpc
This JSON payload is used to request information about a specific guild from Discord. Ensure the 'guild_id' field is populated with the target guild's ID.
```json
{
"nonce": "9524922c-3d32-413a-bdaa-0804f4332588",
"args": {
"guild_id": "199737254929760256"
},
"cmd": "GET_GUILD"
}
```
--------------------------------
### Request rpc.activities.write Scope with authorize()
Source: https://docs.discord.com/developers/rich-presence/using-with-the-embedded-app-sdk
Use this example to authorize your application with the `rpc.activities.write` scope, which is necessary for displaying custom Rich Presence data. Ensure you have installed and instantiated the Embedded App SDK before calling this function.
```javascript
const {
code
} = await discordSdk.commands.authorize({
client_id: import.meta.env.VITE_DISCORD_CLIENT_ID,
response_type: "code",
state: "",
prompt: "none",
scope: [
"identify",
"rpc.activities.write"
],
});
```
--------------------------------
### Navigate to Client Directory
Source: https://docs.discord.com/developers/activities/building-an-activity
Navigate to the client directory of the cloned project to manage frontend dependencies.
```bash
cd getting-started-activity/client
```
--------------------------------
### Example Get Voice Settings Response Payload
Source: https://docs.discord.com/developers/topics/rpc
This JSON payload illustrates the structure of a response when retrieving Discord's voice settings. It includes details about input/output devices, voice activity settings, and various audio processing options.
```json
{
"cmd": "GET_VOICE_SETTINGS",
"data": {
"input": {
"available_devices": [
{
"id": "default",
"name": "Default"
},
{
"id": "Built-in Microphone",
"name": "Built-in Microphone"
}
],
"device_id": "default",
"volume": 49.803921580314636
},
"output": {
"available_devices": [
{
"id": "default",
"name": "Default"
},
{
"id": "Built-in Output",
"name": "Built-in Output"
}
],
"device_id": "default",
"volume": 93.00000071525574
},
"mode": {
"type": "VOICE_ACTIVITY",
"auto_threshold": true,
"threshold": -46.92622950819673,
"shortcut": [{ "type": 0, "code": 12, "name": "i" }],
"delay": 98.36065573770492
},
"automatic_gain_control": false,
"echo_cancellation": false,
"noise_suppression": false,
"qos": false,
"silence_warning": false,
"deaf": false,
"mute": false
},
"nonce": "fa07c532-bb03-4f75-8b9a-397f5109afb6"
}
```
--------------------------------
### Complete Discord SDK C++ Example with Event Handling
Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-c++
A full C++ application demonstrating Discord SDK initialization, logging, and status callbacks. This example includes signal handling for graceful shutdown and a loop to keep the application running.
```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;
}
```
--------------------------------
### Example Get Channel Response Payload
Source: https://docs.discord.com/developers/topics/rpc
This JSON payload represents the response received after a successful GET_CHANNEL command. It contains detailed information about the requested channel, including its ID, name, type, and associated data like voice states or messages.
```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"
}
```
--------------------------------
### DiscordManager.cs Setup and Callbacks
Source: https://docs.discord.com/developers/discord-social-sdk/getting-started/using-unity
This C# script for Unity initializes the Discord client, sets up logging and status change callbacks, and handles UI element references. Ensure the 'clientId' is set in the Unity Inspector and UI elements are connected.
```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;
void Start()
{
client = new Client();
// Modifying LoggingSeverity will show you more or less logging information
client.AddLogCallback(OnLog, LoggingSeverity.Error);
client.SetStatusChangedCallback(OnStatusChanged);
// Make sure the button has a listener
if (loginButton != null)
{
loginButton.onClick.AddListener(StartOAuthFlow);
}
else
{
Debug.LogError("Login button reference is missing, connect it in the inspector!");
}
// Set initial status text
if (statusText != null)
{
statusText.text = "Ready to login";
}
else
{
Debug.LogError("Status text reference is missing, connect it in the inspector!");
}
}
private void OnLog(string message, LoggingSeverity severity)
{
Debug.Log($
```
--------------------------------
### Subscription Object Example
Source: https://docs.discord.com/developers/resources/subscription
This JSON object demonstrates the structure of a Discord subscription. It includes details like subscription ID, user ID, SKUs, entitlement IDs, renewal SKUs, current period start and end dates, status, and cancellation time.
```json
{
"id": "1278078770116427839",
"user_id": "1088605110638227537",
"sku_ids": ["1158857122189168803"],
"entitlement_ids": [],
"renewal_sku_ids": null,
"current_period_start": "2024-08-27T19:48:44.406602+00:00",
"current_period_end": "2024-09-27T19:48:44.406602+00:00",
"status": 0,
"canceled_at": null
}
```