> For the complete documentation index, see [llms.txt](https://docs.mikopbx.com/mikopbx/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.mikopbx.com/mikopbx/faq/cases/notification-in-telegram.md).

# Уведомление в мессенджер о пропущенных

В данной статье будет рассмотрено два способа реализации уведомления о пропущеных вызовах в Telegram

## Уведомление Телеграм на базе Dialplan <a href="#primer_na_baze_dialplan" id="primer_na_baze_dialplan"></a>

{% hint style="success" %}
[Полезная статья](https://gist.github.com/dideler/85de4d64f66c1966788c1b2304b9caf1) по работе с Telegram-ботом средствами **curl.**
{% endhint %}

1. Перейдите в раздел "**Кастомизация системных файлов**":

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2FIn35rPMX4a6Ty9sFCh0t%2FsystemFileCustomization.png?alt=media&amp;token=20e27e89-3807-475c-8dac-3a08229edab0" alt=""><figcaption><p>Раздел "<strong>Кастомизация системных файлов</strong>"</p></figcaption></figure>

2. Перейдите в раздел редактирования файла "**extensions.conf**". Установите режим "**Добавлять в конец файла**" и вставьте следующий контекст:

```php
[add-trim-prefix-clid-custom]
exten => _[0-9*#+a-zA-Z][0-9*#+a-zA-Z]!,1,NoOp(start check blacklist)
	same => n,Set(CHANNEL(hangup_handler_push)=hangup-ext-queues,h,1);
	same => n,Return()

[hangup-ext-queues]
exten => h,1,ExecIf($["${M_DIALSTATUS}" = "ANSWER"]?return)
    same => n,Set(TOKEN=5118292900:AAEWCOAXkay5fXb8AJptZmDyqkNk8QbP200)
    same => n,Set(CHAT_ID=939950800)
    same => n,Set(URL=https://api.telegram.org/bot${TOKEN}/sendMessage)
    same => n,Set(TEXT=MISSED CALL from: ${CALLERID(name)}, did: ${FROM_DID}, callid: ${CHANNEL(callid)})
    same => n,SHELL(curl -s -X POST '${URL}' -d chat_id='${CHAT_ID}' -d text='${TEXT}')
    same => n,Set(MISSED=${SHELL(curl -s -X POST '${URL}' -d chat_id='${CHAT_ID}' -d text='${TEXT}')})
    same => n,return
```

В данном конктексте замените:

* **TOKEN** - токен вашего бота в телеграмм.
* **CHAT\_ID** - идентификатор чата, куда отправлять текстовое сообщение.

Сохраните изменения.

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2FCySFhZ3sRi9y9hwq69Ap%2FextensionsFileCode.jpg?alt=media&amp;token=f8f577c6-89fa-4d90-a0bc-37a927e56a4e" alt=""><figcaption><p>Редактирование файла "extensions.conf"</p></figcaption></figure>

3. Перейдите в раздел редактирования файла "**modules.conf**". Установите режим "**Добавлять в конец файла**" и вставьте следующий контекст:

```
load => func_shell.so
```

Сохраните изменения.

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2FcLzPcOcHvkoCwJRS0UyY%2FmodulesFileCode.jpg?alt=media&amp;token=24416b88-0367-440c-b0bd-60062f735f0b" alt=""><figcaption><p>Редактирование файла "modules.conf"</p></figcaption></figure>

{% hint style="success" %}
Средставми **curl** можно выполнить запрос к любому сайту. К примеру можно отправить уведомление в **slack**:

{% code overflow="wrap" fullWidth="false" %}

```php
same => n,Set(MISSED=${SHELL(curl -X POST --data-urlencode "payload={\"channel\": \"#cannel_name\", \"username\": \"bot_name\", \"text\": \"Пропущенный вызов от ${CALLERID(name)} по внешней линии: ${FROM_DID} в ${STRFTIME(${EPOCH},,%H:%M:%S %d-%m-%Y)}\", \"icon_emoji\": \":sos:\"}" https://hooks.slack.com/services/T76G7L0/B01R/VMPQUeAN)}) 
```

{% endcode %}
{% endhint %}

## Пример на базе PHP-AGI <a href="#primer_na_baze_php-agi" id="primer_na_baze_php-agi"></a>

1. Перейдите в раздел "**Приложения диалпланов**". Создайте новое приложение, нажав на "**Добавить новое**":

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2F1hqJCXDzV1mADG0heaHr%2FaddNewDialplanApp.jpg?alt=media&amp;token=f2ad6c8f-8437-4c7c-9868-cf2d5273bd24" alt=""><figcaption><p>Добавление нового приложения диалплана</p></figcaption></figure>

2. Укажите следующие параметры для диалплана:

* **Название** - произвольное
* **Номер для вызова приложения** - произвольный номер
* **Тип кода** - "*PHP-AGI скрипт*"

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2FCoBtmNaLpjuOqNNAbkzp%2FdialplanParameters.jpg?alt=media&amp;token=0b0f6eb6-d575-4f5b-8487-df6c1ab7e3a5" alt=""><figcaption><p>Параметры диалплана</p></figcaption></figure>

2. Перейдите во вкладку "**Программный код**". Вставьте следующий PHP-AGI скрипт:

{% code overflow="wrap" fullWidth="false" %}

```php
<?php
require_once 'Globals.php';
use \GuzzleHttp\Client;

const API_KEY = '';
const CHAT_ID = '';

$agi = new MikoPBX\Core\Asterisk\AGI();

$name = $agi->get_variable('CALLERID(name)', true);
$num  = $agi->get_variable('CALLERID(num)', true);
$did  = $agi->get_variable('$FROM_DID', true);
$id   = $agi->get_variable('CHANNEL(linkedid)', true);
$date = date('Y.d.m H:i:s', str_replace('mikopbx-', '', $id));

$TEXT = "Пропущенный вызов: $name, did: $did, callid: $num, id: $id, date: $date";
$apiURL = 'https://api.telegram.org/bot' . API_KEY . '/';
$client = new Client([
    'base_uri' => $apiURL,
    'timeout' => 1,
    'http_errors' => false,
]);
try {
    $client->post( 'sendMessage', ['query' => ['chat_id' => CHAT_ID, 'text' => $TEXT]] );
}catch (Throwable $e){
}
```

{% endcode %}

В данном конктексте замените:

* **API\_KEY** - токен вашего бота в телеграмм.
* **CHAT\_ID** - идентификатор чата, куда отправлять текстовое сообщение.

Текст уведомления можно исправить в переменной «$**TEXT**».

Пример скрипта для MAX

```php

<?php
require_once 'Globals.php';
use GuzzleHttp\Client;

const MAX_API_HOST = 'https://platform-api.max.ru/';
const CHAT_ID = 'CHAT_ID';
const AUTHORIZATION = 'API_KEY'; // put real token here

$agi = new MikoPBX\Core\Asterisk\AGI();

$name = $agi->get_variable('CALLERID(name)', true);
$num  = $agi->get_variable('CALLERID(num)', true);
$did  = $agi->get_variable('FROM_DID', true);
$id   = $agi->get_variable('CHANNEL(linkedid)', true);
$date = date('Y.d.m H:i:s', (int)str_replace('mikopbx-', '', $id));

$text = "Пропущенный вызов: {$name}\nисточник: {$did}\nдата: {$date}";

$client = new Client([
    'base_uri' => MAX_API_HOST,
    'timeout' => 2,
    'http_errors' => false,
]);

try {
    $client->post('messages', [
        'query' => [
            'chat_id' => CHAT_ID,
        ],
        'headers' => [
            'accept' => 'application/json',
            'authorization' => AUTHORIZATION,
            'content-type' => 'application/json',
        ],
        'json' => [
            'text' => $text,
        ],
    ]);
} catch (Throwable $e) {
    // optional log
}
```

3. После сохранения скрипта из адресной строки браузера скопируйте идентификатор скрипта, который имеет вид: «**DIALPLAN-APP-1B2B846E**»:

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2Fdgt1BWFzP54TnE7q1xLY%2FdialplanID.jpg?alt=media&amp;token=2251e37b-72a9-4385-835b-fdcd19767388" alt=""><figcaption><p>Идентификатор приложения диалплана</p></figcaption></figure>

4. Перейдите в раздел "**Кастомизация системных файлов**":

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2FIn35rPMX4a6Ty9sFCh0t%2FsystemFileCustomization.png?alt=media&amp;token=20e27e89-3807-475c-8dac-3a08229edab0" alt=""><figcaption><p>Раздел "<strong>Кастомизация системных файлов</strong>"</p></figcaption></figure>

5. Перейдите в раздел редактирования файла "**extensions.conf**". Установите режим "**Добавлять в конец файла**" и вставьте следующий контекст:

```php
[add-trim-prefix-clid-custom]
exten => _.X!,1,Set(CHANNEL(hangup_handler_push)=hangup-ext-queues,h,1);
	same => n,return
[hangup-ext-queues]
exten => h,1,ExecIf($["${M_DIALSTATUS}" = "ANSWER"]?return)
    same => n,AGI(DIALPLAN-APP-1B2B846E.php)
    same => n,return
```

{% hint style="info" %}
Замените "**DIALPLAN-APP-1B2B846E"** на Ваш идентификатор провайдера.
{% endhint %}

Сохраните изменения.

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2F4Xd0MbLFGjTjxrzBPKRj%2FextensionsFileCode2.jpg?alt=media&amp;token=e0e3ff4a-fa54-4930-86e3-35c4b4830f8b" alt=""><figcaption><p>Редактирование файла "extensions.conf"</p></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.mikopbx.com/mikopbx/faq/cases/notification-in-telegram.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
