Орла
Области
Компаний
Пользователи
Галерея
Фиксированные новости
Орла
Отзывы о фирмах
Тарифы
Пользователи
Области
Банкоматы
Торговые точки
Доска объявлений
Курсы валют
Скидки
организации Орла
организации области
товары
сайты
сайты Орел
Данные
Разделы
Поиск
Поиск запросы
Статистика
Показы каталога организаций
Статистика клиенты
Пользователи
Сайты
Управление сайтом
Анкета
Аптеки
Афиша
Афиша новая
Баннеры
Бизнес >
Викторина
Голосование
Гость на сайте
Истории
Календарь событий
Каталоги >
Конкурс красоты
Конкурс аудио
Консультации
Меню
Новое на сайте
Новости >
Организации >
Программа ТВ
Публикации
Разделы сайта
Рассылка
Рестораны
Секрет фирмы >
Сервисы >
Ссылки
Тесты
Файловый менеджер
Форум
Фотогалерея
Обратная связь
Недвижимость
Новый год
Тексты
Пользователи
Юридический рейтинг
Отзывы на товары
Бан пользователей
Жалобы
Новые тесты
Коронавирус
Файловый менеджер
Имя файла
TelegramPosting.php
Содержимое
<?php namespace app\core\social\telegram; use App; use app\core\social\Posting; class TelegramPosting extends Posting { private $title = ''; private $lastError = ''; private $lastPhotoError = ''; const DEFAULT_BOT_TOKEN = '295195669:AAG_yTOj47Cp40Rs3sKfqqhtFFwCIBVKB7E'; const DEFAULT_CHAT_ID = '-1001111826297'; const MAX_CAPTION_LENGTH = 1024; const MAX_MESSAGE_LENGTH = 4096; public static function instance() { return new static(); } public function title($title) { $this->title = $title; return $this; } private function getTelegramConfig() { $config = []; if (isset(App::$config['posting']['telegram']) && is_array(App::$config['posting']['telegram'])) { $config = App::$config['posting']['telegram']; } return [ 'bot_token' => isset($config['bot_token']) ? $config['bot_token'] : self::DEFAULT_BOT_TOKEN, 'chat_id' => isset($config['chat_id']) ? $config['chat_id'] : self::DEFAULT_CHAT_ID, 'proxy_host' => isset($config['proxy_host']) ? $config['proxy_host'] : '77.105.139.146', 'proxy_port' => isset($config['proxy_port']) ? $config['proxy_port'] : 8888, 'proxy_auth' => isset($config['proxy_auth']) ? $config['proxy_auth'] : 'botuser:lBRaRK7S69e3Vztf', ]; } private function cutCaption($text) { if (mb_strlen($text, 'UTF-8') <= self::MAX_CAPTION_LENGTH) { return $text; } return mb_substr($text, 0, self::MAX_CAPTION_LENGTH - 3, 'UTF-8') . '...'; } private function cutMessage($text) { if (mb_strlen($text, 'UTF-8') <= self::MAX_MESSAGE_LENGTH) { return $text; } return mb_substr($text, 0, self::MAX_MESSAGE_LENGTH - 3, 'UTF-8') . '...'; } private function sendTelegramRequest($url, array $postFields, $proxyHost = '', $proxyPort = 0, $proxyAuth = '') { $curl = curl_init($url); curl_setopt($curl, CURLOPT_POST, 1); $isMultipart = false; if (isset($postFields['photo']) && is_string($postFields['photo'])) { $photoField = $postFields['photo']; if ($photoField !== '' && $photoField[0] === '@') { $isMultipart = true; } } if ($isMultipart) { if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); } curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields); } else { curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postFields)); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 25); curl_setopt($curl, CURLOPT_TIMEOUT, 60); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); if (!empty($proxyHost)) { curl_setopt($curl, CURLOPT_PROXY, $proxyHost); curl_setopt($curl, CURLOPT_PROXYPORT, (int) $proxyPort); curl_setopt($curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); if (!empty($proxyAuth)) { curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyAuth); } } $response = curl_exec($curl); $curlError = curl_error($curl); $curlErrno = curl_errno($curl); $httpCode = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($curlErrno !== 0 || $response === false || $httpCode !== 200) { $this->lastError = 'curl_errno=' . $curlErrno . '; http=' . $httpCode . '; error=' . $curlError; return false; } $decoded = json_decode($response, true); if (is_array($decoded) && !empty($decoded['ok'])) { return true; } $this->lastError = 'telegram_response=' . $response; return false; } public function send() { if ($this->getLink() == null) { return false; } $telegramConfig = $this->getTelegramConfig(); $apiBase = 'https://api.telegram.org/bot' . $telegramConfig['bot_token'] . '/'; if (mb_strlen($this->title, 'UTF-8') > 140) { $this->title = mb_substr($this->title, 0, 140) . '...'; } $message = $this->getText(); if ($this->getLink() != null) { $message .= ' ' . $this->getLink(); } $photo = isset($this->getImages()[0]) ? $this->getImages()[0] : ''; if (is_string($photo) && $photo !== '' && $photo[0] === '/' && file_exists($photo)) { // Для PHP 5.4 используем legacy upload-нотацию. $photo = '@' . $photo; } $postFields = [ 'chat_id' => $telegramConfig['chat_id'], 'photo' => $photo, 'caption' => $this->cutCaption($message) ]; $sendMessageFields = [ 'chat_id' => $telegramConfig['chat_id'], 'text' => $this->cutMessage($message) ]; $maxAttempts = 3; $retryDelaySeconds = 2; $hasProxy = !empty($telegramConfig['proxy_host']); $this->lastPhotoError = ''; for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) { if ($hasProxy) { // На сервере Telegram доступен только через прокси. if ($this->sendTelegramRequest( $apiBase . 'sendPhoto', $postFields, $telegramConfig['proxy_host'], $telegramConfig['proxy_port'], $telegramConfig['proxy_auth'] )) { if (php_sapi_name() === 'cli') { fwrite(STDERR, "Telegram sendPhoto OK\n"); } return true; } $this->lastPhotoError = $this->lastError; if ($this->sendTelegramRequest( $apiBase . 'sendMessage', $sendMessageFields, $telegramConfig['proxy_host'], $telegramConfig['proxy_port'], $telegramConfig['proxy_auth'] )) { if (php_sapi_name() === 'cli') { fwrite(STDERR, 'Telegram fallback sendMessage used. sendPhoto error: ' . $this->lastPhotoError . "\n"); } return true; } } else { if ($this->sendTelegramRequest($apiBase . 'sendPhoto', $postFields)) { if (php_sapi_name() === 'cli') { fwrite(STDERR, "Telegram sendPhoto OK\n"); } return true; } $this->lastPhotoError = $this->lastError; if ($this->sendTelegramRequest($apiBase . 'sendMessage', $sendMessageFields)) { if (php_sapi_name() === 'cli') { fwrite(STDERR, 'Telegram fallback sendMessage used. sendPhoto error: ' . $this->lastPhotoError . "\n"); } return true; } } if ($attempt < $maxAttempts) { sleep($retryDelaySeconds); } else { if (php_sapi_name() === 'cli' && !empty($this->lastError)) { fwrite(STDERR, 'Telegram send failed: ' . $this->lastError . "\n"); } } } return false; } }
/app/core/social/telegram/
Имя
Дата
Размер
..
2019-02-01
TelegramPosting.php
2026-10-01
8 кб.
TelegramPosting.php~
2022-01-27
2 кб.
posting.log
2026-10-02
7343 кб.
posting.log~
2026-09-07
656 кб.
/app/core/social/telegram
Загрузить файлы
Файл 1
Файл 2
Файл 3