<?php
namespace Social\FrontendBundle\Controller;
use Psr\Log\LoggerInterface;
use Social\InternalBundle\Entity\TelegramBot;
use Social\InternalBundle\Entity\TelegramBotEvent;
use Social\InternalBundle\Entity\TelegramBotMessage;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class HooksController extends Controller
{
/**
* @var LoggerInterface
*/
private $telegramLogger;
public function __construct(LoggerInterface $telegramLogger)
{
$this->telegramLogger = $telegramLogger;
}
/**
* @param Request $request
*
* @return JsonResponse
*/
public function mailReportAction(Request $request)
{
try {
$sparkService = $this->get('social.emailfilters.sparkpost');
$response = $sparkService->checkAuth($request);
if (true === $response['error_flag']) {
return $response['response'];
}
$response = $sparkService->captureEvent($request);
return new JsonResponse($response);
} catch (\Exception $exception) {
$this->get('sentry.client')->captureException($exception);
}
}
/**
* @param Request $request
*
* @return JsonResponse
*/
public function telegramEventsAction(Request $request)
{
try {
$em = $this->getDoctrine()->getManager();
$this->telegramLogger->info(json_encode($request->getContent()));
$data = json_decode($request->getContent(), true);
if (isset($data['message']['chat']['id'])) {
$text = $data['message']['text'];
$chatId = $data['message']['chat']['id'];
$messageId = $data['message']['message_id'];
$firstName = $data['message']['from']['first_name'];
$lastName = $data['message']['from']['last_name'];
$username = isset($data['message']['from']['username']) ? $data['message']['from']['username'] : null;
$time = $data['message']['date'];
$this->telegramLogger->info('chatId = ' . $chatId);
/** @var TelegramBot|null $telegramBot */
$telegramBot = null;
if ($text && strpos($text, "start")) {
$text = explode("start ", $text);
$telegramBot = $em->getRepository(TelegramBot::class)->findOneBy(['action' => $text[1], 'active' => true]);
}
if ($telegramBot) {
$this->telegramLogger->info("telegramBot = " . $telegramBot->getId());
$botAPIToken = $telegramBot->getTgBotSetting()->getApiToken();
/** @var TelegramBotMessage $botMessage */
foreach ($telegramBot->getTgBotMessages() as $botMessage) {
$message = $botMessage->getMessage();
$botMessageMedia = $botMessage->getMedia();
$client = HttpClient::create();
if ($botMessageMedia) {
$json = [];
$json['chat_id'] = $chatId;
if ($message) {
$json['caption'] = str_replace(['<p>', '</p>', '<b>', '</b>'], '', $botMessage->getMessage());
$json['parse_mode'] = 'HTML';
}
if ($botMessage->getButtonText() && $botMessage->getUrl()) {
$json['reply_markup'] = ['inline_keyboard' => [[['text' => $botMessage->getButtonText(), 'url' => $botMessage->getUrl()]]]];
}
$this->telegramLogger->info('$json = ' . json_encode($json));
// if ($botMessage->getDelayTime()) {
// sleep($botMessage->getDelayTime());
// }
if ($botMessage->getMimeType() == 'video/mp4') {
$json['video'] = $request->getUriForPath('/media/user_tg/' . $botMessage->getMedia());
$response = $client->request('POST', 'https://api.telegram.org/bot' . $botAPIToken . '/sendVideo', [
'json' => $json
]);
$data = json_decode($response->getContent(), true);
if ($data && $data['ok']) {
$this->addTelegramEvents($chatId, $messageId, $firstName, $lastName, $time, $botMessage, $username);
$this->telegramLogger->info("Video sent successfully.");
} else {
$this->telegramLogger->info("Failed to send video.");
}
} elseif ($botMessage->getMimeType() == 'audio/mpeg') {
$json['audio'] = $request->getUriForPath('/media/user_tg/' . $botMessage->getMedia());
$response = $client->request('POST', 'https://api.telegram.org/bot' . $botAPIToken . '/sendAudio', [
'json' => $json
]);
$data = json_decode($response->getContent(), true);
$this->telegramLogger->error('response = ' . json_encode($response));
if ($data && $data['ok']) {
$this->addTelegramEvents($chatId, $messageId, $firstName, $lastName, $time, $botMessage, $username);
$this->telegramLogger->info("Audio sent successfully.");
} else {
$this->telegramLogger->info("Failed to send Audio.");
}
} else {
$json['photo'] = $request->getUriForPath('/media/user_tg/' . $botMessage->getMedia());
$response = $client->request('POST', 'https://api.telegram.org/bot' . $botAPIToken . '/sendPhoto', [
'json' => $json
]);
$this->telegramLogger->error('response = ' . json_encode($response));
$data = json_decode($response->getContent(), true);
if ($data && $data['ok']) {
$this->addTelegramEvents($chatId, $messageId, $firstName, $lastName, $time, $botMessage, $username);
$this->telegramLogger->info("Image sent successfully.");
} else {
$this->telegramLogger->info("Failed to send image.");
}
}
} elseif ($message) {
$this->telegramLogger->info("In message " . $message);
if ($botMessage->getDelayTime()) {
sleep($botMessage->getDelayTime());
}
$client = HttpClient::create();
$response = $client->request('POST', 'https://api.telegram.org/bot' . $botAPIToken . '/sendMessage', [
'json' => [
'chat_id' => $chatId,
'text' => str_replace(['<p>', '</p>'], '', $message),
'parse_mode' => 'HTML'
],
]);
$data = json_decode($response->getContent(), true);
if ($data && $data['ok']) {
$this->addTelegramEvents($chatId, $messageId, $firstName, $lastName, $time, $botMessage, $username);
$this->telegramLogger->info("Message sent successfully.");
} else {
$this->telegramLogger->info("Failed to send message.");
}
}
}
}
}
return new JsonResponse(['success' => true]);
} catch (\Exception $exception) {
$this->get('sentry.client')->captureException($exception);
exit;
}
}
public function addTelegramEvents($chatId, $messageId, $firstName, $lastName, $time, $botMessage, $username=null)
{
try {
$em = $this->getDoctrine()->getManager();
$telegramBotEvent = new TelegramBotEvent();
$telegramBotEvent->setChatId($chatId);
$telegramBotEvent->setMessageId($messageId);
$telegramBotEvent->setFirstName($firstName);
$telegramBotEvent->setLastName($lastName);
$telegramBotEvent->setMessageSentAt(\DateTime::createFromFormat('U', $time));
$telegramBotEvent->setTelegramBotMessage($botMessage);
if ($username) {
$telegramBotEvent->setUsername($username);
}
$em->persist($telegramBotEvent);
$em->flush();
} catch (\Exception $exception) {
$this->get('sentry.client')->captureException($exception);
$this->telegramLogger->error('error while inserting event ' . $exception->getMessage());
}
}
}