]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
[BC-278] Отправка сообщения в Телеграм
authorAleksey Filippov <Aleksey.Filippov@erp-flowers.ru>
Fri, 4 Jul 2025 15:36:22 +0000 (18:36 +0300)
committerAleksey Filippov <Aleksey.Filippov@erp-flowers.ru>
Fri, 4 Jul 2025 15:36:22 +0000 (18:36 +0300)
erp24/actions/infoTable/TestAction.php
erp24/commands/CronController.php
erp24/jobs/SendTelegramPromoMessageJob.php [new file with mode: 0644]
erp24/services/TelegramService.php
erp24/web/images/pic_1.jpg [new file with mode: 0644]
erp24/web/images/pic_2.jpg [new file with mode: 0644]
erp24/web/images/pic_3.jpg [new file with mode: 0644]

index c662008b72fabdb17f38a7059624b6741fa6364f..f4b1d99067819770b659f15e715fa16f1fba8568 100644 (file)
@@ -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
index e31cad29c36f8fee7d620fd28f764fceab53dbdb..0e18bd74af31d8bf8998128cdfc9ea8979114908 100644 (file)
@@ -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 (file)
index 0000000..9a81cf6
--- /dev/null
@@ -0,0 +1,71 @@
+<?php
+
+namespace app\jobs;
+
+
+use Yii;
+use yii\queue\JobInterface;
+use yii_app\services\TelegramService;
+
+class SendTelegramPromoMessageJob extends \yii\base\BaseObject implements JobInterface
+{
+    public $messageData;
+
+    public static $messagesSent = 0;
+    public static $lastResetTime;
+
+    public function execute($queue)
+    {
+        if (!self::$lastResetTime || (microtime(true) - self::$lastResetTime) > 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++;
+    }
+}
index 9e3a02d6c04281a9259ddec7d8c30e7fdadccd2a..fff601b182356ec48e660b200498c381e829aef6 100644 (file)
@@ -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 (file)
index 0000000..d2e3ad1
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 (file)
index 0000000..26fae9d
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 (file)
index 0000000..3ab1771
Binary files /dev/null and b/erp24/web/images/pic_3.jpg differ