How to create Telegram bot with PHP and host in Heroku

Default featured post

Nowadays, Telegram is one of the most popular messengers. The reason that the app is so popular is because of three reasons,

  • The application is open source
  • It is cross platform supports and works out of the box
  • Bot support

Among the reasons, I believe the third one is so exciting and most important. In Telegram you are allowed to create bot(s) for certain tasks or even for fun and/or experiment. In this post, I explain about how to create a simple Telegram bot and code it with PHP and host it in Heroku cloud application platform.

The first step you should do is to create a bot via Telegram itself. This can be done via interacting with Bot Father. Just click on this link to start interaction with bot father.

You can send various commands to bot father. I have listed the most important ones with their explanations.

  • /newbot → create a new bot
  • /setname → set name for your bot
  • /setdescription → set description for your bot
  • /setcommands → define commands for your bot
  • /setuserpic → set picture for bot (minimum size 512X512)
  • /token → get your access token
  • /revoke → delete access token of bot
  • /deletebot → remove the bot forever

Here, I won’t go through the process of how to create a bot using bot father. It is not a difficult task, and if you are not familiar you can follow the official Telegram guideline in this link,

After creation of your bot, the bot father sends you access token. Token is very important and must be kept and saved in a safe place. Now, the next step is to activate the webhook facility of the bot to be able to automate the task of responding via PHP program. To do so, click on this link and replace [TOKEN] with your token.

After pressing the enter, you should receive a message that webhook activated.

The next step is to create a PHP application on Heroku via this link,

After creating Heroku application, it should be linked to Telegram bot. To do that, just click on this link and replace [TOKEN] and [URL] with your Telegram bot and Heroku URL application.

You should receive a success message. Keep in mind that the URL that is passed should be HTTPS. Fortunately, Heroku supports HTTPS out of the box and therefore, you don’t need to be worry about this part, just make sure the URL you pass has HTTPS.

The next step is to define your bot commands via bot father /setcommands.

After you have done with setting the commands and description, the last part remaining is to clone this repository.

You can change the code based on your need and commands you have defined and push the code to your Heroku repository.

Now if you start interacting with your bot, it should be working fine flawlessly.