VacancyChannel.php 2.51 KB
<?php

namespace App\Components\Integrations\Telegram;

use App\Models\Ad_employer;
use Str;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramSDKException;
use Telegram\Bot\Laravel\Facades\Telegram;
use Telegram\Bot\Objects\Update;

class VacancyChannel
{
    const REKAMORE_CHANNEL_ID = 'REKAMORE_CHANNEL_ID';

    private Api $botApi;

    public function __construct()
    {
        $this->botApi = Telegram::bot('channel_bot');
    }

    /**
     * @throws TelegramSDKException
     */
    private function getChatId()
    {
        $updates = $this->botApi->getUpdates();
        /** @var Update $update*/
        $chatId = null;
        foreach ($updates as $update) {
            if ($update->message?->chat->title === config('services.telegram.chat_title')) {
                $chatId = $update->message->chat->id;
                \Cache::set(self::REKAMORE_CHANNEL_ID, $chatId, null);
                break;
            } elseif ($update->channel_post?->chat->title === config('services.telegram.chat_title')) {
                $chatId = $update->channel_post->chat->id;
                \Cache::set(self::REKAMORE_CHANNEL_ID, $chatId, null);
                break;
            }
        }

        if ($chatId === null) {
            $chatId = \Cache::get(self::REKAMORE_CHANNEL_ID);
            if ($chatId === null) {
                throw new TelegramSDKException('Cant locate group chat id');
            }
        }

        return $chatId;
    }

    /**
     * @throws TelegramSDKException
     */
    public function sendVacancy(Ad_employer $vacancy): void
    {
        $chatId = $this->getChatId();

        $text = $this->formatTextFotTelegram($vacancy->text);

        $this->botApi->sendMessage([
            'chat_id' => $chatId,
            'text' => $text,
            'disable_web_page_preview' => true,
            'parse_mode' => 'HTML'
        ]);
    }

    public function formatTextFotTelegram(string $text): string
    {
        $text = str_ireplace('<p>', '', $text);
        $text = str_ireplace('</p>', '', $text);

        $text = str_ireplace('<br>', '', $text);
        $text = str_ireplace('<br />', '', $text);

        $text = str_ireplace('<h3>', '<b>', $text);
        $text = str_ireplace('</h3>', '</b>', $text);

        $text = str_ireplace('<strong>', '<b>', $text);
        $text = str_ireplace('</strong>', '</b>', $text);

        $text = str_ireplace('<em>', '<i>', $text);
        $text = str_ireplace('</em>', '</i>', $text);

        return html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    }
}