MVTHEME
Sending messages from Contact Form 7 to Telegram without plugins
WordPress

Sending messages from Contact Form 7 to Telegram without plugins

Millenium, December 20, 2022

Hello, I would like to show you how to quickly and easily disable the standard sending of emails in Contact Form 7 and redirect all messages to Telegram.

First of all, we need to create a telegram bot. To do this, we need to find the most important bot, this is BotFather, for this, we write @botfather in the search bar. Then select it and press the “Start” button. After that, we will see a list of commands. Now we need to enter the /newbot command. After that, we must enter its name in the line for example: wpcf7_bot. Next, we need to come up with a nickname for him that ends with “_bot”, that is, you can enter the same name again. If everything is fine, then after that, we should receive a message where the token will be indicated. The next step is adding the bot to the shared chat. To do this, we need to create a new group and add our bot – @wpcf7_bot.

Further, in the general chat of this group, you also need to enter the command /join @wpcf7_bot.

Now we already have almost everything, and only the chat id is missing. To do this, enter the following url in the address bar of the browser: https://api.telegram.org/botXXXXXXXXXXXXXXXXXXXXXXX/getUpdates, where instead of “XXXX…” you need our token. After that, we should see the json object. In this object, we are interested in the “id” key, and it must necessarily begin with a minus, for example: “-269866422”. If this object does not appear, then you need to duplicate the /join @wpcf7_bot command again.

Now we need to substitute our token and chat id into the $userId and $token variables, and add the code itself to the functions.php file.

<?php
// Disable the configuration validator
add_filter( 'wpcf7_validate_configuration', '__return_false' );

// Disable sending mail
add_filter('wpcf7_skip_mail','__return_true');

// This is the main code that sends messages to Telegram
add_action('wpcf7_before_send_mail', 'cf7_send_telegram', 10, 3);
function cf7_send_telegram($contact_form, $abort, $submission)
{
    if ($submission) {
        $form_data = $submission->get_posted_data();

        $message = '<b><u>* New message form CF7 *</u></b>%0A%0A';

        foreach ($form_data as $key => $value) {
           $message .= "<b>".ucfirst(str_replace('your-', '', $key)).": </b> ".$value."%0A"; 
        }

        $userId = '-123456789';
        $token = '987654321:AAHTT7giZU1sdfdfgt_AHp1F358';

        // file_get_contents('https://api.telegram.org/bot'. $token .'/sendMessage?chat_id='. $userId .'&text=' . $message . '&parse_mode=markdown');

        wp_remote_fopen('https://api.telegram.org/bot' . $token . '/sendMessage?chat_id=' . $userId . '&text=' . $message . '&parse_mode=html');
    }
}

Thank you for your attention.

Leave a Reply

Your email address will not be published. Required fields are marked *