InteractsWithDiscord Trait

What is InteractsWithDiscord Trait?

The InteractsWithDiscord.php trait adds the discordAccount relationship and a set of methods that delegate to the linked DiscordAccount.

The trait is optional. The same methods are available on the account itself, which can be retrieved with DiscordAccount::forUser($user).

app/Models/User.php
namespace App\Models;
 
use Illuminate\Foundation\Auth\User as Authenticatable;
use Jakyeru\Larascord\Traits\InteractsWithDiscord;
 
class User extends Authenticatable
{
    use InteractsWithDiscord;
}

discordAccount

/**
* Get the user's Discord account relationship.
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/

hasDiscordAccount

/**
* Determine whether the user has linked a Discord account.
*
* @return bool
*/

getDiscordTag

This method returns the user's tag in the format username#discriminator. For accounts migrated to the new username system, it returns the username, followed by the display name in brackets, for example jakye (Jakye).

/**
* Get the user's Discord tag.
*
* @return string|null
*/

getDiscordAccessToken

This method will try getting a new access_token using the refresh_token if the current access_token is expired.

/**
* Get the user's Discord access token.
*
* @return Jakyeru\Larascord\Types\AccessToken|null
*/

unlinkDiscordAccount

⚠️

This method revokes the OAuth2 access token with Discord and deletes the row from larascord_accounts. The user is not deleted.

/**
* Revoke the access token and unlink the user's Discord account.
*
* @return bool
* @throws Illuminate\Http\Client\RequestException
*/

getDiscordConnections

⚠️

This method will make a request to Discord's API. It is recommended to cache the response.

/**
* Get the user's connections.
*
* @return Illuminate\Support\Collection
* @throws Illuminate\Http\Client\RequestException
* @throws Exception
*/

Example

use \Illuminate\Support\Facades\Log;
 
$user = auth()->user();
 
try {
    $connections = $user->getDiscordConnections();
 
    Log::info(json_encode($connections->first()));
    /*
      {
        "type": "github",
        "id": "36800842",
        "name": "JakyeRU",
        "visibility": true,
        "friend_sync": false,
        "show_activity": false,
        "verified": true,
        "two_way_link": false,
        "metadata_visibility": 1
      }
    */
 } catch (\Exception $exception) {
    Log::error('Something went wrong.');
 }

getDiscordAvatar

This method generates the cdn url for user's avatars with a fallback image if the user does not have an avatar.

Parameters

The options parameter is optional.

ParameterTypeDefaultDescription
optionsarray[]Options for the image.
options.extensionstringpngAccepted image extensions: png, jpg, jpeg, webp, gif. Fallback image can only be png.
options.sizeint128Image size can be any power of two between 16 and 4096. Fallback image will be 256.
options.colorintrandomColor of fallback image: 0:blue 1:gray 2:green 3:orange 4:red 5:magenta.

Example

 
<img src="{{ Auth::user()->getDiscordAvatar(['extension' => 'webp', 'size' => 64, 'color' => 2]) }}" alt="{{ Auth::user()->getDiscordTag() }}" />
/**
* This will fetch the user's avatar with:
* - webp extension (fallback image will be png).
* - height and width of 64px (fallback image will 256x256).
* - Color of the fallback image will be green.
*/

getDiscordGuilds

⚠️

This method will make a request to Discord's API. It is recommended to cache the response.

/**
* Returns the user's guilds from Discord's API.
*
* @return Illuminate\Support\Collection
* @throws Illuminate\Http\Client\RequestException
* @throws Exception
*/

Parameters

The withCounts parameter is optional.

ParameterTypeDescription
withCountsboolInclude member counts

Example

use \Illuminate\Support\Facades\Log;
 
$user = auth()->user();
 
try {
    $guilds = $user->getDiscordGuilds(true);
 
    Log::info(json_encode($guilds->first()));
    /*
      {
        "id": "81384788765712384",
        "name": "Discord API",
        "icon": "a363a84e969bcbe1353eb2fdfb2e50e6",
        "owner": false,
        "permissions": 104189632,
        "features": [
          "ANIMATED_ICON",
          "INVITE_SPLASH"
        ],
        "permissions_new": "110917634608832",
        "approximate_member_count": 425,
        "approximate_presence_count": 312
      }
    */
 } catch (\Exception $exception) {
    Log::error('Something went wrong.');
 }

getDiscordGuildMember

⚠️

This method will make a request to Discord's API. It is recommended to cache the response.

/**
* Returns the user's guild member from Discord's API.
*
* @return Jakyeru\Larascord\Types\GuildMember|null
* @throws Illuminate\Http\Client\RequestException
* @throws Exception
*/

Example

use \Illuminate\Support\Facades\Log;
 
$user = auth()->user();
 
try {
    $guildMember = $user->getDiscordGuildMember('123456789012345678');
 
    Log::info(json_encode($guildMember));
    /*
        {
            "avatar": null,
            "joined_at": "2023-01-04T09:26:07.172000Z",
            "nick": "My Server Nickname",
            "roles": [
                "1082025544411000832"
            ],
            "deaf": false,
            "mute": false
        }
    */
 } catch (\Exception $exception) {
    Log::error('Something went wrong.');
 }

joinDiscordGuild

⚠️

The bot's access token must be set in .env as LARASCORD_ACCESS_TOKEN.

The bot must belong to the same application used for authorization and must be a member of the guild with CREATE_INSTANT_INVITE permission.

The OAuth2 access token must have the guilds.join scope.

/**
* Join a guild.
*
* @return Jakyeru\Larascord\Types\GuildMember|null
* @throws Illuminate\Http\Client\RequestException
* @throws Exception
*/

Parameters

The options parameter is optional.

ParameterTypeDescription
guildIdstringThe guild ID.
optionsarrayThe options.
options.nickstringThe nickname to give the user.
options.rolesarrayThe roles to give the user.
options.muteboolWhether to mute the user.
options.deafboolWhether to deafen the user.

Example

use \Illuminate\Support\Facades\Log;
 
$user = auth()->user();
 
try {
    $guildMember = $user->joinDiscordGuild('81384788765712384', [
        'roles' => ['81384788765712384'],
        'nick' => 'Test'
    ]);
 
    Log::info('Joined guild.');
 } catch (\Exception $exception) {
    Log::error('Something went wrong.');
 }

inDiscordGuild

/**
* Determine whether the user is a member of at least one of the given guilds.
* The result is cached like the "discord.guild" middleware.
*
* @param string ...$guildIds
* @return bool
* @throws \Exception
*/

Example

Gate::define('chat', fn (User $user) => $user->inDiscordGuild('81384788765712384'));

hasDiscordRole

/**
* Determine whether the user has at least one of the given roles in a guild.
* The result is cached like the "discord.role" middleware.
*
* @param string $guildId
* @param string ...$roleIds
* @return bool
* @throws \Exception
*/

Example

Gate::define('moderate', fn (User $user) => $user->hasDiscordRole('81384788765712384', '81384788765712385'));

See Guild and Role Middleware for how results are cached.