12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- <?php
- namespace app\Types;
- use app\Exceptions\InvalidRequestException;
- use app\Exceptions\InvalidWebhookMessageException;
- use app\Hajeebtok;
- class WebhookMessage
- {
- public private(set) ?string $url;
- public private(set) ?array $embeds;
- public private(set) ?string $content;
- public private(set) ?string $username;
- public private(set) ?string $avatar_url;
- public function __construct(?string $url=null)
- {
- if(empty($url)) $this->url = Hajeebtok::$Config->GetByDotKey("Instance.DiscordWebhookURL");
- else $this->url = $url;
- }
- public function SetAvatarURL(string $avatar_url): void {
- $this->avatar_url = $avatar_url;
- }
- public function SetUsername(string $username): void {
- $this->username = $username;
- }
- public function AddEmbed(array $embed): void {
- $this->embeds[] = $embed;
- }
- public function SetContent(string $content): void {
- $this->content = $content;
- }
- public function Send(): void {
- $data = [];
- if(!empty($this->username)) $data["username"] = $this->username;
- if(!empty($this->avatar_url)) $data["avatar_url"] = $this->avatar_url;
- if(!empty($this->embeds)) $data["embeds"] = $this->embeds;
- if(!empty($this->content)) $data["content"] = $this->content;
- if(empty($this->embeds) && empty($this->content)) throw new InvalidWebhookMessageException(0, 400);
- $this->PostRequest($this->url, $data);
- }
- public static function postRequest(string $url, array $payload): string
- {
- $ch = curl_init($url);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json',
- 'Content-Length: ' . strlen(json_encode($payload)),
- ]);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- $response = curl_exec($ch);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error) {
- throw new \Exception("Curl error: " . $error);
- }
- return $response;
- }
- }
|