TelegramService.php 1.8 KB

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