| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace App\Jobs;
- use Illuminate\Bus\Queueable;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Bus\Dispatchable;
- use Illuminate\Queue\InteractsWithQueue;
- use Illuminate\Queue\SerializesModels;
- use Telegram\Bot\Api;
- use Illuminate\Support\Facades\Log;
- use App\Services\BaseService;
- use DragonCode\PrettyArray\Services\Formatters\Base;
- class SendTelegramGroupMessageJob implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
- public $chatId;
- public $text;
- public $buttons;
- public $image;
- public $isTop;
- /**
- * @param string $chatId
- * @param string $text
- * @param array $buttons
- * @param string|null $image
- */
- public function __construct( $text, $buttons = [], $image = null ,$isTop = false)
- {
- $this->text = $text;
- $this->buttons = $buttons;
- $this->image = $image;
- $this->isTop = $isTop;
- }
- public function handle()
- {
- $maxRetries = 3; // 最大重试次数
- $retryCount = 0;
-
- while ($retryCount <= $maxRetries) {
- try {
- BaseService::bettingGroupNotice($this->text, $this->buttons, $this->image, $this->isTop);
- return; // 成功则退出
-
- } catch (\Telegram\Bot\Exceptions\TelegramResponseException $e) {
- $retryCount++;
-
- // 捕获 Too Many Requests
- if (str_contains($e->getMessage(), 'Too Many Requests')) {
- preg_match('/retry after (\d+)/', $e->getMessage(), $matches);
- $retryAfter = $matches[1] ?? 5;
-
- Log::warning("Telegram 429 限制,等待 {$retryAfter} 秒重试... (尝试 {$retryCount}/{$maxRetries})");
-
- if ($retryCount <= $maxRetries) {
- sleep($retryAfter + 1);
- continue; // 继续下一次尝试
- }
- }
-
- // 其他错误或达到最大重试次数
- Log::error("Telegram 消息发送失败 (尝试 {$retryCount}/{$maxRetries}): ".$e->getMessage());
-
- // 可以选择记录失败任务或抛出异常
- if ($retryCount > $maxRetries) {
- Log::error("Telegram 消息发送已达到最大重试次数,任务失败");
- // 可以在这里记录到失败队列或发送通知
- }
-
- return;
- }
- }
- }
- }
|