Yet another option to send notifications from Asterisk to Telegram


    Good afternoon, dear harazhiteli. Recently, several articles on the integration of Asterisk and Telegram have appeared on the hub: one , two .

    I propose to consider another option.

    For some reason, these solutions did not suit me.

    Something for objective reasons: the use of telegram-cli, according to reviews, is not very stable, and to use it you need to log in to the server under your telegram account, it seemed to me not too convenient and correct.

    Something subjective: I did not want to use php as in option 1 and force employees to write their numbers to the bot.

    Well, of course, it’s much more interesting to reinvent the wheel yourself, nobody canceled the pleasure of the process of realizing your idea :)

    Initial data:

    The client has several remote managers with mobile phones, the call goes to Asterisk to a common SIP number, after which it is forwarded to the mobile managers via a sip-trunk. With this scheme, there are quite a few amenities - managers are not required to sit in the office, but can work, which is called “in the field” (@boffart sorry for plagiarism :). However, there is one inconvenience that outweighs all the pros - the inability to see the original Callerid client.

    To circumvent this inconvenience, it was decided to send to the general group of managers in the telegram a message like “Incoming call from number $ {CALLERID (num)} to number $ {EXTEN}”.

    So let's get started:

    A telegram bot is required to send call notifications to the group. Registering a new bot is a rather trivial process and is very well described here.

    After registering a bot, we will write a small python script that will be called from Asterisk and send us notifications in the telegram.

    The version of python used is 2.7.

    Since I implemented everything on Centos 6.6, which uses python 2.6 out of the box (you can check your python version by typing python -V in the console), for starters we need to install python 2.7. There are two options: installation from rpm packages and from source. Consider both.

    Installation from source

    Update the system and supply the necessary packages:
    yum -y update
    yum groupinstall -y 'development tools'
    yum install -y zlib-dev openssl-devel sqlite-devel bzip2-devel
    yum install xz-libs

    Download the source code for python 2.7:
    xz -d Python-2.7.6.tar.xz
    tar -xvf Python-2.7.6.tar

    Configuration and installation of python 2.7:
    cd Python-2.7.6
    ./configure --prefix=/usr/local/bin (префикс можно ставить любой удобный вам, к примеру импортировать его из переменной $HOME)
    make altinstall

    Install pip 2.7:
    Перед установкой необходиом скачать и установить setuptools
    wget --no-check-certificate
    tar -xvf setuptools-1.4.2.tar.gz
    cd setuptools-1.4.2
    python2.7 install
    и сам pip
    curl | python2.7 -

    Installation from rpm

    Add rpm packages, install python, pip:
    rpm -ivh
    rpm -ivh
    yum clean all
    yum install python27
    yum install python27-pip

    Python of the required version is installed, install the library for working with the Telegram API:

    pip2.7 install pyTelegramBotAPI==2.3.1

    And directly the script code itself:
    # -*- coding: utf-8 -*-
    import telebot
    import sys
    token = 'INSERT_YOUR_TOKEN'  # Вводим свой телеграм API токен
    group_id = -123456789  # Вводим id группы, куда надо слать сообщения (обратите внимание, что id группы - отрицательное целое число)
    bot = telebot.TeleBot(token, skip_pending=True)
    # Ловим команду старта при старте без аргументов (первый старт)
    @bot.message_handler(func=lambda message: True, commands=['start'])
    def start(message):
        if len(sys.argv) != 1:
        bot.send_message(, "ID чата: " + str(
    # Если были переданы три аргумента, то возвращаем в чат сообщение
    if len(sys.argv) == 4:
        callerid = str(sys.argv[1])
        exten = str(sys.argv[2])
        redirectnum = str(sys.argv[3])
        bot.send_message(group_id, "Вызов с номера " + callerid + "\nна номер " + exten + "\nпереадресован на номер " + redirectnum)
    # Если аргумента нет, то считаем первым стартом и запускаем в режиме полинга
    if len(sys.argv) == 1:

    The thing remained for small: before receiving an incoming call, call the script from Asterisk dialplan. I have it, for example, this:

    vim /etc/asterisk/extensions.conf:
    exten => 84951234567,1,Set(CALLERID(num)=+7${CALLERID(num)})
    same => n,Answer()
    same => n,Playback(hello)
    same => n,Set(REDIRECTNUM=+79261234567)
    same => n,System(/etc/asterisk/redirector/ ${CALLERID(num)} +7${EXTEN:1} ${REDIRECTNUM})
    same =>n,Dial(SIP/mytrunk/mymobilenumer&SIP/mytrunk/mymobilenumber2,40,tTm(default))
    same =>n,Hangup()

    With an incoming call, managers receive a similar message to the telegram group: image

    For convenience, the Habrovsk people designed everything on github .

    In conclusion, I would like to note that it was very amusing to implement this project, and the result was quite good. Maybe someone will find this implementation useful.

    Posted by Asterisk'er, Southbridge Mikhail Komov.

    Also popular now: