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

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