0 votes
36 views

I am trying to send messages to my telegram bot. Exactly name variable can't allow me to do it.

    $arr = array(
      $phoneFieldset => $phone,
      $nameFieldset => $name,
      $messageFieldset => $message,
    );
    foreach($arr as $key => $value) {
      $txt .= "<b>".$key."</b> ".$value."%0A";
    };
    
    $request = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}";
    
    echo $request;
    
    $sendToTelegram = fopen($request,"r");

The request echo output, when the script fails:

https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123%0AИмя: de%0AСообщение: 123213%0A

Warning: fopen(https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123%0AИмя: de%0AСообщение: 123213%0A): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\nginx\html\scripts\php\send-message-to-telegram.php on line 61 Ошибка. Сообщение не отправлено!

Line 61 is the one containing the fopen().

The request echo output, when the script works:

https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123123%0AСообщение: 1213123%0A

Source Author: Swizi

by (1.4k points)   | 36 views

1 Answer

0 votes

The main problem here is that you need to encode Cyrillic characters to URL entities. You can do that using rawurlencode($txt). See full code below:

    $arr = array(
      $phoneFieldset => $phone,
      $nameFieldset => $name,
      $messageFieldset => $message,
    );
    foreach($arr as $key => $value) {
      $txt .= "<b>".$key."</b> ".$value."%0A";
    };

    $txt = rawurlencode($txt)  // To encode cyrillic entities

    $request = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}";
    
    echo $request;
    
    $sendToTelegram = fopen($request,"r");

P.S. Taken from @ed-lucas comment for others who will search for answer.

Credit to: wowkin2

by (2.2k points)  

Related questions

0 votes
1 answer
0 votes
1 answer
+2 votes
0 answers
asked Jun 17, 2020 by noor (1.1k points) | 35 views
+1 vote
1 answer
asked Oct 4, 2020 by toheed (1.4k points) | 104 views
+2 votes
0 answers
+3 votes
1 answer
asked Mar 30, 2020 by toheed (1.4k points) | 68 views
0 votes
1 answer
+2 votes
0 answers
Welcome to Givemeans.net here you can ask questions and get the answers from other members of the community.
143 questions
123 answers
43 comments
159 users