> 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/voip-gateways/goip4/sms-to-telegram.md).

# SMS в Telegram

Настройка SMS в Telegram для шлюза GoIP4

## Настройки в Telegram <a href="#nastrojki_telegram" id="nastrojki_telegram"></a>

Для начала через чат Telegram следует написать боту [**@BotFather**](https://t.me/BotFather). Этот бот позволит создать и настроить вашего нового бота для интеграции с MIKOPBX.

1. Отправляем боту команду

```
/start
```

2. Команда создания нового бота:

```
/newbot
```

3. Отправляем имя нашего нового бота. К примеру:

```
MIKOPBX_NEW_BOT
```

4. Сохраните значение «**token**»: он понадобится для настройки со стороны АТС.
5. Создайте новую «**группу**».
6. Перешлите любое сообщение из группы боту [@getmypid\_bot](https://t.me/getmyid_bot)
7. Сохраните значение «chat ID», для пользователя значение вида "**190389360"**, для группы - отрицательное, вида: "**-4190389360".**

## Настройки в MikoPBX <a href="#nastrojka_mikopbx" id="nastrojka_mikopbx"></a>

### Приложение Dialplan <a href="#prilozhenie_dialplan" id="prilozhenie_dialplan"></a>

В разделе «**Модули**» - «**Приложения диалплан**» создадите новое приложения, со следующими параметрами:

* "**Название**" - Переслать sms в telegram (произвольное).
* "**Тип кода**" - PHP-AGI
* Программный код:

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

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

$agi = new MikoPBX\Core\Asterisk\AGI();
$message  = str_replace(
    ['n'],
    ["\n"], 
    $argv[1]??"");;
$did      = $agi->request['agi_extension'];
$agi->verbose($message, 3);

$TEXT = "
SMS на номер: $did
От: $message
";

$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){
}
```

{% hint style="info" %}
«**API\_KEY**» - токен телеграм бота

«**CHAT\_ID**» - идентификатор телеграм чата (группы).
{% endhint %}

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2Fgit-blob-064e76cc02ea82b73c59c2acbf702578d3969a96%2FcodeForDialplan%20(1).png?alt=media" alt=""><figcaption><p>Программный код для диалплана</p></figcaption></figure>

\
В адресной строке браузера нужно скопировать идентификатор приложения, он имеет вид: «**DIALPLAN-APP-8B0D0964**»:

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2FijaMKAK519vGzvmbZPcW%2FdialplanNumber.png?alt=media&amp;token=8cb4b4a0-dee4-4965-8620-868784078ddf" alt=""><figcaption><p>Идентификатор приложения диалплана</p></figcaption></figure>

### Кастомизация системных файлов <a href="#kastomizacija_sistemnyx_fajlov" id="kastomizacija_sistemnyx_fajlov"></a>

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. Перейдите к редактированию файла "**/etc/asterisk/extensions.conf",** установите режим **"Добавлять в конец файла".** Используйте следующий код:

```php
[messages-from-goip]
exten => _[0-9*#+a-zA-Z]!,1,AGI(DIALPLAN-APP-8B0D0964.php, "${MESSAGE(body)}")
    same => n,hangup()
exten => _[hit],1,Hangup()
```

{% hint style="info" %}
«**DIALPLAN-APP-8B0D0964**» - в данном коде - это идентификатор приложения. Сохраните изменения.
{% endhint %}

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2FAGu5Eu1uA0QNGEUFLfVR%2FeditExtensionsConfFile.png?alt=media&amp;token=5b91c24b-0943-42a8-89d4-e54198b45b75" alt=""><figcaption><p>Изменения в файле extensions.conf</p></figcaption></figure>

### Провайдер <a href="#provajder" id="provajder"></a>

1. Перейдите в раздел "**Маршрутизация**" -> "**Провайдеры телефонии**". Добавьте нового SIP-провайдера, со следующими параметрами:

* "**Название**" - произвольное
* **"Тип учетной записи"** - Аутентификация по IP адресу, без пароля.
* "**Хост или IP адрес**" - IP-адрес Вашего шлюза

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2FdxjLPD8Oebhbu4lso0BQ%2FnewProviderGOIP4.png?alt=media&amp;token=4beb3893-849c-455b-b09c-82ac8f6e521a" alt=""><figcaption><p>Параметры провайдера</p></figcaption></figure>

2. В "**Расширенные настройки**" -> "**Дополнительные параметры**" пропишите:

```
[endpoint]
message_context = messages-from-goip
```

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2Fgit-blob-a2088ef0ebe7ad421a1165fd3c01e18853e2cd8e%2FadditionalParameters.png?alt=media" alt=""><figcaption><p>Дополнительные параметры</p></figcaption></figure>

## Настройка GoIP <a href="#nastrojka_goip" id="nastrojka_goip"></a>

1. Перейдите в раздел «**Configurations**» - «**SMS**»
2. Для каждого канала CH1 / CH2 … CHN выполните настройку:

* «**SMS to VoIP**» (верхнее) - «**Call Function**»
* «**Call mode**» - «**Mode 1**»
* «**SMS to VoIP**» (нижнее) - укажите номер телефона sim карты

<figure><img src="https://3704471835-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MPK4TuzRBnP7rt8htho-887967055%2Fuploads%2Fgit-blob-73b449807d078eec1fb003e38bf704933855dcee%2Fimage%20(116).png?alt=media" alt=""><figcaption><p>Параметры в GoIP</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/voip-gateways/goip4/sms-to-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.
