SendTelegramGroupMessageJob.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 SendTelegramGroupMessageJob 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( $text, $buttons = [], $image = null ,$isTop = false)
  27. {
  28. $this->text = $text;
  29. $this->buttons = $buttons;
  30. $this->image = $image;
  31. $this->isTop = $isTop;
  32. }
  33. public function handle()
  34. {
  35. $maxRetries = 3; // 最大重试次数
  36. $retryCount = 0;
  37. while ($retryCount <= $maxRetries) {
  38. try {
  39. BaseService::bettingGroupNotice($this->text, $this->buttons, $this->image, $this->isTop);
  40. return; // 成功则退出
  41. } catch (\Telegram\Bot\Exceptions\TelegramResponseException $e) {
  42. $retryCount++;
  43. // 捕获 Too Many Requests
  44. if (str_contains($e->getMessage(), 'Too Many Requests')) {
  45. preg_match('/retry after (\d+)/', $e->getMessage(), $matches);
  46. $retryAfter = $matches[1] ?? 5;
  47. Log::warning("Telegram 429 限制,等待 {$retryAfter} 秒重试... (尝试 {$retryCount}/{$maxRetries})");
  48. if ($retryCount <= $maxRetries) {
  49. sleep($retryAfter + 1);
  50. continue; // 继续下一次尝试
  51. }
  52. }
  53. // 其他错误或达到最大重试次数
  54. Log::error("Telegram 消息发送失败 (尝试 {$retryCount}/{$maxRetries}): ".$e->getMessage());
  55. // 可以选择记录失败任务或抛出异常
  56. if ($retryCount > $maxRetries) {
  57. Log::error("Telegram 消息发送已达到最大重试次数,任务失败");
  58. // 可以在这里记录到失败队列或发送通知
  59. }
  60. return;
  61. }
  62. }
  63. }
  64. }