coolify/app/Jobs/SendMessageToTelegramJob.php

77 lines
2.3 KiB
PHP
Raw Normal View History

2023-09-06 14:31:38 +02:00
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
2023-09-14 10:12:44 +02:00
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
2023-09-06 14:31:38 +02:00
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
2023-09-15 11:19:36 +02:00
use Illuminate\Support\Str;
2023-09-06 14:31:38 +02:00
2024-06-10 22:43:34 +02:00
class SendMessageToTelegramJob implements ShouldBeEncrypted, ShouldQueue
2023-09-06 14:31:38 +02:00
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 5;
/**
* The maximum number of unhandled exceptions to allow before failing.
*/
public int $maxExceptions = 3;
public function __construct(
public string $text,
public array $buttons,
public string $token,
public string $chatId,
2023-09-08 14:15:28 +02:00
public ?string $topicId = null,
2024-06-19 08:59:46 +02:00
) {}
2023-09-06 14:31:38 +02:00
/**
* Execute the job.
*/
public function handle(): void
{
2024-06-10 22:43:34 +02:00
$url = 'https://api.telegram.org/bot'.$this->token.'/sendMessage';
2023-09-06 14:31:38 +02:00
$inlineButtons = [];
2024-06-10 22:43:34 +02:00
if (! empty($this->buttons)) {
2023-09-06 14:31:38 +02:00
foreach ($this->buttons as $button) {
$buttonUrl = data_get($button, 'url');
2023-11-06 10:49:35 +01:00
$text = data_get($button, 'text', 'Click here');
2023-09-06 14:31:38 +02:00
if ($buttonUrl && Str::contains($buttonUrl, 'http://localhost')) {
$buttonUrl = str_replace('http://localhost', config('app.url'), $buttonUrl);
}
$inlineButtons[] = [
2023-11-06 10:49:35 +01:00
'text' => $text,
2023-09-06 14:31:38 +02:00
'url' => $buttonUrl,
];
}
}
$payload = [
2024-04-29 09:38:45 +02:00
// 'parse_mode' => 'markdown',
2023-09-06 14:31:38 +02:00
'reply_markup' => json_encode([
'inline_keyboard' => [
[...$inlineButtons],
],
]),
'chat_id' => $this->chatId,
'text' => $this->text,
];
2023-09-08 14:15:28 +02:00
if ($this->topicId) {
$payload['message_thread_id'] = $this->topicId;
}
2023-09-06 14:31:38 +02:00
$response = Http::post($url, $payload);
if ($response->failed()) {
2024-06-10 22:43:34 +02:00
throw new \Exception('Telegram notification failed with '.$response->status().' status code.'.$response->body());
2023-09-06 14:31:38 +02:00
}
}
}