Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor the Discord Api Helper to use the RateLimiter #168

Merged
merged 2 commits into from
Oct 30, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions src/Discord/ApiHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@
class ApiHelper
{
const TOKEN_TYPE_BOT = 'Bot';
const TOKEN_TYPE_OAUTH = 'OAuth';

private $botToken;

/** @var DiscordClient|null */
private $client;

public function __construct(string $discordBotToken)
{
Expand All @@ -30,7 +31,7 @@ public function __construct(string $discordBotToken)

public function getGuild(int $guildId): Guild
{
$client = $this->getClient($this->botToken, self::TOKEN_TYPE_BOT);
$client = $this->getClient();

return $client->guild->getGuild([
'guild.id' => $guildId,
Expand All @@ -42,7 +43,7 @@ public function getGuild(int $guildId): Guild
*/
public function getMembersInGuild(int $guildId, int $after = null): array
{
return $this->getClient($this->botToken, self::TOKEN_TYPE_BOT)->guild->listGuildMembers([
return $this->getClient()->guild->listGuildMembers([
'guild.id' => $guildId,
'limit' => 200,
'after' => $after,
Expand All @@ -54,15 +55,15 @@ public function getMembersInGuild(int $guildId, int $after = null): array
*/
public function getRolesInGuild(int $guildId): array
{
return $this->getClient($this->botToken, self::TOKEN_TYPE_BOT)->guild->getGuildRoles([
return $this->getClient()->guild->getGuildRoles([
'guild.id' => $guildId,
'limit' => 100,
]);
}

public function sendMessage(int $userId, string $message): void
{
$client = $this->getClient($this->botToken, self::TOKEN_TYPE_BOT);
$client = $this->getClient();

$channel = $client->user->createDm([
'recipient_id' => $userId,
Expand All @@ -74,11 +75,15 @@ public function sendMessage(int $userId, string $message): void
]);
}

private function getClient(string $token, string $tokenType): DiscordClient
private function getClient(): DiscordClient
{
return new DiscordClient([
'token' => $token,
'tokenType' => $tokenType,
]);
if (!($this->client instanceof DiscordClient)) {
$this->client = new DiscordClient([
'token' => $this->botToken,
'tokenType' => self::TOKEN_TYPE_BOT,
]);
}

return $this->client;
}
}