Creating Telegram Bot using PHP : Webhook and Localhost using Ngrok

In this post I will tell you about how to create a fully functional Telegram bot using PHP, webhook, and ngrok. To be able to make a bot using Webhook method, you need to understand the basic concept of Webhook and Long Polling method. I have explained this very clearly in this post : Basic Concept of Telegram Bot API. In this tutorial, you can build a webhook in your local server, so you don’t need to have a hosted server in the internet.

Required Apps

To create a Telegram bot using webhook method and PHP, you need to have :

  1. Telegram App. Download link : telegram.org.
  2. Ngrok. Download link : ngrok.com/download.
  3. PHP server (preferably XAMPP). Check out my post about this : 1st Web Development Tutorial : Deploying XAMPP Server in Windows.

Using webhook method, we usually need to have a hosted server running in the internet.

But wait, in this tutorial, you don’t need to worry about having a hosted site, because it can be replaced with ngrok in our local server. I’ll explain it later.

Create Bot via Botfather

  1. Open your Telegram app, preferred on desktop, search for @BotFather.
  2. Click on /start on the bottom of the chat
  3. Click on /newbot to create a new bot. BotFather will then ask you to type bot name and username.
  4. After picking your bot username, you will receive a chat containing your bot token.
    Creating Telegram Bot
  5. Congratulations, you just created a bot. But surely, without further anticipation, your bot will be useless since it has no soul.

Build the Script

  1. Start your apache web server on the localhost. If you don’t know how to do this, you can read this simple post : 1st Web Development Tutorial : Deploying XAMPP Server in Windows.
  2. To make your bot alive, create a new project in your workspace. If you don’t know how to do it, I suggest you to take a look at this post : 1st Web Development Tutorial : Deploying XAMPP Server in Windows.
    Name the folder of your project webhook. Inside the folder, create a new php file called index.php.
  3. Copy and paste this php code into your index.php file.
    <?php
    $content = file_get_contents("php://input");
    if($content){
        $token = '<YOUR BOT TOKEN>';
        
        $apiLink = "https://api.telegram.org/bot$token/";
        
        echo '<pre>content = '; print_r($content); echo '</pre>';
        $update = json_decode($content, true);
        if(!@$update["message"]) $val = $update['callback_query'];
        else $val = $update;
        
        $chat_id = $val['message']['chat']['id'];
        $text = $val['message']['text'];
        $update_id = $val['update_id'];
        $sender = $val['message']['from'];
        ?>
        <b>There is a message :</b>
        <br /><br />
        <b>Username : </b> <?php echo $sender['username']; ?> <br />
        <b>Sender's Name : </b> <?php echo $sender['first_name'].' '.$sender['last_name']; ?> <br />
        <b>Text Message : </b> <?php echo $text; ?> <br /><br />
        <?php 
        
        file_get_contents($apiLink . "sendmessage?chat_id=$chat_id&text=You just sent ".$text);
        echo 'Response sent.<br /><br />';
    } else echo 'Only telegram can access this url.';
    
    ?>

    Replace <YOUR BOT TOKEN> on line 4 with your bot token sent from BotFather earlier.

  4. Now let’s try to run the script. Open your browser, open url localhost/webhook. You should see something like this :
    testing webhook telegram bot 1

Set up ngrok

The basic concept of ngrok is very simple. With ngrok, you will be able to get a public address for your local website. Basically, it will make your localhost accessible from the internet.

  1. First, let’s download ngrok here.
  2. Extract the files anywhere in your computer.
  3. Open Windows Command Prompt (cmd), then point to the folder location of the downloaded ngrok app.
  4. Inside the folder, type : ngrok.exe http 80
    set up ngrok
  5. If successful, you will see something like this :
    ngrok started
  6. Note the forwarding section. Now lets check it out on the browser. In my case, I will type https://d36fa284.ngrok.io/webhook.
  7. Yass, it is so simple to make your localhost accessible through the internet. You can definitely access the url anywhere from the internet. Basically, ngrok has turned your localhost into a public site, in my case it is accessible through https://d36fa284.ngrok.io. You can also check your other sites inside htdocs folder by accessing https://d36fa284.ngrok.io/<any project folders inside htdocs>.
  8. Now, I need to tell Telegram that we have a running server running on https://d36fa284.ngrok.io. Open browser, and type :

    https://api.telegram.org/bot<YOUR BOT TOKEN>/setwebhook?url=https://d36fa284.ngrok.io/webhook/

    Replace <YOUR BOT TOKEN> with your bot token. Don’t miss the trailing slash.

    Also you need to replace d36fa284.ngrok.io with url according to your ngrok ‘Forwarding’ section.

  9. It’s done. I everything is correct, you should see something like this :
    set webhook telegram bot
  10. Let’s open the log provided by ngrok. Open up localhost:4040 in your browser.
    ngrok log url
  11. Now every time someone send a chat to your bot, the bot will reply. Check it out.
    test bot webhook

That’s all about how to create a fully functional Telegram bot using webhook, but no need to worry about having a public site to place the webhook url. You may edit the PHP script to make the bot reply any other responses as you wish. If you have any question or difficulties, feel free to ask in the comment section.

324 comments

  1. Ashleigh

    Why visitors still make use of to read news papers when in this technological world everything
    is existing on web?

  2. Louanne

    Good day! I could have sworn I’ve been to this website before but
    after looking at some of the posts I realized it’s new to me.
    Regardless, I’m certainly happy I stumbled upon it and I’ll
    be book-marking it and checking back frequently!

  3. ver tweak de jailbreak de instagram privado

    Thank you for any other informative blog. The place else may just I get that kind of information written in such an ideal way?
    I have a venture that I’m just now working on, and I’ve
    been at the glance out for such information.

  4. 管式炉

    I’ve been browsing online more than three
    hours today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. In my view, if
    all website owners and bloggers made good content as you did,
    the internet will be a lot more useful than ever before.

  5. Brian

    Hi there, yup this piece of writing is really good and I have
    learned lot of things from it on the topic of blogging.
    thanks.

  6. ver videos privados de instagram

    If some one wants to be updated with hottest technologies therefore he must be visit this website and be up to date every
    day.

  7. Dian

    I blog frequently and I seriously appreciate your content.
    Your article has really peaked my interest. I am going to take a note of your website and keep checking for new information about once
    per week. I subscribed to your Feed as well.

  8. Maurine

    I’m curious to find out what blog system you’re working with?
    I’m having some small security problems with my latest site and I’d like
    to find something more risk-free. Do you have any suggestions?

  9. 美国华人快递

    Hey there! Quick question that’s entirely off topic.
    Do you know how to make your site mobile friendly?

    My blog looks weird when browsing from my iphone. I’m trying to find a template or plugin that might be able to correct this
    problem. If you have any recommendations, please share.
    Appreciate it!

  10. Gregg

    Excellent post. I used to be checking constantly this blog and I am inspired!
    Extremely useful information specially the closing section 🙂 I maintain such info a lot.
    I used to be seeking this particular information for a very lengthy time.
    Thanks and best of luck.

  11. Sabina

    These are really enormous ideas in about blogging. You have touched some
    pleasant factors here. Any way keep up wrinting.

  12. Melvina

    I think the admin of this site is actually working hard in favor of his site, as here every stuff is quality
    based data.

  13. Lithium Battery Lab Line

    I do believe all of the ideas you have presented on your
    post. They’re very convincing and will definitely work.

    Still, the posts are very brief for newbies.
    May just you please lengthen them a little from next time?
    Thank you for the post.

  14. Brianne

    My family members every time say that I am killing my time
    here at net, but I know I am getting know-how daily by
    reading thes nice content.

  15. Alejandrina

    I am genuinely thankful to the owner of this web site who has shared this fantastic
    post at at this time.

  16. Keira

    This is my first time pay a visit at here and i
    am truly happy to read all at one place.

  17. Joni

    Excellent post. I used to be checking constantly this blog and I’m impressed!
    Extremely helpful info specially the remaining phase 🙂 I maintain such information much.

    I used to be seeking this certain information for a very lengthy time.
    Thank you and good luck.

  18. Carri

    Great post however , I was wanting to know if you could write a litte more on this topic?

    I’d be very thankful if you could elaborate a little bit further.
    Kudos!

  19. Patrick

    Greetings from Idaho! I’m bored to tears at work so I decided to check out your
    blog on my iphone during lunch break. I really like the
    info you present here and can’t wait to take a look when I get
    home. I’m amazed at how fast your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyhow, superb blog!

  20. Annette

    Piece of writing writing is also a fun, if you be acquainted with then you can write otherwise
    it is difficult to write.

  21. Berniece

    It’s genuinely very difficult in this full of activity life to listen news on TV, thus I only
    use web for that reason, and take the newest news.

Leave a Reply

Your email address will not be published. Required fields are marked *