Create a Telegram bot & send messages with PHP

Created: December 28, 2021 11:11 PM

This is how you can create a Telegram bot and send messages in 3 easy steps using PHP

Create Telegram bot

To create a Telegram bot you need to:

  • Search for @BotFather in the Telegram app (Mobile or Desktop no difference)
  • Send this message /newbot and follow the instructions to create the bot, it's super easy
  • Get the token and store it somewhere safe, we'll use it in the code to send messages in a bit


Get Chat Id

To get your Chat Id you have to:

  • Send a message to the bot that you just created, for me it's @Test1997Bot
  • Go to your browser and type ""

You'll get a result like this


You need to look for and copy chat → id and that's it, in this example it's 9999999999

Send messages using PHP

Now that we have everything we need let's code

    function sendTelegramMessage($message) {
      $token = '(REPLACE-WITH-YOUR-BOT-TOKEN)'; 
      $chatId = (REPLACE-WITH-YOUR-CHAT-ID);
      $url = '' . $token . '/sendMessage';
      $data = array(
        'chat_id' => $chatId,
        'text' => $message
      $options = array(
        'http' => array(
          'method' => 'POST',
          'header' => "Content-Type:application/x-www-form-urlencoded",
          'content' => http_build_query($data)
      $context = stream_context_create($options);
      $result = file_get_contents($url, false, $context);
      return $result;

To send the message just run the function like this

  sendTelegramMessage('Hello World!');

if you want to learn more you can visit the official docs

... and we're done, easy right.