src/Controller/TelegramBotController.php line 142

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Controller\Classes\Telegram;
  4. use App\Entity\Adressen;
  5. use App\Entity\City;
  6. use App\Entity\OrderUkraine;
  7. use App\Entity\User;
  8. use App\Entity\RegistrationStep;
  9. use App\Service\RegistrationHandlerTelegram;
  10. use Borsaco\TelegramBotApiBundle\Service\Bot;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. class TelegramBotController extends AbstractController
  17. {
  18.     public EntityManagerInterface $entityManager;
  19.     public function __construct(EntityManagerInterface $entityManager)
  20.     {
  21.         $this->entityManager $entityManager;
  22.     }
  23.     #[Route('/admin/sendToTelegramUser'name'testDVB2222222')]
  24.     public function sendToTelegramUser(Bot $botEntityManagerInterface $entityManager): Response
  25.     {
  26.         $users $entityManager->getRepository(User::class)->findAll();
  27.         foreach ($users as $user) {
  28.             if($user->getTelegramID()) {
  29.                 $telegramBotFunction = new Telegram($this->entityManager);
  30.                 $orders $entityManager->getRepository(OrderUkraine::class)->findBy(['phoneInGermany'=> $user->getPhoneNumber(), 'statusDelivery' => "У німетчині" ]);
  31.                 if($orders) {
  32.                     $sendMessageHTML "Увага до Вас прямує посилочка з України\n";
  33.                     foreach ($orders as $item) {
  34.                         $trackNumber $item->getTracknumberInGermany();
  35.                         $status $item->getStatusDelivery();
  36.                         $city $item->getCityInGermany();
  37.                         $getFactWeight $item->getFactWeight();
  38.                         $priceToPay $item->priceToPay();
  39.                         $address $entityManager->getRepository(Adressen::class)->findOneBy(['city'=> $item->getCityInGermany()]);
  40.                         $sendMessageHTML .= "━━━━━━━━━━━━━━━━━━━━━━\n";
  41.                         $sendMessageHTML .= "📦 <b>Номер посилки:</b> $trackNumber\n";
  42.                         $sendMessageHTML .= "🔄 <b>Статус:</b> $status\n";
  43.                         $sendMessageHTML .= "🏙️ <b>Місто отримання:</b> $city\n";
  44.                         if($address) {
  45.                             $sendMessageHTML .= "📍 <b>Адресса отримання:</b> $address\n";
  46.                         } else {
  47.                             $sendMessageHTML .= "📍 <b>Адресса отримання:</b> Не вказана\n";
  48.                         }
  49.                         $sendMessageHTML .= "⚖ <b>Фактична вага:</b> $getFactWeight кг\n";
  50.                         $sendMessageHTML .= "💰 <b>Ціна до сплати:</b> $priceToPay грн\n";
  51.                         $sendMessageHTML .= "━━━━━━━━━━━━━━━━━━━━━━\n";
  52.                     }
  53.                     $telegramBotFunction->sendMessageHTML($user->getTelegramID(), $sendMessageHTML);
  54.                 } else {
  55.                     $telegramBotFunction->sendMessage($user->getTelegramID(), "📦 У вас немає посилок.");
  56.                 }
  57.             }
  58.         }
  59.         return $this->json('Empty');
  60.     }
  61.     #[Route('/testDVB'name'testDVB')]
  62.     public function index2(Bot $botEntityManagerInterface $entityManager): Response
  63.     {
  64.         $user $this->entityManager->getRepository(User::class)->findOneBy(['phoneNumber' => 666666]);
  65.         if($user) {
  66.             $user->setPhoneNumber("666666");
  67.             $this->entityManager->flush();
  68.             return $this->json('t');
  69.         }
  70.         return $this->json('f');
  71.     }
  72.     #[Route('/testDVB2'name'testDVB2')]
  73.     public function index22(Bot $botEntityManagerInterface $entityManager): Response
  74.     {
  75.         $cityArray $entityManager->getRepository(City::class)->findAll();
  76.         $buttons = [];
  77.         foreach ($cityArray as $city) {
  78.             $buttons[] = [
  79.                 'text' => $city->getName() // Текст кнопки, отправляемый как сообщение
  80.             ];
  81.         }
  82. // Формируем клавиатуру с кнопками городов
  83.         $keyboard = [
  84.             'keyboard' => array_chunk(array_map(function ($button) {
  85.                 return $button// Добавляем каждую кнопку
  86.             }, $buttons), 3), // Разбиваем кнопки на строки по 3 в каждой
  87.             'resize_keyboard' => true,
  88.             'one_time_keyboard' => true
  89.         ];
  90.         $keyboard json_encode($keyboard);
  91.         return $this->json($keyboard);
  92.     }
  93.     #[Route('/index222'name'index222')]
  94.     public function index222(Bot $botEntityManagerInterface $entityManager): Response
  95.     {
  96.        // $userOb = $this->entityManager->getRepository(User::class)->findOneBy(['telegramID' => $userChat]);
  97.         $userOb $entityManager->getRepository(User::class)->findOneBy(['telegramID' => "295940824"]);
  98.         $orders $this->entityManager->getRepository(OrderUkraine::class)->findBy(['phoneInGermany' => $userOb->getPhoneNumber()]);
  99.         $telegramBotFunction = new Telegram($this->entityManager);
  100.         if($orders) {
  101.             $sendMessageHTML "";
  102.             foreach ($orders as $item) {
  103.                 $trackNumber $item->getTracknumberInGermany();
  104.                 $status $item->getStatusDelivery();
  105.                 $sendMessageHTML .= "---------------------------\n";
  106.                 $sendMessageHTML .= "<b>Номер:</b> $trackNumber\n";
  107.                 $sendMessageHTML .= "<b>Статус:</b> $status\n";
  108.                 $sendMessageHTML .= "---------------------------\n";
  109.             }
  110.             $telegramBotFunction->sendMessageHTML("295940824"$sendMessageHTML);
  111.         } else {
  112.             $telegramBotFunction->sendMessage("295940824""📦 У вас немає посилок.");
  113.         }
  114.         return $this->json("Empty");
  115.     }
  116.     #[Route('/telegram/bot'name'app_telegram_bot')]
  117.     public function index(Bot $botEntityManagerInterface $entityManagerUserPasswordHasherInterface $userPasswordHasher): Response
  118.     {
  119.         file_put_contents('log.txt'"Метод index вызван\n"FILE_APPEND);
  120.         $telegramBotFunction = new Telegram($entityManager);
  121.         file_put_contents('log.txt'" 111 Метод index вызван\n"FILE_APPEND);
  122.         $firstBot $bot->getBot('first');
  123.         $updateArray $firstBot->getWebhookUpdate();
  124.         file_put_contents('log.txt'"Метод getWebhookUpdate вызван\n"FILE_APPEND);
  125.         $webhookInfo $firstBot->getWebhookInfo();
  126.         file_put_contents('log.txt'"Метод getWebhookInfo вызван\n"FILE_APPEND);
  127.         file_put_contents('log.txt'"Webhook Info: " json_encode($webhookInfoJSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE) . "\n"FILE_APPEND);
  128.         file_put_contents('log.txt'"updateArray Info: " json_encode($updateArrayJSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE) . "\n"FILE_APPEND);
  129.         if ($updateArray->getMessage()) {
  130.             file_put_contents('log.txt'"Получено сообщение: " json_encode($updateArrayJSON_PRETTY_PRINT JSON_UNESCAPED_UNICODE) . "\n"FILE_APPEND);
  131.             $textRequest $updateArray->getMessage()->get('text');
  132.             $userChat $updateArray->getMessage()->getChat()->get('id');
  133.             file_put_contents('log.txt'"Получено сообщение: '$textRequest' от пользователя: $userChat\n"FILE_APPEND);
  134.             $userOb $entityManager->getRepository(User::class)->findOneBy(['telegramID' => $userChat]);
  135.             $registrationStep $entityManager->getRepository(RegistrationStep::class)->findOneBy(['chatId' => $userChat]);
  136.             // Лог о состоянии пользователя и шага регистрации
  137.             file_put_contents('log.txt'"Пользователь найден: " . ($userOb 'Да' 'Нет') . "\n"FILE_APPEND);
  138.             file_put_contents('log.txt'"Текущий шаг регистрации: " . ($registrationStep $registrationStep->getStep() : 'Нет') . "\n"FILE_APPEND);
  139.             if ($registrationStep) {
  140.                 file_put_contents('log.txt'"Продолжение незавершённой регистрации.\n"FILE_APPEND);
  141.                 $registrationHandler = new RegistrationHandlerTelegram($entityManager$telegramBotFunction$userPasswordHasher);
  142.                 $result $registrationHandler->handleStep($registrationStep$textRequest$userChat);
  143.                 if ($result === 'complete') {
  144.                     file_put_contents('log.txt'"Регистрация завершена. Удаление шага регистрации.\n"FILE_APPEND);
  145.                     $entityManager->remove($registrationStep);
  146.                     $entityManager->flush();
  147.                 }
  148.                 return $this->json('Empty');
  149.             }
  150.             if($userOb) {
  151.                 switch ($textRequest) {
  152.                     case '📞 Контакти':
  153.                         file_put_contents('log.txt'"Команда: '📞 Контакти'"FILE_APPEND);
  154.                         $contactMessage "📞 <b>Контакти:</b>\n\n";
  155.                         $contactMessage .= "<b>Телефони:</b>\n";
  156.                         $contactMessage .= "<a href=\"tel:+491639454555\">+49 163 945 4555</a>\n";
  157.                         $contactMessage .= "<a href=\"tel:+380955137377\">+380 95 513 7377</a>\n";
  158.                         $contactMessage .= "<a href=\"tel:+4915259177701\">+49 152 591 777 01</a>\n\n";
  159.                         file_put_contents('log.txt'"Отправка контактной информации.\n"FILE_APPEND);
  160.                         $telegramBotFunction->sendMessageHTML($userChat$contactMessage);
  161.                         return $this->json('Empty');
  162.                     case '📜 Політика конфіденційності':
  163.                         file_put_contents('log.txt'"Команда: '📜 Політика конфіденційності'"FILE_APPEND);
  164.                         $telegramBotFunction->sendMessage($userChat"📜 Політика конфіденційності:\nВаші дані зберігаються відповідно до GDPR. Детальніше на нашому сайті.");
  165.                         return $this->json('Empty');
  166.                     case '📦 Показати мої посилки':
  167.                         file_put_contents('log.txt'"Команда: '📦 Показати мої посилки'"FILE_APPEND);
  168.                         return $this->handleShowParcels($userChat$telegramBotFunction);
  169.                     case '📍 Адреса отримування':
  170.                         file_put_contents('log.txt'"Команда: '📍 Адреса отримування"FILE_APPEND);
  171.                         return $this->handleDeliveryAddress($userChat$telegramBotFunction);
  172.                     default:
  173.                         file_put_contents('log.txt'"Неизвестная команда: $textRequest\n"FILE_APPEND);
  174.                                 $telegramBotFunction->sendMessagewithKeyboard($userChat"Виберіть команду із меню."$this->getMainMenu());
  175.                                 return $this->json('Empty');
  176.                 }
  177.             } else {
  178.                 file_put_contents('log.txt'"Начало новой регистрации.\n"FILE_APPEND);
  179.                 return $this->handleStart($userChat$userOb$registrationStep$entityManager$telegramBotFunction);
  180.             }
  181.             // Обработка команд
  182.         }
  183.         return $this->json('Empty');
  184.     }
  185. // Обработчик команды /start
  186.     private function handleStart($userChat$userOb$registrationStep$entityManager$telegramBotFunction): Response
  187.     {
  188.         if ($registrationStep) {
  189.             // Продолжить с текущего шага
  190.             $telegramBotFunction->sendMessage($userChat"Реєстрація не завершена. Введіть ваш email для продовження:");
  191.             return $this->json('Empty');
  192.         }
  193.         if (!$userOb) {
  194.             $registrationStep = new RegistrationStep();
  195.             $registrationStep->setChatId($userChat);
  196.             $registrationStep->setStep('check_email');
  197.             $entityManager->persist($registrationStep);
  198.             $entityManager->flush();
  199.             $telegramBotFunction->sendMessage($userChat"Реєстрація почалась. Введіть свій email:");
  200.             return $this->json('Empty');
  201.         }
  202.         $telegramBotFunction->sendMessagewithKeyboard($userChat"Ласкаво просимо! Оберіть дію:"$this->getMainMenu());
  203.         return $this->json('Empty');
  204.     }
  205.     private function handleShowParcels($userChat$telegramBotFunction): Response
  206.     {
  207.         $userOb $this->entityManager->getRepository(User::class)->findOneBy(['telegramID' => $userChat]);
  208.         $orders $this->entityManager->getRepository(OrderUkraine::class)->findBy(['phoneInGermany' => $userOb->getPhoneNumber()]);
  209.         if($orders) {
  210.             $sendMessageHTML "";
  211.             foreach ($orders as $item) {
  212.                 $trackNumber $item->getTracknumberInGermany();
  213.                 $status $item->getStatusDelivery();
  214.                 $city $item->getCityInGermany();
  215.                 $getFactWeight $item->getFactWeight();
  216.                 $priceToPay $item->priceToPay();
  217.                 /*$address = $this->entityManager->getRepository(Adressen::class)->findOneBy(['city'=> $item->getCityInGermany()]);*/
  218.                 $sendMessageHTML .= "━━━━━━━━━━━━━━━━━━━━━━\n";
  219.                 $sendMessageHTML .= "📦 <b>Номер посилки:</b> $trackNumber\n";
  220.                 $sendMessageHTML .= "🔄 <b>Статус:</b> $status\n";
  221.                 $sendMessageHTML .= "🏙️ <b>Місто отримання:</b> $city\n";
  222.               /*  if($address) {
  223.                     $sendMessageHTML .= "📍 <b>Адресса отримання:</b> $address\n";
  224.                 } else {
  225.                     $sendMessageHTML .= "📍 <b>Адресса отримання:</b> Не вказана\n";
  226.                 }*/
  227.                 $sendMessageHTML .= "⚖ <b>Фактична вага:</b> $getFactWeight кг\n";
  228.                 $sendMessageHTML .= "💰 <b>Ціна до сплати:</b> $priceToPay грн\n";
  229.                 $sendMessageHTML .= "━━━━━━━━━━━━━━━━━━━━━━\n";
  230.             }
  231.             $telegramBotFunction->sendMessageHTML($userChat$sendMessageHTML);
  232.             return $this->json('Empty');
  233.         } else {
  234.             $telegramBotFunction->sendMessage($userChat"📦 У вас немає посилок.");
  235.             return $this->json('Empty');
  236.         }
  237.     }
  238.     private function handleDeliveryAddress($userChat$telegramBotFunction): Response
  239.     {
  240.         // Получаем все адреса из базы данных
  241.         $adresses $this->entityManager->getRepository(Adressen::class)->findAll();
  242.         if ($adresses) {
  243.             $sendMessageHTML "<b>📍 Доступні адреси:</b>";
  244.             // Формируем HTML для каждого адреса
  245.             foreach ($adresses as $address) {
  246.                 $city $address->getCity();
  247.                 $addressText $address->getAddressen();
  248.                 $workDay $address->getWorkDay();
  249.                 $advanced $address->getAdvanced();
  250.                 $time $address->getTime();
  251.                 $sendMessageHTML .= "---------------------------\n";
  252.                 $sendMessageHTML .= "<b>Місто:</b> $city\n";
  253.                 $sendMessageHTML .= "<b>Адреса:</b> $addressText\n";
  254.                 $sendMessageHTML .= "<b>Робочі дні:</b> $workDay\n";
  255.                 $sendMessageHTML .= "<b>Додаткова інформація:</b> $advanced\n";
  256.                 $sendMessageHTML .= "<b>Час роботи:</b> $time\n";
  257.                 $sendMessageHTML .= "---------------------------\n\n";
  258.             }
  259.             // Отправляем сообщение пользователю
  260.             $telegramBotFunction->sendMessageHTML($userChat$sendMessageHTML);
  261.         } else {
  262.             // Если адресов нет, отправляем сообщение об этом
  263.             $telegramBotFunction->sendMessage($userChat"📍 Упс немає даних");
  264.         }
  265.         return $this->json('Empty');
  266.     }
  267. // Генерация меню
  268.     public function getMainMenu(): array
  269.     {
  270.         $keyboard = [
  271.             [
  272.                 ['text' => '📦 Показати мої посилки''callback_data' => 'show_parcels'],
  273.                 ['text' => '📍 Адреса отримування''callback_data' => 'delivery_address']
  274.             ],
  275.             [
  276.                 ['text' => '📞 Контакти''callback_data' => 'contacts'],
  277.                 ['text' => '📜 Політика конфіденційності''callback_data' => 'privacy_policy']
  278.             ]
  279.         ];
  280.         $replyMarkup = [
  281.             'keyboard' => $keyboard,
  282.             'resize_keyboard' => true,
  283.             'one_time_keyboard' => false
  284.         ];
  285.         return $replyMarkup;
  286.     }
  287.     // Функция для проверки заполненности всех обязательных полей
  288.     private function allRequiredFieldsFilled(array $data, array $excludeFields = []): bool
  289.     {
  290.         $requiredFields = ['firstName''lastName''city''postalCode''address''password'];
  291.         foreach ($requiredFields as $field) {
  292.             if (!in_array($field$excludeFields) && empty($data[$field])) {
  293.                 return false;
  294.             }
  295.         }
  296.         return true;
  297.     }
  298.     // Проверка, существует ли пользователь в базе данных по email
  299.     private function checkUserExistsInDatabase(string $emailEntityManagerInterface $entityManager): bool
  300.     {
  301.         return (bool) $entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
  302.     }
  303.     // Создание нового пользователя в базе данных
  304.     private function createNewUserInDatabase(array $data$userChat,UserPasswordHasherInterface $userPasswordHasherEntityManagerInterface $entityManager$telegramBotFunction)
  305.     {
  306.         $user = new User();
  307.         $user->setFirstName($data['firstName']);
  308.         $user->setLastName($data['lastName']);
  309.         $user->setEmail($data['email']);
  310.         $user->setPhoneNumber($data['phoneNumber']);
  311.         $user->setCity($data['city']);
  312.         $user->setPostalCode($data['postalCode']);
  313.         $user->setAddress($data['address']);
  314.         $user->setPassword(
  315.             $userPasswordHasher->hashPassword(
  316.                 $user,
  317.                 $data['password']
  318.             )
  319.         );
  320.         $user->setRoles([
  321.             "ROLE_RECEIVER"
  322.         ]);
  323.         $user->setPassword(password_hash($data['password'], PASSWORD_BCRYPT));
  324.         $user->setTelegramID($userChat);
  325.         $entityManager->persist($user);
  326.         $entityManager->flush();
  327.         $telegramBotFunction->sendMessage($userChat"Реєстрація пройшла успішно!");
  328.     }
  329.     // Обновление данных существующего пользователя в базе данных
  330.     private function updateUserDataInDatabase(array $data$userChatEntityManagerInterface $entityManager$telegramBotFunction)
  331.     {
  332.         $user $entityManager->getRepository(User::class)->findOneBy(['email' => $data['email']]);
  333.         if ($user) {
  334.             $user->setFirstName($data['firstName']);
  335.             $user->setLastName($data['lastName']);
  336.             $user->setPhoneNumber($data['phoneNumber']);
  337.             $user->setCity($data['city']);
  338.             $user->setPostalCode($data['postalCode']);
  339.             $user->setAddress($data['address']);
  340.             $user->setTelegramID($userChat);
  341.             $entityManager->flush();
  342.             $telegramBotFunction->sendMessage($userChat"Ваші дані оновлені!");
  343.         } else {
  344.             $telegramBotFunction->sendMessage($userChat"Помилка при оновленні даних. Спробуйте ще раз.");
  345.         }
  346.     }
  347. }