TelegramService.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 approveChatJoinRequest(int $chatId, int $userId)
  25. {
  26. $this->request('approveChatJoinRequest', [
  27. 'chat_id' => $chatId,
  28. 'user_id' => $userId
  29. ]);
  30. }
  31. public function declineChatJoinRequest(int $chatId, int $userId)
  32. {
  33. $this->request('declineChatJoinRequest', [
  34. 'chat_id' => $chatId,
  35. 'user_id' => $userId
  36. ]);
  37. }
  38. public function getMe()
  39. {
  40. return $this->request('getMe');
  41. }
  42. public function setWebhook(string $url)
  43. {
  44. return $this->request('setWebhook', [
  45. 'url' => $url
  46. ]);
  47. }
  48. private function request(string $method, array $params = [])
  49. {
  50. $curl = new Curl();
  51. $curl->get($this->api . $method . '?' . http_build_query($params));
  52. $response = $curl->response;
  53. $curl->close();
  54. if (!isset($response->ok)) abort(500, '请求失败');
  55. if (!$response->ok) {
  56. abort(500, '来自TG的错误:' . $response->description);
  57. }
  58. return $response;
  59. }
  60. public function sendMessageWithAdmin($message, $isStaff = false)
  61. {
  62. if (!config('v2board.telegram_bot_enable', 0)) return;
  63. $users = User::where(function ($query) use ($isStaff) {
  64. $query->where('is_admin', 1);
  65. if ($isStaff) {
  66. $query->orWhere('is_staff', 1);
  67. }
  68. })
  69. ->where('telegram_id', '!=', NULL)
  70. ->get();
  71. foreach ($users as $user) {
  72. SendTelegramJob::dispatch($user->telegram_id, $message);
  73. }
  74. }
  75. }