TelegramService.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. class TelegramService
  5. {
  6. private static string $api;
  7. public function __construct(string $token = null)
  8. {
  9. self::$api = 'https://api.telegram.org/bot'.($token ?? sysConfig('telegram_token')).'/';
  10. }
  11. public function sendMessage(int $chatId, string $text, string $parseMode = ''): array
  12. {
  13. return $this->request('sendMessage', [
  14. 'chat_id' => $chatId,
  15. 'text' => $text,
  16. 'parse_mode' => $parseMode,
  17. ]);
  18. }
  19. private function request(string $method, array $params = []): array
  20. {
  21. $response = Http::get(self::$api.$method.'?'.http_build_query($params));
  22. $data = $response->json();
  23. if ($response->ok()) {
  24. return $data;
  25. }
  26. abort(500, "来自TG的错误:$data");
  27. }
  28. public function getMe(): array
  29. {
  30. return $this->request('getMe');
  31. }
  32. public function setWebhook(string $url): array
  33. {
  34. return $this->request('setWebhook', ['url' => $url]);
  35. }
  36. }