TelegramService.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 (!isset($response->ok)) abort(500, '请求失败');
  37. if (!$response->ok) {
  38. abort(500, '来自TG的错误:' . $response->description);
  39. }
  40. return $response;
  41. }
  42. public function sendMessageWithAdmin($message, $isStaff = false)
  43. {
  44. if (!config('v2board.telegram_bot_enable', 0)) return;
  45. $users = User::where(function ($query) use ($isStaff) {
  46. $query->where('is_admin', 1);
  47. if ($isStaff) {
  48. $query->orWhere('is_staff', 1);
  49. }
  50. })
  51. ->where('telegram_id', '!=', NULL)
  52. ->get();
  53. foreach ($users as $user) {
  54. SendTelegramJob::dispatch($user->telegram_id, $message);
  55. }
  56. }
  57. }