SendTelegramMessageJob.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Jobs;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Contracts\Queue\ShouldQueue;
  5. use Illuminate\Foundation\Bus\Dispatchable;
  6. use Illuminate\Queue\InteractsWithQueue;
  7. use Illuminate\Queue\SerializesModels;
  8. use Telegram\Bot\Api;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Services\BaseService;
  11. use DragonCode\PrettyArray\Services\Formatters\Base;
  12. class SendTelegramMessageJob implements ShouldQueue
  13. {
  14. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  15. public $chatId;
  16. public $text;
  17. public $buttons;
  18. public $image;
  19. public $isTop;
  20. /**
  21. * @param string $chatId
  22. * @param string $text
  23. * @param array $buttons
  24. * @param string|null $image
  25. */
  26. public function __construct($chatId, $text, $buttons = [], $image = null ,$isTop = false)
  27. {
  28. $this->chatId = $chatId;
  29. $this->text = $text;
  30. $this->buttons = $buttons;
  31. $this->image = $image;
  32. $this->isTop = $isTop;
  33. }
  34. public function handle()
  35. {
  36. try {
  37. BaseService::sendMessage($this->chatId ,$this->text, $this->buttons, $this->image);
  38. } catch (\Telegram\Bot\Exceptions\TelegramResponseException $e) {
  39. // 捕获 Too Many Requests
  40. if (str_contains($e->getMessage(), 'Too Many Requests')) {
  41. preg_match('/retry after (\d+)/', $e->getMessage(), $matches);
  42. $retryAfter = $matches[1] ?? 5;
  43. Log::warning("Telegram 429 限制,等待 {$retryAfter} 秒重试...");
  44. sleep($retryAfter + 1);
  45. // 重试
  46. $this->handle();
  47. } else {
  48. Log::error('Telegram 消息发送失败: '.$e->getMessage());
  49. }
  50. }
  51. }
  52. }