Authenticate with Discord #

In this section, we’ll log into the platform with Discord. This method is appropriate for use in production.

Prerequisites:

Discord admin panel setup #

  1. Log into the Discord Admin Panel.
  2. Click on the Applications tab, then click the New Application button.
If the application has already been created, then you can click on it under My Applications.

  1. Name your application, then click the Create button.

  1. (optional) After your application has been created, you can click on the Bot section in the left sidebar, then click the Add Bot button. Confirm that you wish to create a bot. Once the bot has been created, click Reset Token and save the generated token–you can use this later in your config as the botToken.

  1. Click on OAuth2 in the left sidebar, then click the Add Redirect button. Paste the following URL: http://localhost:11000/v1/account/discord-redirect. Click the Save Changes button.

  1. In the left sidebar, click URL Generator which is nested under OAuth2. Tick the identify and email boxes, then choose http://localhost:11000/v1/account/discord-redirect under the Select Redirect URL dropdown.

Configure the Pragma Engine Discord Identity Provider #

  1. Obtain your clientSecret and clientId from the OAuth2 General tab of your application in the Discord Admin Panel. If you have not yet been issued a Client Secret, click the Reset Secret button.

The fields botToken, guildId, and authorizedRoleId are only required if you plan on using a bot to automatically authorize users from your Discord server who have a specific role.
  1. Open the User Settings cog in your Discord client, then scroll down to Advanced and toggle on Developer Mode.

  2. Access your guildId by right-clicking on a server and selecting Copy ID.

  3. Access your authorizedRoleId by opening Server Settings within a server, opening the Roles page, right-clicking on the desired Role, and selecting Copy ID.

  4. Navigate to the pragma-engine/platform/<PROJECT>/config/ directory and open local-dev.yml.

  5. Insert the following code while making sure to edit in your clientId, clientSecret, and redirectUri:

social:
  pluginConfigs:
    AccountService.identityProviderPlugins:
      plugins:
        Discord:
          class: "pragma.account.DiscordIdentityProviderPlugin"
          config:
            clientId: "${discordClientId}"
            clientSecret: "${discordClientSecret}"
            redirectUri: "http://localhost:11000/v1/account/discord-redirect"
            botToken: "${discordBotToken}"
            guildId: "${guildId}"
            allowedRoleIds: 
              1: "${RoleId1}"
              2: "${RoleId2}"
            playerLoginEnabled: true
            operatorLoginEnabled: false
            accountLinkingEnabled: true
            showPortalLoginButton: false
            visibleToOtherPlayers: false
  1. Run Pragma Engine via one of the following methods.
Running via Command Line
From your pragma-engine/platform working directory, run ./pragma run to start the platform.
Running in IntelliJ
Run Pragma from the IDE by selecting the ‘Run Pragma’ run configuration from the dropdown in the upper right.

Once the engine has started successfully, it prints the message INFO main - Pragma server startup complete.

Import the Discord SDK into Unreal #

  1. Download the Discord SDK from the Discord Developer site.
  2. Follow the directions on the Discord developer site to import the Discord SDK into your Unreal project.
  3. Add the bot to your server by doing the following:
    • In your bot’s settings go to OAuth2 -> URL Generator.
    • Tick the “bot” field.
    • Copy the URL and visit it.
    • Authorize your bot to your server.
Note that the code provided by the Discord guide for editing your-project-name.Build.cs is missing trailing semicolons.
Instead of creating a MyPawn class in the Discord, continue following the instructions here.

Integrate Discord login into your game #

We will use the MyPlayerController class we created in Create Player Controller and Blueprint to add a Discord login method.

  1. Open MyPlayerController.h in your IDE.
  2. Make sure your class has these definitions.
class discord::Core;

class AMyPlayerController : public APlayerController
{
    // ...
public:
    AMyPlayerController();

    virtual void BeginPlay() override;

    UFUNCTION(Exec)
    void LogInDiscord();

	    virtual void Tick(float DeltaSeconds) override;
        // ...

private:
    discord::Core* Discord;
    // ...
}
  1. Open MyPlayerController.cpp in your IDE.
  2. Add the following includes.
#include "discord-files/discord.h"
  1. Add the following to the constructor.
AMyPlayerController::AMyPlayerController()
{
    PrimaryActorTick.bStartWithTickEnabled = true;
    PrimaryActorTick.bCanEverTick = true;
}
  1. Add the following to the BeginPlay method.
    auto Result = discord::Core::Create("Discord Client Token", DiscordCreateFlags_Default, &Discord);
    if (Result != discord::Result::Ok)
    {
        UE_LOG(LogTemp, Display, TEXT("Pragma -- Error creating discord core object."));
        return;
    }
  1. Add the following method definitions to finish it off.

    void AMyPlayerController::LogInDiscord()
    {
        Discord->ApplicationManager().GetOAuth2Token([this](
            discord::Result Result, 
            discord::OAuth2Token token)
        {
            if (Result != discord::Result::Ok) {
                UE_LOG(LogTemp, Display, TEXT("Pragma -- Discord::GetOAuth2Token error."));
                return;
            }
            const char* AccessTokenUtf8 = token.GetAccessToken();
            const FString AccessTokenStrs{UTF8_TO_TCHAR(AccessTokenUtf8)};
    
            Player->LogIn(
                EPragma_Account_IdProvider::Discord, 
                AccessTokenStrs, 
                Pragma::FPlayer::FLoggedInDelegate::CreateWeakLambda(
                this, [this](const TPragmaResult<>& Result)
                {
                    if (Result.IsSuccessful())
                    {
                        UE_LOG(LogTemp, Display, TEXT("MyGameClient -- Logged in with Discord."));
                    }
                    else
                    {
                        UE_LOG(LogTemp, Error, TEXT("MyGameClient -- Discord login failed: %s"),
                            *Result.GetErrorAsString());
                    }
                }));
        });
    }
    
    void AMyPlayerController::Tick(float DeltaSecond)
    {
        Super::Tick(DeltaSecond);
        Discord->RunCallbacks();
    }
    
  2. Compile the project in your IDE.

  3. Save and click the Play icon at the top of the window.

  4. Click on the game window to focus it, open the in-game console with ~, and type LogInDiscord.

  5. Navigate to your local Pragma Portal and sign in via Pragma Unsafe using the test04 account.

  6. Confirm that you see both the test04 account and your Discord account’s display name in the list of logged-in players.

  7. Click on the Discord account’s display name. Under the Identity providers section, verify that the account’s identity provider is Discord.