TelegramService.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Services;
  3. use App\Jobs\SendTelegramJob;
  4. use \Curl\Curl;
  5. class TelegramService {
  6. protected $api;
  7. public function __construct($token = '')
  8. {
  9. $this->api = 'https://api.telegram.org/bot' . config('v2board.telegram_bot_token', $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 Curl();
  32. $curl->get($this->api . $method . '?' . http_build_query($params));
  33. $response = $curl->response;
  34. $curl->close();
  35. if (!$response->ok) {
  36. abort(500, '来自TG的错误:' . $response->description);
  37. }
  38. return $response;
  39. }
  40. public function sendMessageWithAdmin($message)
  41. {
  42. if (!config('v2board.telegram_bot_enable', 0)) return;
  43. $users = User::where('is_admin', 1)
  44. ->where('telegram_id', '!=', NULL)
  45. ->get();
  46. foreach ($users as $user) {
  47. SendTelegramJob::dispatch($user->telegram_id, $message);
  48. }
  49. }
  50. }