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

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