TelegramService.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace App\Services;
  3. use App\Jobs\SendTelegramJob;
  4. use App\Models\User;
  5. use \Curl\Curl;
  6. class TelegramService {
  7. protected $api;
  8. public function __construct($token = '')
  9. {
  10. $this->api = 'https://api.telegram.org/bot' . config('v2board.telegram_bot_token', $token) . '/';
  11. }
  12. public function sendMessage(int $chatId, string $text, string $parseMode = '')
  13. {
  14. $this->request('sendMessage', [
  15. 'chat_id' => $chatId,
  16. 'text' => $text,
  17. 'parse_mode' => $parseMode
  18. ]);
  19. }
  20. public function getMe()
  21. {
  22. return $this->request('getMe');
  23. }
  24. public function setWebhook(string $url)
  25. {
  26. return $this->request('setWebhook', [
  27. 'url' => $url
  28. ]);
  29. }
  30. private function request(string $method, array $params = [])
  31. {
  32. $curl = new Curl();
  33. $curl->get($this->api . $method . '?' . http_build_query($params));
  34. $response = $curl->response;
  35. $curl->close();
  36. if (!$response->ok) {
  37. abort(500, '来自TG的错误:' . $response->description);
  38. }
  39. return $response;
  40. }
  41. public function sendMessageWithAdmin($message)
  42. {
  43. if (!config('v2board.telegram_bot_enable', 0)) return;
  44. $users = User::where(function ($query) {
  45. $query->where('is_admin', 1)
  46. ->orWhere('is_staff', 1);
  47. })
  48. ->where('telegram_id', '!=', NULL)
  49. ->get();
  50. foreach ($users as $user) {
  51. SendTelegramJob::dispatch($user->telegram_id, $message);
  52. }
  53. }
  54. }