Notification of sent Drupal 7 forms to telegram bot

Some time ago there was an article on sending web form results to a telegram bot in Drupal 8, today we will remake this module to work in Drupal 7.

I will not describe the process of creating the bot itself and obtaining its token, because it is already in the previous article. Here I will only post the code of the module itself under the seven.

Like last time, we create two module files - .info and .module

In the info file we will write information about the module and the version of the engine

name = "Telegram notification"
description = "Webform notification in telegram."
package = "author"
core = 7.x
; Information added by Drupal.org packaging script on 2017-06-26
version = "7.x-1"
core = "7.x"
project = "telegram_notification"
datestamp = "1498476180"

In the second file we will have the following content

<?php

function telegram_notification_form_alter(&$form, &$form_state, $form_id) {

    if($form['#id'] == '*id_your_webform*'){
        $form['actions']['submit']['#submit'][] = '_telegram_notification_form_submit';
    }
}

function _telegram_notification_form_submit(&$form, &$form_state) {

    # Telegram data
    $telegram_token = 'bot*token_your_bot*';
    $telegram_id_chat = '*chat_id_where_bot_sending_messages*';

    if (!empty($telegram_token) && !empty($telegram_id_chat)) {

        # Form data
        $form_field = $form_state['values']['submitted'];
        $data_result = array(
            'name' => '<b>Name:</b> ' . $form_field['your_name'],
            'email' => '<b>Email:</b> ' . $form_field['your_email'],
            'phone' => '<b>Messages:</b> ' . $form_field['your_messages']
        );
        # Send message
        $message = implode($data_result, '%0A');
        $send_message = fopen("https://api.telegram.org/{$telegram_token}/sendMessage?chat_id={$telegram_id_chat}&parse_mode=html&text={$message}", "r");
    }

}

Простий текст

  • Не дозволено жодних HTML теґів.
  • Рядки й абзаци переносяться автоматично.
  • Адреси вебсторінок та адреси електронної пошти автоматично перетворюються у посилання.
Код мови коментаря.