TelegramService.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. class TelegramService
  5. {
  6. private string $api;
  7. public function __construct(?string $token = null)
  8. {
  9. $this->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 = [], bool $usePost = false): array
  20. {
  21. $http = Http::timeout(30);
  22. if ($usePost) {
  23. $response = $http->post($this->api.$method, $params);
  24. } else {
  25. $response = $http->get($this->api.$method.'?'.http_build_query($params));
  26. }
  27. $data = $response->json();
  28. if ($response->ok()) {
  29. return $data;
  30. }
  31. abort(500, '来自 TG 的错误:'.json_encode($data));
  32. }
  33. public function getMe(): array
  34. {
  35. return $this->request('getMe');
  36. }
  37. public function setWebhook(array $config): array
  38. {
  39. return $this->request('setWebhook', $config, true);
  40. }
  41. }