use app\jobs\SendTelegramMessageJob;
+use app\jobs\SendTelegramPromoMessageJob;
use app\jobs\SendWhatsappMessageJob;
use DateTime;
use DateTimeZone;
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();
--- /dev/null
+<?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++;
+ }
+}
}
}
+ 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()) {
]
];
}
+ 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 для файла