Sending Telegram messages using PHP

Fire away those messages with this simple script!

First of all, create bot at @botfather by searching botfather and send him the following command:

/newbot

Fill in the long name and user name for the bot when @botfather is prompting for this.

You will now get back a Bot ID and Hash.
Save this ID and Hash in your PHP file.

$telegrambot='<Bot ID>:<Bot Hash>';

Example:
$telegrambot='7345345735:agADFsfjdfhSGTYJdfafhksdsdrQ';

In telegram send your newly create bot a message and go and fetch the Chat_ID

Browse to the following page using your own telegrambot values:
Please note the part where it says bot in front of your Bot ID!

https://api.telegram.org/bot7345345735:agADFsfjdfhSGTYJdfafhksdsdrQ/getUpdates

Search for the part “Chat” and look for the “ID“.
Place this ID underneath your $telegrambot value in your PHP file.

$telegramchatid=<Chat ID>;

Example:
$telegramchatid=374659345;

Now go and create a page with the current function and code.

<?php
// Telegram function which you can call
function telegram($msg) {
        global $telegrambot,$telegramchatid;
        $url='https://api.telegram.org/bot'.$telegrambot.'/sendMessage';$data=array('chat_id'=>$telegramchatid,'text'=>$msg);
        $options=array('http'=>array('method'=>'POST','header'=>"Content-Type:application/x-www-form-urlencoded\r\n",'content'=>http_build_query($data),),);
        $context=stream_context_create($options);
        $result=file_get_contents($url,false,$context);
        return $result;
}

// Set your Bot ID and Chat ID.
$telegrambot='7345345735:agADFsfjdfhSGTYJdfafhksdsdrQ';
$telegramchatid=374659345;

// Function call with your own text or variable
telegram ("Here is your message!!");
?>

In the end its just 3 lines of code with a small function.
You can place the Bot ID and Chat ID in a config.php file and place the function in a seperate functions.php file. This way you can call this function from all your pages, create API’s and so forth…

When you are done you can message the botfather again to customize your bot with his own profile picture, description, etc.

Good luck!

Was this post helpful?

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *

Deze website gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.