Skip to content

Commit b934e69

Browse files
committed
Отправка битриксовых почтовых событий в Телеграм.
1 parent 30cc87d commit b934e69

File tree

3 files changed

+142
-2
lines changed

3 files changed

+142
-2
lines changed

install/version.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?php
22

33
$arModuleVersion = [
4-
'VERSION' => '1.0.6',
4+
'VERSION' => '1.1.0',
55
'VERSION_DATE' => '2021-07-28'
66
];
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
<?php
2+
3+
namespace Proklung\Notifier\Bitrix;
4+
5+
use Bitrix\Main\ArgumentException;
6+
use Bitrix\Main\Mail\Internal\EventTable;
7+
use Bitrix\Main\ObjectPropertyException;
8+
use Bitrix\Main\SystemException;
9+
use Exception;
10+
use RuntimeException;
11+
use Symfony\Component\Notifier\Bridge\Telegram\TelegramOptions;
12+
use Symfony\Component\Notifier\Bridge\Telegram\TelegramTransport;
13+
use Symfony\Component\Notifier\ChatterInterface;
14+
use Symfony\Component\Notifier\Exception\TransportExceptionInterface;
15+
use Symfony\Component\Notifier\Message\ChatMessage;
16+
17+
/**
18+
* Class BitrixTelegramEventSender
19+
* @package Proklung\Notifier\Bitrix
20+
*
21+
* @since 28.07.2021
22+
*/
23+
class BitrixTelegramEventSender
24+
{
25+
/**
26+
* @var EventBridge $eventBridge Обработка битриксовых данных события.
27+
*/
28+
private $eventBridge;
29+
30+
/**
31+
* @var ChatterInterface $notifier Notifier.
32+
*/
33+
private $notifier;
34+
35+
/**
36+
* BitrixChatEventSender constructor.
37+
*
38+
* @param EventBridge $eventBridge Обработка битриксовых данных события.
39+
* @param ChatterInterface $notifier Notifier.
40+
*/
41+
public function __construct(EventBridge $eventBridge, ChatterInterface $notifier)
42+
{
43+
$this->eventBridge = $eventBridge;
44+
$this->notifier = $notifier;
45+
}
46+
47+
/**
48+
* Статический фасад.
49+
*
50+
* @param ChatterInterface $notifier Notifier.
51+
*
52+
* @return static
53+
* @throws RuntimeException Когда пакет symfony/telegram-notifier не установлен.
54+
*/
55+
public static function getInstance(ChatterInterface $notifier) : self
56+
{
57+
if (!class_exists(TelegramTransport::class)) {
58+
throw new RuntimeException(
59+
sprintf(
60+
'Unable to send notification via "%s" as the bridge is not installed; try running "composer require %s".',
61+
'telegram',
62+
'symfony/telegram-notifier'
63+
)
64+
);
65+
}
66+
67+
return new static(new EventBridge(), $notifier);
68+
}
69+
70+
/**
71+
* Отправить сообщение.
72+
*
73+
* @param string $codeEvent Код события.
74+
* @param array $arFields Параметры события.
75+
*
76+
* @return void
77+
* @throws ArgumentException | ObjectPropertyException | SystemException Битриксовые ошибки.
78+
* @throws TransportExceptionInterface Ошибки транспорта.
79+
*/
80+
public function send(string $codeEvent, array $arFields) : void
81+
{
82+
$eventsInfo = $this->eventBridge->getMessageTemplate($codeEvent);
83+
foreach ($eventsInfo as $eventInfo) {
84+
$compileData = $this->eventBridge->compileMessage($eventInfo, $arFields, ['s1']);
85+
86+
$notification = (new ChatMessage($compileData['subject'] . ' ' . $compileData['body']))
87+
->transport('telegram');
88+
89+
$telegramOptions = (new TelegramOptions())
90+
->parseMode('Markdown')
91+
->disableWebPagePreview(true)
92+
->disableNotification(false);
93+
94+
$notification->options($telegramOptions);
95+
96+
$this->notifier->send($notification);
97+
98+
// Эмуляция поведения Битрикса при обработке событий.
99+
try {
100+
EventTable::add(
101+
[
102+
'EVENT_NAME' => $eventInfo->getEventCode(),
103+
'SUCCESS_EXEC' => 'Y',
104+
'MESSAGE_ID' => 99999, // Признак, что отправлено через Notifier
105+
'DUPLICATE' => 'N',
106+
'LID' => SITE_ID,
107+
'LANGUAGE_ID' => LANGUAGE_ID,
108+
'DATE_INSERT' => new \Bitrix\Main\Type\DateTime,
109+
'DATE_EXEC' => new \Bitrix\Main\Type\DateTime,
110+
'C_FIELDS' => $eventInfo->getMessageData(),
111+
]
112+
);
113+
} catch (Exception $e) {
114+
// Silence. Не самый важный момент.
115+
}
116+
}
117+
}
118+
}

readme.MD

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,4 +225,26 @@ return [
225225
```
226226

227227
Ошибки отправки глушатся. Если что-то с доставкой SMS пойдет не так, то будет тихо, но в таблице `b_event`
228-
появится запись с признаком неудачи и текстом ошибки.
228+
появится запись с признаком неудачи и текстом ошибки.
229+
230+
### Отправка битриксовых почтовых шаблонов в Телеграм
231+
232+
```php
233+
use Proklung\Notifier\Bitrix\BitrixTelegramEventSender;
234+
235+
$bitrixEventHandler = BitrixTelegramEventSender::getInstance(
236+
\Proklung\Notifier\DI\Services::getInstance()->get('chatter')
237+
);
238+
239+
$arFields = ['CODE' => '2222', 'LINK' => 'http://site.loc/'];
240+
241+
$bitrixEventHandler->send('TEST_EVENT', $arFields);
242+
```
243+
244+
Должен быть установлен `symfony/telegram-notifier` и зарегистрирован транспорт `telegram` в секции `chatter_transports`
245+
файла `/bitrix/.settings.php`.
246+
247+
Нюанс:
248+
249+
- Telegram плохо переваривает html (даже в режиме `parse_mode = html`). Посему рекомендуется оформлять шаблоны
250+
в `markdown` разметке.

0 commit comments

Comments
 (0)