Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a message to a Telegram bot using PHP

I'm trying to send a message to a Telegram Bot using CURL in this PHP code ...

 <?php
  $botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";

  $website="https://api.telegram.org/bot".$botToken;
  $chatId=1234567;  //Receiver Chat Id
  $params=[
      'chat_id'=>$chatId,
      'text'=>'This is my message !!!',
  ];
  $ch = curl_init($website . '/sendMessage');
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  $result = curl_exec($ch);
  curl_close($ch);
?>

The code runs with no error but no message is shown in my destination Telegram bot.

The token is what the BotFather give me when I created my destination Telegram bot (Use this token to access the HTTP API: <MY_DESTINATION_BOT_TOKEN>)

Any suggestion will be appreciated ...

like image 433
Cesare Avatar asked Sep 01 '25 04:09

Cesare


1 Answers

I've solved .... In my original code there were two errors, one in the code and one due on a Telegram feature that I didn't know: actually, telegram bot to bot communication is not possible as explained here Simulate sending a message to a bot from url

So my code revised is the follow

 <?php
  $botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";

  $website="https://api.telegram.org/bot".$botToken;
  $chatId=1234567;  //** ===>>>NOTE: this chatId MUST be the chat_id of a person, NOT another bot chatId !!!**
  $params=[
      'chat_id'=>$chatId, 
      'text'=>'This is my message !!!',
  ];
  $ch = curl_init($website . '/sendMessage');
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  $result = curl_exec($ch);
  curl_close($ch);
?>

In this way all works fine!

like image 114
Cesare Avatar answered Sep 02 '25 18:09

Cesare