TelegramService.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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, $isStaff = false)
  42. {
  43. if (!config('v2board.telegram_bot_enable', 0)) return;
  44. $users = User::where(function ($query) use ($isStaff) {
  45. $query->where('is_admin', 1);
  46. if ($isStaff) {
  47. $query->orWhere('is_staff', 1);
  48. }
  49. })
  50. ->where('telegram_id', '!=', NULL)
  51. ->get();
  52. foreach ($users as $user) {
  53. SendTelegramJob::dispatch($user->telegram_id, $message);
  54. }
  55. }
  56. }