src/Controller/Cronjob/Telegram/AgentPublicBot/CronjobController.php line 170

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Cronjob\Telegram\AgentPublicBot;
  3. use App\Entity\Generic\User;
  4. use App\Entity\Telegram\AgentPublicBot\Bot;
  5. use App\Entity\Telegram\AgentPublicBot\BotAnalytics;
  6. use App\Entity\Telegram\AgentPublicBot\BotUser;
  7. use App\Repository\Telegram\AgentPublicBot\BotAnalyticsRepository;
  8. use App\Repository\Telegram\AgentPublicBot\BotNotificationRepository;
  9. use App\Repository\Telegram\AgentPublicBot\BotRepository;
  10. use App\Repository\Telegram\AgentPublicBot\BotTransactionRepository;
  11. use App\Repository\Telegram\AgentPublicBot\BotUserRepository;
  12. use App\Repository\VPN\Service\ServiceRepository;
  13. use App\Service\SettingService;
  14. use App\Service\Util\NotificationService;
  15. use App\Service\Util\Telegram;
  16. use DateTime;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use phpDocumentor\Reflection\DocBlock\Tags\Return_;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. class CronjobController extends AbstractController
  23. {
  24.     private EntityManagerInterface $entityManager;
  25.     public function __construct(EntityManagerInterface $entityManager)
  26.     {
  27.         $this->entityManager $entityManager;
  28.     }
  29.     #[Route('/cronjob/telegram/agent-public-bot/cronjob'name'app_cronjob_telegram_agent_public_bot_cronjob')]
  30.     public function index(BotRepository $botRepository): JsonResponse
  31.     {
  32.         foreach ($botRepository->findBy([]) as $bot) {
  33.             $array $this->checkTelegramBotToken($bot->getToken());
  34.             if ($array['res']) {
  35.                 $bot->setDescription($array['data']['result']['first_name']);
  36.                 $bot->setTitle($array['data']['result']['username']);
  37.                 $this->setWebhook($bot);
  38.             } else {
  39.                 $bot->setActive(false);
  40.             }
  41.             $this->getDoctrine()->getManager()->flush();
  42. //            ServicesCount
  43. //            $ocService = (int)count($ocServServiceRepository->findBy(['creatorBot' => $bot , 'active' => 1]));
  44. //            $v2ray = (int)count($v2rayMultiServiceRepository->findBy(['creatorBot' => $bot , 'active' => 1]));
  45. //            $open  = (int)count($openServiceRepository->findBy(['creatorBot' => $bot , 'active' => 1]));
  46. //            $totalService = $ocService + $v2ray +$open;
  47. //            $bot->setBotServices($totalService);
  48. //            $this->getDoctrine()->getManager()->flush();
  49. //            channelMember
  50. //            $count = $this->getChannelMemberCount($bot->getToken() , $bot->getChannelUserNAme());
  51. //            if ($count['res']){
  52. //                $bot->setChannelMembers($count['data']);
  53. //            }else{
  54. //                $bot->setChannelMembers(0);
  55. //            }
  56. //            $this->getDoctrine()->getManager()->flush();
  57.         }
  58.         return $this->json([
  59.             'res' => true
  60.         ]);
  61.     }
  62.     #[Route('/cronjob/telegram/agent-public-bot/cronjob-notifications'name'app_cronjob_telegram_agent_public_bot_cronjob_notifications')]
  63.     public function app_cronjob_telegram_agent_public_bot_cronjob_notifications(NotificationService $notificationService,BotNotificationRepository $botNotificationRepository\App\Repository\Generic\UserRepository $userRepository): JsonResponse
  64.     {
  65.         die;
  66.         foreach ($botNotificationRepository->findBy(['active' => 1'isSent' => 0]) as $notification) {
  67.             $bot $notification->getBot();
  68.             if ($bot->isActive()) {
  69.                 $users $bot->getBotUsers();
  70.                 foreach ($users as $botUser) {
  71.                     /**
  72.                      * @var BotUser $botUser
  73.                      */
  74.                     try {
  75.                         if ($botUser->getUserId() !== null){
  76.                             $this->sendMessage($botUser->getUserId(), $notification->getMessage(), $bot->getToken());
  77.                         }
  78.                     } catch (\Exception $exception) {
  79.                         $notificationService->exception($exception);
  80.                         if ($bot->isIsBotForWebsite()) {
  81.                             foreach ($userRepository->getOldExistTelegramUser($botUser->getUserId()) as $panelUser) {
  82.                                 /**
  83.                                  * @var User $panelUser
  84.                                  */
  85.                                 $panelUser->setConnectedTelegramUserId([]);
  86.                             }
  87.                         }
  88.                         $botUser->setActive(0);
  89.                     }
  90.                 }
  91.             }
  92.             $notification->setIsSent(1);
  93.             $this->entityManager->flush();
  94.         }
  95.         return $this->json(['res' => true]);
  96.     }
  97.     #[Route('/cronjob/telegram/agent-public-bot/cronjob-marketing'name'app_cronjob_telegram_agent_public_bot_cronjob_marketing')]
  98.     public function app_cronjob_telegram_agent_public_bot_cronjob_marketing(NotificationService $notificationService BotRepository $botRepositoryBotUserRepository $botUserRepository): JsonResponse
  99.     {
  100.         foreach ($botRepository->findBy(['active' => 1'sentAutoMessages' => 1]) as $bot) {
  101.             $testMessage $bot->getAdsNotTestedMessage();
  102.             if ($testMessage) {
  103.                 $users $botUserRepository->findBy(['bot' => $bot'gotTest' => 0]);
  104.                 foreach ($users as $user) {
  105.                     /**
  106.                      * @var BotUser $botUser
  107.                      */
  108.                     try {
  109.                         $this->sendInlineKeyboard($user->getUserId(), $testMessage$bot->getToken(),
  110.                             [
  111.                                 [
  112.                                     [
  113.                                         "text" => "🎁 دریافت اکانت تست (رایگان)",
  114.                                         "callback_data" => "testService"
  115.                                     ]
  116.                                 ],
  117.                             ]
  118.                         );
  119.                     } catch (\Exception $exception) {
  120.                         $notificationService->exception($exception);
  121.                         $botUser->setActive(0);
  122.                     }
  123.                 }
  124.             }
  125.             $boughtMessage $bot->getAdsNotBoughtMessage();
  126.             if ($boughtMessage) {
  127.                 $users $botUserRepository->getNotBoughtUsers($bot);
  128.                 foreach ($users as $user) {
  129.                     /**
  130.                      * @var BotUser $botUser
  131.                      */
  132.                     try {
  133.                         $this->sendInlineKeyboard($user->getUserId(), $testMessage$bot->getToken(),
  134.                             [
  135.                                 [
  136.                                     [
  137.                                         "text" => "🛒 خرید کانفیگ جدید",
  138.                                         "callback_data" => "buyService"
  139.                                     ]
  140.                                 ],
  141.                             ]
  142.                         );
  143.                     } catch (\Exception $exception) {
  144.                         $notificationService->exception($exception);
  145.                         $botUser->setActive(0);
  146.                     }
  147.                 }
  148.             }
  149.         }
  150.         $this->entityManager->flush();
  151.         return $this->json(['res' => true]);
  152.     }
  153.     #[Route('/cronjob/telegram/agent-public-bot/cronjob-analytics'name'app_cronjob_telegram_agent_public_bot_cronjob_analytics')]
  154.     public function app_cronjob_telegram_agent_public_bot_cronjob_analytics(NotificationService $notificationService ServiceRepository $serviceRepositoryBotRepository $botRepository BotAnalyticsRepository $analyticsRepository BotTransactionRepository $transactionRepository): JsonResponse
  155.     {
  156.         $haveError false;
  157.         $now = new DateTime(); // Get the current date
  158.         foreach ($botRepository->findBy(['active' => ]) as $bot) {
  159.             // Loop through the last 30 days
  160.             for ($i 0$i <=2$i++) {
  161.                 // Subtract $i days from today
  162.                 $currentDate = clone $now// Clone to avoid modifying the original $now
  163.                 $currentDate->modify('-' $i ' day'); // Modify the date by subtracting $i days
  164.                 // Check if an analytics record exists for the current date
  165.                 $analyticsObject $analyticsRepository->findOneBy(['date' => $currentDate 'bot' => $bot]);
  166.                 if (!$analyticsObject) {
  167.                     $analyticsObject = new BotAnalytics();
  168.                     $analyticsObject->setBot($bot);
  169.                     $analyticsObject->setDate($currentDate);
  170.                 }
  171. //                var_dump($analyticsObject->getId());die;
  172.                 // Get the required data for the current date
  173.                 $increaseValue $transactionRepository->getIncreaseForDate($currentDate $bot);
  174.                 $boughtVolume $transactionRepository->getBoughtVolume($currentDate $bot);
  175.                 $totalBought 0;
  176.                 // Set the analytics data for the current date
  177.                 $analyticsObject->setVip($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot 'sized' 'vip'));
  178.                 $analyticsObject->setOcServ($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot 'sized' 'ocserv'));
  179.                 $analyticsObject->setOcServUnlimited($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot 'unlimited' 'ocserv'));
  180.                 $analyticsObject->setV2ray($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot 'sized' 'v2ray'));
  181.                 $analyticsObject->setV2rayUnlimited($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot 'unlimited' 'v2ray'));
  182.                 $analyticsObject->setOpen($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot 'sized' 'open'));
  183.                 $analyticsObject->setOpenUnlimited($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot 'unlimited' 'open'));
  184.                 $analyticsObject->setTestService($serviceRepository->getTotalTestForDateCountTelegramBot($currentDate,$bot ));
  185.                 $analyticsObject->setBoughtVolume($boughtVolume);
  186.                 // Calculate total bought volume for the current date
  187.                 $totalBought += $analyticsObject->getVip();
  188.                 $totalBought += $analyticsObject->getV2ray();
  189.                 $totalBought += $analyticsObject->getV2rayUnlimited();
  190.                 $totalBought += $analyticsObject->getOpen();
  191.                 $totalBought += $analyticsObject->getOpenUnlimited();
  192.                 $totalBought += $analyticsObject->getOcServ();
  193.                 $totalBought += $analyticsObject->getOcServUnlimited();
  194.                 $analyticsObject->setBoughtService($totalBought);
  195.                 $analyticsObject->setWalletIncrease($increaseValue);
  196.                 // Persist the analytics data for the current date
  197.                 $this->entityManager->persist($analyticsObject);
  198.                 $analyticsObject->setUpdatedAt(new \DateTime());
  199.             $this->entityManager->flush();
  200.             }
  201.         }
  202.         // Flush all persisted data at once after the loop
  203.         $this->entityManager->flush();
  204.         $this->entityManager->clear(); // Clear to free memory after flush
  205.         return $this->json(['res' => true]);
  206.     }
  207.     public function checkTelegramBotToken($botToken)
  208.     {
  209.         $url "https://api.telegram.org/bot{$botToken}/getMe";
  210.         $ch curl_init();
  211.         curl_setopt($chCURLOPT_URL$url);
  212.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  213.         $response curl_exec($ch);
  214.         curl_close($ch);
  215.         $result json_decode($responsetrue);
  216.         if (isset($result['ok']) && $result['ok']) {
  217.             return [
  218.                 'res' => true,
  219.                 'data' => $result
  220.             ];
  221.         } else {
  222.             return [
  223.                 'res' => false,
  224.                 'data' => null
  225.             ];
  226.         }
  227.     }
  228.     public function getChannelMemberCount($botToken$channelUsername)
  229.     {
  230.         $url "https://api.telegram.org/bot{$botToken}/getChatMembersCount";
  231.         $params = [
  232.             'chat_id' => '@' $channelUsername
  233.         ];
  234.         $ch curl_init();
  235.         curl_setopt($chCURLOPT_URL$url);
  236.         curl_setopt($chCURLOPT_POST1);
  237.         curl_setopt($chCURLOPT_POSTFIELDShttp_build_query($params));
  238.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  239.         $response curl_exec($ch);
  240.         curl_close($ch);
  241.         $responseData json_decode($responsetrue);
  242.         if (isset($responseData['ok']) && $responseData['ok']) {
  243.             return [
  244.                 'res' => true,
  245.                 'data' => $responseData['result']
  246.             ];
  247.         } else {
  248.             return [
  249.                 'res' => false,
  250.                 'data' => null
  251.             ];
  252.         }
  253.     }
  254.     public function setWebhook(Bot $bot)
  255.     {
  256.         try {
  257.             $webhookUrl $_ENV['APP_URL'] . '/telegram/agent-public-bot/webhook/' $bot->getId();
  258.             $webhookUrl $_ENV['APP_URL'] . '/telegram/agent-public-bot/webhook-neo/' $bot->getId();
  259. //            $webhookUrl = $_ENV['APP_URL'] . '/telegram/agent-public-bot/webhook-neo/{id}' . $bot->getId();
  260.             $telegramApiUrl "https://api.telegram.org/bot{$bot->getToken()}/setWebhook";
  261.             $data = [
  262.                 'url' => $webhookUrl,
  263.                 'drop_pending_updates' => 'True',
  264.                 'max_connections' => '100'
  265.             ];
  266.             $ch curl_init($telegramApiUrl);
  267.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  268.             curl_setopt($chCURLOPT_POSTtrue);
  269.             curl_setopt($chCURLOPT_POSTFIELDS$data);
  270.             $response curl_exec($ch);
  271.             if (curl_errno($ch)) {
  272.                 echo 'cURL error: ' curl_error($ch);
  273.             } else {
  274.                 $responseData json_decode($responsetrue);
  275.                 if ($responseData['ok']) {
  276.                     return true;
  277.                 } else {
  278.                     return false;
  279.                 }
  280.             }
  281.             curl_close($ch);
  282.             return false;
  283.         } catch (\Exception $exception) {
  284. //            $this->bot('sendMessage', [
  285. //                'chat_id' => $this->chatId,
  286. //                'text' =>
  287. //                    $exception->getMessage()
  288. //                ,
  289. ////                'reply_markup' => $mainMenuKeyboard
  290. //            ]);
  291.             return false;
  292.         }
  293.     }
  294.     private function sendMessage(string $chatIdstring $text$token$markdown nullbool $silent false): void
  295.     {
  296.         $url sprintf(
  297.             'https://api.telegram.org/bot%s/sendMessage',
  298.             $token // Replace with your bot token
  299.         );
  300.         $payload = [
  301.             'chat_id' => $chatId,
  302.             'text' => ($text),
  303.             'disable_notification' => $silent// Set to true for silent messages
  304.         ];
  305.         if ($markdown) {
  306.             $payload['parse_mode'] = $markdown;
  307.         }
  308.         $this->sendRequest($url$payload);
  309.     }
  310.     private function sendRequest(string $url, array $payload)
  311.     {
  312.         $ch curl_init($url);
  313.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  314.         curl_setopt($chCURLOPT_POSTtrue);
  315.         curl_setopt($chCURLOPT_POSTFIELDS$payload);
  316.         $response curl_exec($ch);
  317.         if (curl_errno($ch)) {
  318.             // Log or handle the error
  319.             throw new \Exception('Curl error: ' curl_error($ch));
  320.         }
  321.         curl_close($ch);
  322.         return $response// Return the response for further processing
  323.     }
  324.     public function bot($method$data$token)
  325.     {
  326.         $setting = new SettingService($this->entityManager);
  327.         $telegramApiUrl 'https://api.telegram.org/bot' $token '/';
  328.         return file_get_contents($telegramApiUrl $method '?' str_replace('&amp;''&'http_build_query($data)));
  329.     }
  330.     private function sendInlineKeyboard(string $chatIdstring $text$token, array $keyborad$parseMode null): void
  331.     {
  332.         $url sprintf(
  333.             'https://api.telegram.org/bot%s/sendMessage',
  334.             $token
  335.         );
  336.         $payload = [
  337.             'chat_id' => $chatId,
  338.             'text' => ($text),
  339.             'parse_mode' => $parseMode,
  340.             'reply_markup' => json_encode([
  341.                 'inline_keyboard' =>
  342.                     $keyborad,
  343.             ]),
  344.         ];
  345.         if ($parseMode) {
  346.             $payload['parse_mode'] = $parseMode;
  347.         }
  348.         $this->sendRequest($url$payload);
  349.     }
  350. }