Sending form results to Telegram bot

In this short article, we will continue the topic of transferring data to a telegram bot. This time we will accept the data from the usual form on the site.

Let's immediately omit the moment of creating a bot and agree that we already have it, as well as the chat ID for sending a message and the token of the receiving bot.

In addition to submitting text fields in this form, we will also submit an attached image.

This method was peeped at the resource smartlanding.biz and here will be its summary.

In the root of the site we will create a telegram folder with js, php and tmp folders

<form id="form-contact" method="POST" class="contact-form" autocomplete="off" enctype="multipart/form-data">
  <p class="contact-form__title">Request a callback and our consultant will contact you</p>
  <div class="preloader"></div>
  <p class="contact-form__message"></p>
  <div class="contact-form__input-wrapper contact-form__input-wrapper_name">
    <input name="name" type="text" class="contact-form__input contact-form__input_name" placeholder="Name">
  </div>
  <div class="contact-form__input-wrapper contact-form__input-wrapper_phone">
    <input name="phone" type="tel" class="contact-form__input contact-form__input_phone" placeholder="Phone number">
  </div>
  <div class="contact-form__input-wrapper">
    <input type="file" name="files[]" id="contact-form__input_file" class="contact-form__input contact-form__input_file" multiple>
    <label for="contact-form__input_file" class="contact-form__file-button">
      <span class="contact-form__file-text">Choice file</span>
    </label>
  </div>
  <input name="theme" type="hidden" class="contact-form__input contact-form__input_theme" value="Application from the site *Sitename*">
  <button type="submit" class="contact-form__button">Send</button>
</form>

To send requests without reloading, we will use ajax and jquery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="/telegram/js/telegram.js"></script>

In the folder telegram/js, create a file telegram.js with the contents

(function ($) {
  $(".contact-form").submit(function (event) {
    event.preventDefault();
 
    let successSendText = "Message sent successfully";
    let errorSendText = "Message not sent. Try again!";
    let requiredFieldsText = "Fill in the fields with your name and phone number";
 
    let message = $(this).find(".contact-form__message");
 
    let form = $("#" + $(this).attr("id"))[0];
    let fd = new FormData(form);
    $.ajax({
      url: "/telegram/php/sender.php",
      type: "POST",
      data: fd,
      processData: false,
      contentType: false,
      beforeSend: () => {
        $(".preloader").addClass("preloader_active");
      },
      success: function success(res) {
        $(".preloader").removeClass("preloader_active");
 
        // View response status if error
        // console.log(res);
        let respond = $.parseJSON(res);
 
        if (respond === "SUCCESS") {
          message.text(successSendText).css("color", "#21d4bb");
          setTimeout(() => {
            message.text("");
          }, 4000);
        } else if (respond === "NOTVALID") {
          message.text(requiredFieldsText).css("color", "#d42121");
          setTimeout(() => {
            message.text("");
          }, 3000);
        } else {
          message.text(errorSendText).css("color", "#d42121");
          setTimeout(() => {
            message.text("");
          }, 4000);
        }
      }
    });
  });
})(jQuery);

And now we will create a processing file sender.php in the folder telegram/php

<?php
 
    // Bot token
    const TOKEN = '341996777:AAHbnuvQib-vHU47i-6hbUrCU9D-qHYekxc';
     
    // Chat ID 
    const CHATID = '-209253141';
     
    // An array of valid file type values.
    $types = array('image/gif', 'image/png', 'image/jpeg', 'application/pdf');
     
    // Maximum file size in kilobytes
    // 1048576; // 1 МБ
    $size = 1073741824; // 1 ГБ
 
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
     
      $fileSendStatus = '';
      $textSendStatus = '';
      $msgs = [];
       
      // Check if the fields with the name and phone number are empty
      if (!empty($_POST['name']) && !empty($_POST['phone'])) {
         
        // If not empty, then validate these fields and save and add to the body of the message. The minimum for the test is as follows:
        $txt = "";
         
        // Name
        if (isset($_POST['name']) && !empty($_POST['name'])) {
            $txt .= "Name: " . strip_tags(trim(urlencode($_POST['name']))) . "%0A";
        }
         
        // Phone number
        if (isset($_POST['phone']) && !empty($_POST['phone'])) {
            $txt .= "Phone: " . strip_tags(trim(urlencode($_POST['phone']))) . "%0A";
        }
         
        // Don't forget the subject line
        if (isset($_POST['theme']) && !empty($_POST['theme'])) {
            $txt .= "Themes: " . strip_tags(urlencode($_POST['theme']));
        }
     
        $textSendStatus = @file_get_contents('https://api.telegram.org/bot'. TOKEN .'/sendMessage?chat_id=' . CHATID . '&parse_mode=html&text=' . $txt); 
     
        if( isset(json_decode($textSendStatus)->{'ok'}) && json_decode($textSendStatus)->{'ok'} ) {
          if (!empty($_FILES['files']['tmp_name'])) {
         
              $urlFile =  "https://api.telegram.org/bot" . TOKEN . "/sendMediaGroup";
               
              // File upload path
              $path = $_SERVER['DOCUMENT_ROOT'] . '/telegram/tmp/';
               
              // Loading a file and displaying a message
              $mediaData = [];
              $postContent = [
                'chat_id' => CHATID,
              ];
           
              for ($ct = 0; $ct < count($_FILES['files']['tmp_name']); $ct++) {
                if ($_FILES['files']['name'][$ct] && @copy($_FILES['files']['tmp_name'][$ct], $path . $_FILES['files']['name'][$ct])) {
                  if ($_FILES['files']['size'][$ct] < $size && in_array($_FILES['files']['type'][$ct], $types)) {
                    $filePath = $path . $_FILES['files']['name'][$ct];
                    $postContent[$_FILES['files']['name'][$ct]] = new CURLFile(realpath($filePath));
                    $mediaData[] = ['type' => 'document', 'media' => 'attach://'. $_FILES['files']['name'][$ct]];
                  }
                }
              }
           
              $postContent['media'] = json_encode($mediaData);
           
              $curl = curl_init();
              curl_setopt($curl, CURLOPT_HTTPHEADER, ["Content-Type:multipart/form-data"]);
              curl_setopt($curl, CURLOPT_URL, $urlFile);
              curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
              curl_setopt($curl, CURLOPT_POSTFIELDS, $postContent);
              $fileSendStatus = curl_exec($curl);
              curl_close($curl);
              $files = glob($path.'*');
              foreach($files as $file){
                if(is_file($file))
                  unlink($file);
              }
          }
          echo json_encode('SUCCESS');
        } else {
          echo json_encode('ERROR');
          // 
          // echo json_decode($textSendStatus);
        }
      } else {
        echo json_encode('NOTVALID');
      }
    } else {
      header("Location: /");
    }

As a result, when submitting a form from the site, data will be sent to the chat or groups from the telegram bot.

It is worth noting right away that if something does not work out for you, do not despair.

First of all, we look at whether errors are displayed with the text that we wrote in the script or handler file. If there are no errors, check the output of the script by uncommenting the line

console log(res);

our script and see if the browser console writes anything.

If the console does not display anything, an empty string, most likely an error in the location of the files. Try to place the telegram folder immediately at the top level of the site folder, without nesting in subfolders.

hasmiah (not verified)
Thu, 01/18/2024 - 14:15

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.