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.

5,984 comments

  1. 000 jobs cheats

    It’s actually a nice and helpful piece of information. I’m happy that you shared this helpful info with us.
    Please stay us informed like this. Thanks for sharing.

  2. ajenako.com

    Hey there I am so happy I found your website, I really found you by mistake,
    while I was looking on Google for something else, Anyhow I am here now and would
    just like to say kudos for a marvelous post and a all round entertaining blog
    (I also love the theme/design), I don’t have time to read through it all at the minute but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read much more, Please
    do keep up the fantastic b.

  3. hack para kings of war

    It’s actually a nice and useful piece of information. I am glad
    that you just shared this helpful information with us. Please keep us informed like this.
    Thank you for sharing.

  4. hack para kings of war

    Wow, this article is nice, my sister is analyzing such things,
    thus I am going to inform her.

  5. utility construction machines hacks

    Hi there! Someone in my Myspace group shared this site with us so
    I came to give it a look. I’m definitely enjoying the information. I’m book-marking and will be
    tweeting this to my followers! Excellent blog and wonderful design.

  6. friendzoned 2 cheats

    My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs. But he’s tryiong none
    the less. I’ve been using WordPress on numerous websites for about a year and am concerned about switching to
    another platform. I have heard very good things about blogengine.net.
    Is there a way I can transfer all my wordpress posts
    into it? Any help would be greatly appreciated!

  7. download mod apk gratis

    I am actually grateful to the owner of this web page who has shared this impressive piece of writing at here.

  8. how to hack recharge rc

    Hey there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get
    my blog to rank for some targeted keywords but I’m not
    seeing very good success. If you know of any please share.

    Kudos!

  9. bubble lamp hacks

    Greetings! Very helpful advice in this particular post!
    It is the little changes which will make the largest changes.
    Thanks for sharing!

  10. fantastic city bus simulator cheat codes

    I must thank you for the efforts you have put in penning this website.
    I really hope to see the same high-grade content from you in the future as well.
    In truth, your creative writing abilities has motivated me to get my own website now ;
    )

  11. link two hack apk

    When some one searches for his essential thing, so he/she wants to be available that in detail, so that
    thing is maintained over here.

  12. hack for slots casino slot machines

    I’m gone to tell my little brother, that he should also pay a visit this blog on regular basis to
    take updated from newest reports.

  13. games cleaning hotel rooms mod

    After checking out a handful of the blog posts on your site, I truly appreciate your technique of writing a blog.
    I added it to my bookmark webpage list and will be checking back in the near future.
    Take a look at my web site too and tell me your opinion.

  14. whip simulator hacked apk

    If you would like to increase your experience simply keep visiting this web page and be
    updated with the newest gossip posted here.

  15. free online games hack ios

    I am really enjoying the theme/design of your blog.
    Do you ever run into any web browser compatibility issues?
    A number of my blog visitors have complained
    about my blog not operating correctly in Explorer but looks great in Firefox.
    Do you have any ideas to help fix this issue?

  16. Wendell

    Hi there would you mind sharing which blog platform you’re
    working with? I’m looking to start my own blog in the near future but I’m having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different then most blogs and I’m looking for
    something unique. P.S Apologies for being off-topic but
    I had to ask!

    Here is my homepage … james (Wendell)

  17. baby hazel halloween party hack

    Spot on with this write-up, I truly believe that this web site needs much more attention. I’ll probably be returning to read more,
    thanks for the info!

Leave a Reply

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