Codeconia -Learn Programming

Send message to a Telegram channel using PHP

Today we are going to make a telegram bot that will send messages to a telegram channel using PHP.

In order to be able to do so, you will have first to

  • Create a Telegram Channel (public now)
  • Create  a telegram bot using botfather
  • Set the bot as an administrator in your channel

Now you can able to send message to message to your telegram channel by HTTP GET method by using the following link

https://api.telegram.org/bot[BOT_API_KEY]/sendMessage?chat_id=[MY_CHANNEL_NAME]&text=[MY_MESSAGE_TEXT]
  • [BOT_API_KEY] – Replace with your API Key generated by BotFather when you created your bot
  • [MY_CHANNEL_NAME] –  the handle of your channel (e.g. @yourchannelname)
  • [MY_MESSAGE_TEXT] – is the message you want to send

 

So let’s make it using PHP 

$apiToken = "my_bot_api_token";

$data = [
    'chat_id' => '@yourchannelname',
    'text' => 'Hello world!'
];

$response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data) );
// Do what you want with result

Now let’s try with a form 

<form action="" method="post">
    <input type="text" name="message">
    <input type="submit" name="submit">
</form>


<?php
    if(isset($_POST['submit']))
    {
        $apiToken = "******";
        $data = [
            'chat_id' => '@*****', 
            'text' => $_POST['message']
        ];
        $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data) );	
    }
?>

 

 

 

Ajith Jojo

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular