Files
chatroom/app/Jobs/SendWechatBotMessage.php

80 lines
2.0 KiB
PHP
Raw Normal View History

<?php
/**
* 文件功能:异步发送微信机器人消息任务
*
* @author ChatRoom Laravel
*
* @version 1.0.0
*/
namespace App\Jobs;
use App\Models\SysParam;
use App\Services\WechatBot\WechatBotApiService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class SendWechatBotMessage implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* @var string 目标 wxid 群组 ID (@chatroom)
*/
protected string $target;
/**
* @var string 要发送的消息内容
*/
protected string $message;
/**
* 队列任务构造函数
*
* @param string $target 目标用户或群聊
* @param string $message 正文内容
*/
public function __construct(string $target, string $message)
{
$this->target = $target;
$this->message = $message;
}
/**
* 执行任务
*/
public function handle(WechatBotApiService $apiService): void
{
if (empty($this->target)) {
Log::warning('WechatBot: Target is empty, skipping message dispatch.');
return;
}
$params = SysParam::where('alias', 'wechat_bot_config')->first();
if ($params && ! empty($params->body)) {
$config = json_decode($params->body, true);
$isEnabled = $config['global_enabled'] ?? false;
if (! $isEnabled) {
return; // 全局未开启,直接抛弃不发
}
}
try {
$apiService->sendTextMessage($this->target, $this->message);
} catch (\Exception $e) {
Log::error('WechatBot: Failed to send message in queue', [
'target' => $this->target,
'message' => $this->message,
'error' => $e->getMessage(),
]);
}
}
}