<?php
namespace App\Controller\Cronjob\Telegram\AgentPublicBot;
use App\Entity\Generic\User;
use App\Entity\Telegram\AgentPublicBot\Bot;
use App\Entity\Telegram\AgentPublicBot\BotAnalytics;
use App\Entity\Telegram\AgentPublicBot\BotUser;
use App\Repository\Telegram\AgentPublicBot\BotAnalyticsRepository;
use App\Repository\Telegram\AgentPublicBot\BotNotificationRepository;
use App\Repository\Telegram\AgentPublicBot\BotRepository;
use App\Repository\Telegram\AgentPublicBot\BotTransactionRepository;
use App\Repository\Telegram\AgentPublicBot\BotUserRepository;
use App\Repository\VPN\Service\ServiceRepository;
use App\Service\SettingService;
use App\Service\Util\NotificationService;
use App\Service\Util\Telegram;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\DocBlock\Tags\Return_;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
class CronjobController extends AbstractController
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
#[Route('/cronjob/telegram/agent-public-bot/cronjob', name: 'app_cronjob_telegram_agent_public_bot_cronjob')]
public function index(BotRepository $botRepository): JsonResponse
{
foreach ($botRepository->findBy([]) as $bot) {
$array = $this->checkTelegramBotToken($bot->getToken());
if ($array['res']) {
$bot->setDescription($array['data']['result']['first_name']);
$bot->setTitle($array['data']['result']['username']);
$this->setWebhook($bot);
} else {
$bot->setActive(false);
}
$this->getDoctrine()->getManager()->flush();
// ServicesCount
// $ocService = (int)count($ocServServiceRepository->findBy(['creatorBot' => $bot , 'active' => 1]));
// $v2ray = (int)count($v2rayMultiServiceRepository->findBy(['creatorBot' => $bot , 'active' => 1]));
// $open = (int)count($openServiceRepository->findBy(['creatorBot' => $bot , 'active' => 1]));
// $totalService = $ocService + $v2ray +$open;
// $bot->setBotServices($totalService);
// $this->getDoctrine()->getManager()->flush();
// channelMember
// $count = $this->getChannelMemberCount($bot->getToken() , $bot->getChannelUserNAme());
// if ($count['res']){
// $bot->setChannelMembers($count['data']);
// }else{
// $bot->setChannelMembers(0);
// }
// $this->getDoctrine()->getManager()->flush();
}
return $this->json([
'res' => true
]);
}
#[Route('/cronjob/telegram/agent-public-bot/cronjob-notifications', name: 'app_cronjob_telegram_agent_public_bot_cronjob_notifications')]
public function app_cronjob_telegram_agent_public_bot_cronjob_notifications(NotificationService $notificationService,BotNotificationRepository $botNotificationRepository, \App\Repository\Generic\UserRepository $userRepository): JsonResponse
{
foreach ($botNotificationRepository->findBy(['active' => 1, 'isSent' => 0]) as $notification) {
$bot = $notification->getBot();
if ($bot->isActive()) {
$users = $bot->getBotUsers();
foreach ($users as $botUser) {
/**
* @var BotUser $botUser
*/
try {
$this->sendMessage($botUser->getUserId(), $notification->getMessage(), $bot->getToken());
} catch (\Exception $exception) {
$notificationService->exception($exception);
if ($bot->isIsBotForWebsite()) {
foreach ($userRepository->getOldExistTelegramUser($botUser->getUserId()) as $panelUser) {
/**
* @var User $panelUser
*/
$panelUser->setConnectedTelegramUserId([]);
}
}
$botUser->setActive(0);
}
}
}
$notification->setIsSent(1);
$this->entityManager->flush();
}
return $this->json(['res' => true]);
}
#[Route('/cronjob/telegram/agent-public-bot/cronjob-marketing', name: 'app_cronjob_telegram_agent_public_bot_cronjob_marketing')]
public function app_cronjob_telegram_agent_public_bot_cronjob_marketing(NotificationService $notificationService , BotRepository $botRepository, BotUserRepository $botUserRepository): JsonResponse
{
foreach ($botRepository->findBy(['active' => 1, 'sentAutoMessages' => 1]) as $bot) {
$testMessage = $bot->getAdsNotTestedMessage();
if ($testMessage) {
$users = $botUserRepository->findBy(['bot' => $bot, 'gotTest' => 0]);
foreach ($users as $user) {
/**
* @var BotUser $botUser
*/
try {
$this->sendInlineKeyboard($user->getUserId(), $testMessage, $bot->getToken(),
[
[
[
"text" => "🎁 دریافت اکانت تست (رایگان)",
"callback_data" => "testService"
]
],
]
);
} catch (\Exception $exception) {
$notificationService->exception($exception);
$botUser->setActive(0);
}
}
}
$boughtMessage = $bot->getAdsNotBoughtMessage();
if ($boughtMessage) {
$users = $botUserRepository->getNotBoughtUsers($bot);
foreach ($users as $user) {
/**
* @var BotUser $botUser
*/
try {
$this->sendInlineKeyboard($user->getUserId(), $testMessage, $bot->getToken(),
[
[
[
"text" => "🛒 خرید کانفیگ جدید",
"callback_data" => "buyService"
]
],
]
);
} catch (\Exception $exception) {
$notificationService->exception($exception);
$botUser->setActive(0);
}
}
}
}
$this->entityManager->flush();
return $this->json(['res' => true]);
}
#[Route('/cronjob/telegram/agent-public-bot/cronjob-analytics', name: 'app_cronjob_telegram_agent_public_bot_cronjob_analytics')]
public function app_cronjob_telegram_agent_public_bot_cronjob_analytics(NotificationService $notificationService , ServiceRepository $serviceRepository, BotRepository $botRepository , BotAnalyticsRepository $analyticsRepository , BotTransactionRepository $transactionRepository): JsonResponse
{
$haveError = false;
$now = new DateTime(); // Get the current date
foreach ($botRepository->findBy(['active' => 1 ]) as $bot) {
// Loop through the last 30 days
for ($i = 0; $i <=2; $i++) {
// Subtract $i days from today
$currentDate = clone $now; // Clone to avoid modifying the original $now
$currentDate->modify('-' . $i . ' day'); // Modify the date by subtracting $i days
// Check if an analytics record exists for the current date
$analyticsObject = $analyticsRepository->findOneBy(['date' => $currentDate , 'bot' => $bot]);
if (!$analyticsObject) {
$analyticsObject = new BotAnalytics();
$analyticsObject->setBot($bot);
$analyticsObject->setDate($currentDate);
}
// var_dump($analyticsObject->getId());die;
// Get the required data for the current date
$increaseValue = $transactionRepository->getIncreaseForDate($currentDate , $bot);
$boughtVolume = $transactionRepository->getBoughtVolume($currentDate , $bot);
$totalBought = 0;
// Set the analytics data for the current date
$analyticsObject->setVip($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot , 'sized' , 'vip'));
$analyticsObject->setOcServ($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot , 'sized' , 'ocserv'));
$analyticsObject->setOcServUnlimited($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot , 'unlimited' , 'ocserv'));
$analyticsObject->setV2ray($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot , 'sized' , 'v2ray'));
$analyticsObject->setV2rayUnlimited($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot , 'unlimited' , 'v2ray'));
$analyticsObject->setOpen($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot , 'sized' , 'open'));
$analyticsObject->setOpenUnlimited($serviceRepository->getTotalSellForDateCountTelegramBot($currentDate,$bot , 'unlimited' , 'open'));
$analyticsObject->setTestService($serviceRepository->getTotalTestForDateCountTelegramBot($currentDate,$bot ));
$analyticsObject->setBoughtVolume($boughtVolume);
// Calculate total bought volume for the current date
$totalBought += $analyticsObject->getVip();
$totalBought += $analyticsObject->getV2ray();
$totalBought += $analyticsObject->getV2rayUnlimited();
$totalBought += $analyticsObject->getOpen();
$totalBought += $analyticsObject->getOpenUnlimited();
$totalBought += $analyticsObject->getOcServ();
$totalBought += $analyticsObject->getOcServUnlimited();
$analyticsObject->setBoughtService($totalBought);
$analyticsObject->setWalletIncrease($increaseValue);
// Persist the analytics data for the current date
$this->entityManager->persist($analyticsObject);
$analyticsObject->setUpdatedAt(new \DateTime());
$this->entityManager->flush();
}
}
// Flush all persisted data at once after the loop
$this->entityManager->flush();
$this->entityManager->clear(); // Clear to free memory after flush
return $this->json(['res' => true]);
}
public function checkTelegramBotToken($botToken)
{
$url = "https://api.telegram.org/bot{$botToken}/getMe";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if (isset($result['ok']) && $result['ok']) {
return [
'res' => true,
'data' => $result
];
} else {
return [
'res' => false,
'data' => null
];
}
}
public function getChannelMemberCount($botToken, $channelUsername)
{
$url = "https://api.telegram.org/bot{$botToken}/getChatMembersCount";
$params = [
'chat_id' => '@' . $channelUsername
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$responseData = json_decode($response, true);
if (isset($responseData['ok']) && $responseData['ok']) {
return [
'res' => true,
'data' => $responseData['result']
];
} else {
return [
'res' => false,
'data' => null
];
}
}
public function setWebhook(Bot $bot)
{
try {
$webhookUrl = $_ENV['APP_URL'] . '/telegram/agent-public-bot/webhook/' . $bot->getId();
$webhookUrl = $_ENV['APP_URL'] . '/telegram/agent-public-bot/webhook-neo/' . $bot->getId();
// $webhookUrl = $_ENV['APP_URL'] . '/telegram/agent-public-bot/webhook-neo/{id}' . $bot->getId();
$telegramApiUrl = "https://api.telegram.org/bot{$bot->getToken()}/setWebhook";
$data = [
'url' => $webhookUrl,
'drop_pending_updates' => 'True',
'max_connections' => '100'
];
$ch = curl_init($telegramApiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'cURL error: ' . curl_error($ch);
} else {
$responseData = json_decode($response, true);
if ($responseData['ok']) {
return true;
} else {
return false;
}
}
curl_close($ch);
return false;
} catch (\Exception $exception) {
// $this->bot('sendMessage', [
// 'chat_id' => $this->chatId,
// 'text' =>
// $exception->getMessage()
// ,
//// 'reply_markup' => $mainMenuKeyboard
// ]);
return false;
}
}
private function sendMessage(string $chatId, string $text, $token, $markdown = null, bool $silent = false): void
{
$url = sprintf(
'https://api.telegram.org/bot%s/sendMessage',
$token // Replace with your bot token
);
$payload = [
'chat_id' => $chatId,
'text' => ($text),
'disable_notification' => $silent, // Set to true for silent messages
];
if ($markdown) {
$payload['parse_mode'] = $markdown;
}
$this->sendRequest($url, $payload);
}
private function sendRequest(string $url, array $payload)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$response = curl_exec($ch);
if (curl_errno($ch)) {
// Log or handle the error
throw new \Exception('Curl error: ' . curl_error($ch));
}
curl_close($ch);
return $response; // Return the response for further processing
}
public function bot($method, $data, $token)
{
$setting = new SettingService($this->entityManager);
$telegramApiUrl = 'https://api.telegram.org/bot' . $token . '/';
return file_get_contents($telegramApiUrl . $method . '?' . str_replace('&', '&', http_build_query($data)));
}
private function sendInlineKeyboard(string $chatId, string $text, $token, array $keyborad, $parseMode = null): void
{
$url = sprintf(
'https://api.telegram.org/bot%s/sendMessage',
$token
);
$payload = [
'chat_id' => $chatId,
'text' => ($text),
'parse_mode' => $parseMode,
'reply_markup' => json_encode([
'inline_keyboard' =>
$keyborad,
]),
];
if ($parseMode) {
$payload['parse_mode'] = $parseMode;
}
$this->sendRequest($url, $payload);
}
}