WebhookMessage.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace app\Types;
  3. use app\Exceptions\InvalidRequestException;
  4. use app\Exceptions\InvalidWebhookMessageException;
  5. use app\Hajeebtok;
  6. class WebhookMessage
  7. {
  8. public private(set) ?string $url;
  9. public private(set) ?array $embeds;
  10. public private(set) ?string $content;
  11. public private(set) ?string $username;
  12. public private(set) ?string $avatar_url;
  13. public function __construct(?string $url=null)
  14. {
  15. if(empty($url)) $this->url = Hajeebtok::$Config->GetByDotKey("Instance.DiscordWebhookURL");
  16. else $this->url = $url;
  17. }
  18. public function SetAvatarURL(string $avatar_url): void {
  19. $this->avatar_url = $avatar_url;
  20. }
  21. public function SetUsername(string $username): void {
  22. $this->username = $username;
  23. }
  24. public function AddEmbed(array $embed): void {
  25. $this->embeds[] = $embed;
  26. }
  27. public function SetContent(string $content): void {
  28. $this->content = $content;
  29. }
  30. public function Send(): void {
  31. $data = [];
  32. if(!empty($this->username)) $data["username"] = $this->username;
  33. if(!empty($this->avatar_url)) $data["avatar_url"] = $this->avatar_url;
  34. if(!empty($this->embeds)) $data["embeds"] = $this->embeds;
  35. if(!empty($this->content)) $data["content"] = $this->content;
  36. if(empty($this->embeds) && empty($this->content)) throw new InvalidWebhookMessageException(0, 400);
  37. $this->PostRequest($this->url, $data);
  38. }
  39. public static function postRequest(string $url, array $payload): string
  40. {
  41. $ch = curl_init($url);
  42. curl_setopt($ch, CURLOPT_POST, true);
  43. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
  44. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  45. 'Content-Type: application/json',
  46. 'Content-Length: ' . strlen(json_encode($payload)),
  47. ]);
  48. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  49. $response = curl_exec($ch);
  50. $error = curl_error($ch);
  51. curl_close($ch);
  52. if ($error) {
  53. throw new \Exception("Curl error: " . $error);
  54. }
  55. return $response;
  56. }
  57. }