TelegramService.php 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. class TelegramService
  5. {
  6. private $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 = '')
  12. {
  13. $this->request('sendMessage', [
  14. 'chat_id' => $chatId,
  15. 'text' => $text,
  16. 'parse_mode' => $parseMode,
  17. ]);
  18. }
  19. public function getMe()
  20. {
  21. return $this->request('getMe');
  22. }
  23. public function setWebhook(string $url)
  24. {
  25. return $this->request('setWebhook', ['url' => $url]);
  26. }
  27. private function request(string $method, array $params = [])
  28. {
  29. $response = Http::get($this->api.$method.'?'.http_build_query($params));
  30. if (! $response->ok()) {
  31. abort(500, '来自TG的错误:'.$response->json());
  32. }
  33. return $response->json();
  34. }
  35. }