public function SendMessageGroup(Request $req) { $alldata = $req->all(); $phone =…
- User
public function SendMessageGroup(Request req) { alldata = phone = sessionDB = Session::where('phone', token = $sessionDB->token;
- Assistant
public function SendMessageGroup(Request req) { alldata = phone = sessionDB = Session::where('phone', token = $sessionDB->token;
$tophone = $req->toPhone;
Log::info($alldata);
$data = [
"phone"=>$tophone,
"message"=> $req->msg,
"apiToken" => $req->apiToken,
"countryCode" => $req->country_code,
];
$res = Http::withOptions(['verify' => false])->withHeaders(['Authorization' => "Bearer $token"])->post("https://whatsapp.habib.cloud/api/$phone/send-message/", $data);
if ($res->successful())
{
Log::info($res->json());
Log::info("success");
$newmsg = new savemsgs();
$newmsg->created_at = Carbon::now();
$newmsg->phone = $phone;
$newmsg->fromphone = $data['phone'];
$newmsg->message = $data['message'];
$newmsg->save();
$createdat = MessageDate::first();
if ($createdat){
$createdat = $newmsg->created_at;
$createdat->save();
}
else{
$createdat = new MessageDate();
$createdat->created_atdate = $newmsg->created_at;
$createdat->save();
}
}
else
{
Log::info($res->json());
Log::info("unsuccess");
}
} make it if a other request got sent then it will check if time in the $createdat variable as been passed or no if has been passed it executes the request right way if not then it will execute it when the time gets passed which is 35 seconds
To implement a mechanism that ensures messages are sent only if 35 seconds have passed since the last message, you can leverage Laravel's Job Queues. This approach allows you to handle rate limiting effectively without blocking the main thread or causing delays in HTTP responses.
Here's a step-by-step guide to modifying your SendMessageGroup method to achieve this:
SendMessageGroup Method to Use the Jobcreated_at TimestampFirst, create a job that will handle the actual sending of the message. This job can be dispatched immediately or after a delay based on your requirement.
Run the following Artisan command to create a new job:
php artisan make:job SendMessageJob
This will create a new file at app/Jobs/SendMessageJob.php. Modify it as follows:
<?php
namespace App\Jobs;
use App\Models\MessageDate;
use App\Models\savemsgs;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Client\Response;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
class SendMessageJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $data;
public $phone;
public $token;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($data, $phone, $token)
{
$this->data = $data;
$this->phone = $phone;
$this->token = $token;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
try {
$res = Http::withOptions(['verify' => false])
->withHeaders(['Authorization' => "Bearer {$this->token}"])
->post("https://whatsapp.habib.cloud/api/{$this->phone}/send-message/", $this->data);
if ($res->successful()) {
Log::info($res->json());
Log::info("success");
// Save the message
$newmsg = new savemsgs();
$newmsg->created_at = Carbon::now();
$newmsg->phone = $this->phone;
$newmsg->fromphone = $this->data['phone'];
$newmsg->message = $this->data['message'];
$newmsg->save();
// Update MessageDate
$createdat = MessageDate::first();
if ($createdat) {
$createdat->created_atdate = $newmsg->created_at;
$createdat->save();
} else {
$createdat = new MessageDate();
$createdat->created_atdate = $newmsg->created_at;
$createdat->save();
}
} else {
Log::info($res->json());
Log::info("unsuccess");
}
} catch (\Exception $e) {
Log::error("Error sending message: " . $e->getMessage());
// Optionally, you can retry the job or handle the exception as needed
}
}
}
SendMessageGroup Method to Use the JobUpdate your SendMessageGroup method to check the time elapsed since the last message and decide whether to send immediately or delay the sending by 35 seconds.
Here’s the modified SendMessageGroup method:
public function SendMessageGroup(Request $req)
{
$alldata = $req->all();
$phone = $req->phone;
$sessionDB = Session::where('phone', $phone)->first();
if (!$sessionDB) {
Log::error("Session not found for phone: $phone");
return response()->json(['error' => 'Invalid session'], 400);
}
$token = $sessionDB->token;
$tophone = $req->toPhone;
Log::info($alldata);
$data = [
"phone" => $tophone,
"message" => $req->msg,
"apiToken" => $req->apiToken,
"countryCode" => $req->country_code,
];
$createdatRecord = MessageDate::first();
$now = Carbon::now();
$shouldSendImmediately = false;
$delaySeconds = 0;
if ($createdatRecord) {
$lastSentAt = Carbon::parse($createdatRecord->created_atdate);
$diffInSeconds = $now->diffInSeconds($lastSentAt);
if ($diffInSeconds >= 35) {
$shouldSendImmediately = true;
} else {
$delaySeconds = 35 - $diffInSeconds;
}
} else {
// No previous message sent, send immediately
$shouldSendImmediately = true;
}
if ($shouldSendImmediately) {
// Dispatch the job immediately
SendMessageJob::dispatch($data, $phone, $token);
} else {
// Dispatch the job with a delay
SendMessageJob::dispatch($data, $phone, $token)->delay(now()->addSeconds($delaySeconds));
}
return response()->json(['status' => 'Message queued'], 200);
}
Job Creation (SendMessageJob):
ShouldQueue interface to allow Laravel to handle it asynchronously.SendMessageGroup Method:
MessageDate model.>= 35 seconds), dispatches the job immediately.Ensure that your Laravel application is set up to handle queued jobs. Here's how you can do it:
Configure Queue Driver:
In your .env file, set the queue connection. For development purposes, you can use the database driver.
QUEUE_CONNECTION=database
Create the Jobs Table:
Run the migrations to create the necessary tables for the queue.
php artisan queue:table
php artisan migrate
Start the Queue Worker:
To process the queued jobs, run the queue worker. For development, you can use the sync driver which processes jobs immediately, but for production, it's recommended to use a persistent queue worker like redis or database.
php artisan queue:work
Alternatively, you can use the supervisor process manager to keep the queue worker running in the background.
Concurrency Handling: If multiple requests come in rapid succession, ensure that your logic correctly handles the queuing without overlaps.
Multiple Recipients: If toPhone can have multiple recipients, adjust the job and method accordingly to handle bulk sending while respecting the rate limit.
Feedback to Users: You might want to inform users if their messages are queued and provide an estimated time of delivery.
Retry Mechanism: Configure retry logic in the job to handle transient failures when sending messages.
app/Jobs/SendMessageJob.php
<?php
namespace App\Jobs;
use App\Models\MessageDate;
use App\Models\savemsgs;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Client\Response;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
class SendMessageJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $data;
public $phone;
public $token;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($data, $phone, $token)
{
$this->data = $data;
$this->phone = $phone;
$this->token = $token;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
try {
$res = Http::withOptions(['verify' => false])
->withHeaders(['Authorization' => "Bearer {$this->token}"])
->post("https://whatsapp.habib.cloud/api/{$this->phone}/send-message/", $this->data);
if ($res->successful()) {
Log::info($res->json());
Log::info("success");
// Save the message
$newmsg = new savemsgs();
$newmsg->created_at = Carbon::now();
$newmsg->phone = $this->phone;
$newmsg->fromphone = $this->data['phone'];
$newmsg->message = $this->data['message'];
$newmsg->save();
// Update MessageDate
$createdat = MessageDate::first();
if ($createdat) {
$createdat->created_atdate = $newmsg->created_at;
$createdat->save();
} else {
$createdat = new MessageDate();
$createdat->created_atdate = $newmsg->created_at;
$createdat->save();
}
} else {
Log::info($res->json());
Log::info("unsuccess");
}
} catch (\Exception $e) {
Log::error("Error sending message: " . $e->getMessage());
// Optionally, you can retry the job or handle the exception as needed
}
}
}
app/Http/Controllers/YourController.php
<?php
namespace App\Http\Controllers;
use App\Jobs\SendMessageJob;
use App\Models\MessageDate;
use App\Models\savemsgs;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class YourController extends Controller
{
public function SendMessageGroup(Request $req)
{
$alldata = $req->all();
$phone = $req->phone;
$sessionDB = Session::where('phone', $phone)->first();
if (!$sessionDB) {
Log::error("Session not found for phone: $phone");
return response()->json(['error' => 'Invalid session'], 400);
}
$token = $sessionDB->token;
$tophone = $req->toPhone;
Log::info($alldata);
$data = [
"phone" => $tophone,
"message" => $req->msg,
"apiToken" => $req->apiToken,
"countryCode" => $req->country_code,
];
$createdatRecord = MessageDate::first();
$now = Carbon::now();
$shouldSendImmediately = false;
$delaySeconds = 0;
if ($createdatRecord) {
$lastSentAt = Carbon::parse($createdatRecord->created_atdate);
$diffInSeconds = $now->diffInSeconds($lastSentAt);
if ($diffInSeconds >= 35) {
$shouldSendImmediately = true;
} else {
$delaySeconds = 35 - $diffInSeconds;
}
} else {
// No previous message sent, send immediately
$shouldSendImmediately = true;
}
if ($shouldSendImmediately) {
// Dispatch the job immediately
SendMessageJob::dispatch($data, $phone, $token);
} else {
// Dispatch the job with a delay
SendMessageJob::dispatch($data, $phone, $token)->delay(now()->addSeconds($delaySeconds));
}
return response()->json(['status' => 'Message queued'], 200);
}
}
To ensure that the implementation works as expected:
Run the Queue Worker:
php artisan queue:work
Send Multiple Requests:
Use a tool like Postman to send multiple requests to the SendMessageGroup endpoint rapidly and observe the behavior. Check the logs to verify that messages are sent respecting the 35-second interval.
Monitor Delayed Jobs:
Ensure that delayed jobs are processed after the specified delay. Check the database entries in the MessageDate and savemsgs tables to confirm correct timestamps.
Scalability: If your application needs to handle high volumes of messages, consider optimizing the queue configuration and using faster queue drivers like Redis.
Multiple Users: If rate limiting needs to be applied per user or per phone number, ensure that the MessageDate model accounts for this by including identifiers.
Error Notifications: Implement notifications or alerts for failed jobs to allow for timely interventions.
Idempotency: Ensure that sending the same message multiple times doesn't cause unintended side effects, especially when retrying failed jobs.
By following the above steps, you can effectively manage the timing of your message-sending functionality, ensuring that messages are sent only after the specified interval of 35 seconds has passed since the last message.
Not yet included in a published release.