diff --git a/app/Helpers/Discord.php b/app/Helpers/Discord.php new file mode 100644 index 0000000..e05c757 --- /dev/null +++ b/app/Helpers/Discord.php @@ -0,0 +1,116 @@ +. + */ + + +namespace App\Helpers; + +use App\Exceptions\AccountNotLinkedException; +use App\User; +use Illuminate\Http\Client\RequestException; +use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\Crypt; +use Illuminate\Support\Facades\Http; + +class Discord +{ + + /** + * The current working guild. Default is Home guild from app config + * @var string + */ + protected string $workingGuild; + + + public function __construct() { + if (!is_null($this->workingGuild)) { + $this->setWorkingGuild(config('services.discord.home_guild')); + } + } + + + /** + * Sets the working guild + * + * @param string $workingGuild + * @return Discord + */ + public function setWorkingGuild(string $workingGuild): Discord + { + $this->workingGuild = $workingGuild; + return $this; + } + + /** + * Adds sepcified user to specified guild. Bot must be member of target guild, and account must be linked + * + * @param User $user + * @return object|bool A GuildMember object; false if member is already in guild + * @throws AccountNotLinkedException Thrown when user didn't link/create their account yet + * @throws RequestException Any client and server errors + * @see https://discord.com/developers/docs/resources/guild#guild-member-object + */ + public function addGuildMember(User $user): object|bool + { + if ($user->hasDiscordConnection()) { + $params = [ + 'access_token' => $user->discord_token + ]; + + $member = Http::withBody(json_encode($params), 'application/json') + ->withHeaders([ + 'Authorization' => 'Bot ' . config('services.discord.token') + ])->put(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/members/{$user->discord_user_id}") + ->throw(); + + if ($member->successful() && $member->status() == 204) { + return false; + } else { + return (object) $member->json(); + } + } + + throw new AccountNotLinkedException('Specified Discord user has not linked their account yet.'); + } + + + /** + * Bans a specified user from the guild. + * May be called from the suspension service optionally by the banning user + * + * @param User $user The user to ban from the Guild + * @param string $reason The reason to supply Discord with + * @return void Nothing on success + * @throws RequestException + */ + public function addGuildBan(User $user, string $reason): void { + + if ($user->hasDiscordConnection()) { + $req = Http::withHeaders([ + 'Authorization' => 'Bot ' . config('services.discord.token'), + 'X-Audit-Log-Reason' => $reason + ])->put(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/bans/{$user->discord_user_id}") + ->throw(); + } + + } + + +}