TelegramService.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. class TelegramService
  5. {
  6. protected $api;
  7. public function __construct($token = '')
  8. {
  9. $this->api = 'https://api.telegram.org/bot'.($token ? $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', [
  26. 'url' => $url,
  27. ]);
  28. }
  29. private function request(string $method, array $params = [])
  30. {
  31. $curl = new Http();
  32. $response = Http::get($this->api.$method.'?'.http_build_query($params));
  33. if (! $response->ok()) {
  34. abort(500, '来自TG的错误:'.$response->json());
  35. }
  36. return $response->json();
  37. }
  38. }