point-tools/src/Service/Telegram/MessageSender.php

101 lines
3.0 KiB
PHP
Raw Normal View History

2017-01-06 17:18:39 +00:00
<?php
declare(strict_types=1);
2017-01-06 17:18:39 +00:00
namespace App\Service\Telegram;
2017-01-06 17:18:39 +00:00
use App\Entity\Telegram\Account;
use Psr\Log\LoggerInterface;
use TelegramBot\Api\BotApi;
use TelegramBot\Api\Types\ReplyKeyboardMarkup;
use Twig\Environment;
2017-01-06 17:18:39 +00:00
class MessageSender
{
public const PARSE_PLAIN = '';
public const PARSE_MARKDOWN = 'Markdown';
public const PARSE_MARKDOWN_V2 = 'MarkdownV2';
public const PARSE_HTML = 'HTML';
2017-01-06 17:18:39 +00:00
public function __construct(
private readonly BotApi $client,
private readonly Environment $twig,
private readonly LoggerInterface $log,
) {
2017-01-06 17:18:39 +00:00
}
/** @param Account[] $accounts */
public function sendMassTemplatedMessage(
array $accounts,
string $template,
array $templateData = [],
ReplyKeyboardMarkup $keyboardMarkup = null,
bool $disableWebPreview = true,
bool $disableNotifications = false,
string $parseMode = self::PARSE_MARKDOWN_V2
): void
{
$text = $this->twig->render($template, $templateData);
foreach ($accounts as $account) {
$this->sendMessage($account, $text, $parseMode, $keyboardMarkup, $disableWebPreview, $disableNotifications);
}
}
public function sendTemplatedMessage(
Account $account,
string $template,
array $templateData = [],
ReplyKeyboardMarkup $keyboardMarkup = null,
bool $disableWebPreview = true,
bool $disableNotifications = false,
string $parseMode = self::PARSE_MARKDOWN_V2
): bool
{
$text = $this->twig->render($template, $templateData);
return $this->sendMessage($account, $text, $parseMode, $keyboardMarkup, $disableWebPreview, $disableNotifications);
}
public function sendMessage(
2017-01-06 17:18:39 +00:00
Account $account,
string $text,
string $parseMode = self::PARSE_PLAIN,
ReplyKeyboardMarkup $keyboardMarkup = null,
2017-01-06 17:18:39 +00:00
bool $disableWebPreview = false,
2017-01-06 17:24:40 +00:00
bool $disableNotifications = false
): bool
{
2017-01-06 17:18:39 +00:00
return $this->sendMessageToChat($account->getChatId(), $text, $parseMode, $keyboardMarkup, $disableWebPreview, $disableNotifications);
}
public function sendMessageToChat(
2017-01-06 17:18:39 +00:00
int $chatId,
string $text,
string $parseMode = self::PARSE_PLAIN,
ReplyKeyboardMarkup $keyboardMarkup = null,
2017-01-06 17:18:39 +00:00
bool $disableWebPreview = false,
2017-01-06 17:24:40 +00:00
bool $disableNotifications = false
): bool
{
2017-01-06 17:18:39 +00:00
try {
$this->client->sendMessage(
chatId: (string) $chatId,
text: $text,
parseMode: $parseMode,
disablePreview: $disableWebPreview,
replyMarkup: $keyboardMarkup,
disableNotification: $disableNotifications,
);
2017-01-06 17:18:39 +00:00
return true;
} catch (\Exception $e) {
$this->log->error('sendMessageToChat', [
'error' => $e->getMessage(),
'file' => $e->getFile() . ':' . $e->getLine(),
]);
2017-01-06 17:18:39 +00:00
return false;
}
}
}