TelegramService.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Services;
  3. use \Curl\Curl;
  4. class TelegramService {
  5. protected $api;
  6. public function __construct($token = '')
  7. {
  8. $this->api = 'http://dev.v2board.com/bot' . config('v2board.telegram_bot_token', $token) . '/';
  9. }
  10. public function sendMessage(int $chatId, string $text, string $parseMode = '')
  11. {
  12. $this->request('sendMessage', [
  13. 'chat_id' => $chatId,
  14. 'text' => $text,
  15. 'parse_mode' => $parseMode
  16. ]);
  17. }
  18. public function getMe()
  19. {
  20. return $this->request('getMe');
  21. }
  22. public function setWebhook(string $url)
  23. {
  24. return $this->request('setWebhook', [
  25. 'url' => $url
  26. ]);
  27. }
  28. private function request(string $method, array $params = [])
  29. {
  30. $curl = new Curl();
  31. $curl->get($this->api . $method . '?' . http_build_query($params));
  32. $response = $curl->response;
  33. $curl->close();
  34. if (!$response->ok) {
  35. abort(500, '来自TG的错误:' . $response->description);
  36. }
  37. return $response;
  38. }
  39. }