From: Aleksey Filippov Date: Fri, 4 Jul 2025 15:36:22 +0000 (+0300) Subject: [BC-278] Отправка сообщения в Телеграм X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=9dafcb224b35c4b5ffc8c73fb156b0e0cd30c4cd;p=erp24_rep%2Fyii-erp24%2F.git [BC-278] Отправка сообщения в Телеграм --- diff --git a/erp24/actions/infoTable/TestAction.php b/erp24/actions/infoTable/TestAction.php index c662008b..f4b1d990 100644 --- a/erp24/actions/infoTable/TestAction.php +++ b/erp24/actions/infoTable/TestAction.php @@ -41,8 +41,16 @@ class TestAction extends Action "\n\n" . "📢 Проверьте данные!"; - TelegramService::sendTargetStatToTelegramMessage($messageBonuses); + $chats = [ + '337084327', +// '1813871861' + + ]; //Алексей + + foreach ($chats as $chatId) { + TelegramService::sendTargetTestToTelegramDocument($chatId); + } return 'ok'; } } \ No newline at end of file diff --git a/erp24/commands/CronController.php b/erp24/commands/CronController.php index e31cad29..0e18bd74 100644 --- a/erp24/commands/CronController.php +++ b/erp24/commands/CronController.php @@ -4,6 +4,7 @@ namespace yii_app\commands; use app\jobs\SendTelegramMessageJob; +use app\jobs\SendTelegramPromoMessageJob; use app\jobs\SendWhatsappMessageJob; use DateTime; use DateTimeZone; @@ -685,6 +686,40 @@ class CronController extends Controller return ExitCode::OK; } + public function actionSendTelegramPromoMessage() + { + + if (1) { + $toSend = UsersTelegram::find() + ->where(['is_blocked' => 0, 'is_registered' => 1]) + ->select(['phone', 'chat_id']) + ->where(['phone' => '79036571587']) + ->asArray() + ->all(); + + $countTelegramPhones = count($toSend); + $this->stdout( + "Всего в рассылке телеграма {$countTelegramPhones} записей.\n", + BaseConsole::FG_GREEN + ); + + if (!empty($toSend)) { + foreach ($toSend as $telegramUser) { + $messageData = []; + $messageData['chat_id'] = $telegramUser['chat_id']; + $messageData['phone'] = $telegramUser['phone']; + + Yii::$app->queue->push(new SendTelegramPromoMessageJob([ + 'messageData' => $messageData, + ])); + + } + } + } + + return ExitCode::OK; + } + public function actionSendSecondTelegramMessage() { $messagesSettings = UsersMessageManagement::find()->one(); diff --git a/erp24/jobs/SendTelegramPromoMessageJob.php b/erp24/jobs/SendTelegramPromoMessageJob.php new file mode 100644 index 00000000..9a81cf61 --- /dev/null +++ b/erp24/jobs/SendTelegramPromoMessageJob.php @@ -0,0 +1,71 @@ + 1) { + self::$lastResetTime = microtime(true); + self::$messagesSent = 0; + } + + if (self::$messagesSent >= 30) { + $delay = 1 - (microtime(true) - self::$lastResetTime); + if ($delay > 0) { + usleep($delay * 1e6); // Спим оставшееся время + } + self::$lastResetTime = microtime(true); + self::$messagesSent = 0; + } + + $chatId = ($this->messageData)['chat_id']; + $phone = ($this->messageData)['phone']; + $message = ($this->messageData)['message']; + + try { + $result = TelegramService::sendPromoMessageToTelegramDocument($chatId); + + if ($result == "OK") { + try { + $result = TelegramService::saveSentMessageToDB($this->messageData); + //TODO - перенос сюда обновления статусов записей когорт + if ($result) { + Yii::warning("Сообщение успешно сохранено для пользователя с ID {$chatId} телефон {$phone}", 'telegram'); + } else { + Yii::warning("Сообщение не удалось сохранить для пользователя с ID {$chatId} телефон {$phone}", 'telegram'); + } + + } catch (\Exception $e) { + Yii::error( + "Сообщение не удалось сохранить для пользователя ID {$chatId} телефон {$phone}: " . $e->getMessage(), + 'telegram' + ); + } + Yii::warning("Сообщение успешно отправлено пользователю с ID {$chatId} {$result}", 'telegram'); + } else { + Yii::warning("Сообщение не удалось отправить пользователю ID {$chatId} {$result}", 'telegram'); + } + + } catch (\Exception $e) { + Yii::error( + "Сообщение не удалось отправить пользователю ID {$chatId}: " . $e->getMessage(), + 'telegram' + ); + } + + + self::$messagesSent++; + } +} diff --git a/erp24/services/TelegramService.php b/erp24/services/TelegramService.php index 9e3a02d6..fff601b1 100644 --- a/erp24/services/TelegramService.php +++ b/erp24/services/TelegramService.php @@ -102,6 +102,93 @@ class TelegramService } } + public static function sendPromoMessageToTelegramDocument($chatId) + { + if (self::isDevEnv()) { + $botToken = self::TELEGRAM_BOT_DEV; + } else { + $botToken = self::TELEGRAM_BOT_PROD; + } + $apiURL1 = "https://api.telegram.org/bot{$botToken}/sendMediaGroup"; + $apiURL2 = "https://api.telegram.org/bot{$botToken}/sendMessage"; + + $text = 'АКЦИЯ: –20% НА БУКЕТЫ ДНЯ — с 4 по 11 июля 🔥 + +Только 7 дней: Скидка 20% на три стильных букета из нашей летней коллекции!'; + + $pic1Path = curl_file_create( + __DIR__ . '/../web/images/pic_1.jpg', + 'image/jpg', + 'pic_1.jpg' + ); + + $pic2Path = curl_file_create( + __DIR__ . '/../web/images/pic_2.jpg', + 'image/jpg', + 'pic_2.jpg' + ); + + $pic3Path = curl_file_create( + __DIR__ . '/../web/images/pic_3.jpg', + 'image/jpg', + 'pic_3.jpg' + ); + + $result = 'false'; + + if (!empty($chatId)) { + try { + $buttons = self::getTgShortButtons($chatId); + + $arrayQuery1 = [ + 'chat_id' => $chatId, + 'media' => json_encode([ + ['type' => 'photo', 'media' => 'attach://pic_1.jpg', "caption" => $text], + ['type' => 'photo', 'media' => 'attach://pic_2.jpg' ], + ['type' => 'photo', 'media' => 'attach://pic_3.jpg' ], + ]), + 'pic_1.jpg' => $pic1Path, + 'pic_2.jpg' => $pic2Path, + 'pic_3.jpg' => $pic3Path, + ]; + + $ch = curl_init($apiURL1); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $arrayQuery1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HEADER, false); + $res1 = curl_exec($ch); + curl_close($ch); + +// echo $res1; + + $arrayQuery2 = [ + 'chat_id' => $chatId, + "text" => "Выберите действие:", + 'parse_mode' => 'MarkdownV2', + 'reply_markup' => Json::encode([ + "inline_keyboard" => $buttons + ]), + ]; + $ch = curl_init($apiURL2); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $arrayQuery2); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HEADER, false); + $res2 = curl_exec($ch); + curl_close($ch); + +// echo $res2; + + } catch (\Exception $e) { + Yii::error("Ошибка отправки сообщения в Telegram: " . $e->getMessage(), 'telegram'); + } + $result = 'OK'; + } + + return $result; + } + public static function sendMessageToTelegramClient($chatId, $message) { if (self::isDevEnv()) { @@ -178,6 +265,24 @@ class TelegramService ] ]; } + public static function getTgShortButtons($chatId) : array + { + $hash = self::getHashTG($chatId); + + $siteBc24Url = "https://bazacvetov24.ru/"; + $chatBotBc24Url = 'https://chatbot.bazacvetov24.ru'; + + $linkAppStore = $chatBotBc24Url . "/bot/telegram?hash=$hash&start=store"; + $linkAppEvents = $chatBotBc24Url . "/bot/telegram?hash=$hash&start=promo.1000"; + $linkAppBalance = $chatBotBc24Url . "/bot/telegram?hash=$hash"; + + return [ + [ + ['text' => "Адреса магазинов", "web_app" => ['url' => $linkAppStore]], + ['text' => "Заказ на сайте", "url" => $siteBc24Url], + ] + ]; + } // Метод для экранирования символов MarkdownV2 для файла diff --git a/erp24/web/images/pic_1.jpg b/erp24/web/images/pic_1.jpg new file mode 100644 index 00000000..d2e3ad14 Binary files /dev/null and b/erp24/web/images/pic_1.jpg differ diff --git a/erp24/web/images/pic_2.jpg b/erp24/web/images/pic_2.jpg new file mode 100644 index 00000000..26fae9da Binary files /dev/null and b/erp24/web/images/pic_2.jpg differ diff --git a/erp24/web/images/pic_3.jpg b/erp24/web/images/pic_3.jpg new file mode 100644 index 00000000..3ab1771f Binary files /dev/null and b/erp24/web/images/pic_3.jpg differ