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.

14,741 comments

  1. boarding up

    I’m extremely impressed together with your writing abilities as smartly as with the format to your weblog.
    Is this a paid theme or did you modify it yourself? Anyway keep boarding up the nice quality
    writing, it is uncommon to look a nice blog like this one these days..

  2. lisa armstrong makeup avon

    Hello There. I found your blog using msn. This is a really
    well written article. I’ll make sure to bookmark it and come back
    to read more of your useful information. Thanks for the post.
    I’ll certainly return.

    Feel free to surf to my website lisa armstrong makeup avon

  3. locksmiths

    I am regular reader, how are you everybody?

    This post posted at this site is in fact fastidious.

    Feel free to visit my blog post … locksmiths

  4. segredozen.pt

    Hi there! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?

    Stop by my web-site Are edibles legal (segredozen.pt)

  5. Genia

    Oh my goodness! Impressive article dude!
    Thank you so much, However I am encountering issues with your RSS.
    I don’t understand the reason why I am unable to subscribe to it.
    Is there anybody else getting similar RSS problems?

    Anyone that knows the answer can you kindly respond?
    Thanks!!

    My web site: Genia

  6. ghost 2 immobiliser

    Ghost 2 ghost 2 immobiliser 2 is a
    small and weather-proofed immobiliser that can be placed almost anywhere.

    The Ghost is not Thatcham certified, which means it doesn’t have alarm systems.

  7. bridal gown rental

    Photography could be hired any local photo expert. Because so much cost and
    paper get excited about traditional regarding wedding
    photography, your friends and relations could be asked to give their
    cameras and take pictures.

    Also visit my blog bridal gown rental

  8. lost spare car Key

    Car technologies have witnessed amazing innovations your last many years.
    Modern engineering has enabled lost spare car Key designers to incorporate unique features into today’s automobiles.

  9. Leticia

    I do believe all of the ideas you have presented for
    your post. They are very convincing and can definitely work.
    Nonetheless, the posts are too quick for starters. May you please lengthen them a bit from subsequent time?
    Thanks for the post.

    Here is my web-site … adhd in adults medication (Leticia)

  10. http://iklanbisnisindonesia.com/__media__/js/netsoltrademark.php?d=www.washersanddryers.co.ukproduct-categorywashing-machines

    I know this if off topic but I’m looking into starting my own blog and was curious what all
    is required to get setup? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet smart so I’m not 100% sure.

    Any suggestions or advice would be greatly appreciated.
    Kudos

    Feel free to surf to my homepage http://iklanbisnisindonesia.com/__media__/js/netsoltrademark.php?d=www.washersanddryers.co.uk%2Fproduct-category%2Fwashing-machines%2F

  11. adhd treatment options

    I really like what you guys tend to be up too. Such clever work and coverage!
    Keep up the very good works guys I’ve included you guys to my own blogroll.

    Stop by my web blog adhd treatment options

  12. Treating Adhd in adults

    I’m really enjoying the theme/design of your web site. Do you ever run into any web browser compatibility issues?

    A few of my blog audience have complained about my site not working correctly
    Treating Adhd in adults Explorer but looks great in Safari.
    Do you have any solutions to help fix this problem?

  13. electricians near to me

    I’m really loving the theme/design of your website.
    Do you ever run into any web browser compatibility issues?
    A number of my blog audience have complained about my site
    not working correctly in Explorer but looks great in Firefox.
    Do you have any advice electricians near to me help fix this issue?

  14. electrician

    Hello, yeah this paragraph is really pleasant and I have learned lot of things from it concerning blogging.
    thanks.

    Check out my blog post: electrician

  15. glass replacement

    If you are going for best contents like I do, only go to see this web site every day because it offers feature contents,
    thanks

    Check out my blog glass replacement

  16. Devin Holiman

    For most up-to-date information you have to visit the web and on web I found this website as
    a best website for most recent updates.

    Here is my website … 대전휴게텔사이트

  17. Charla

    I’ll immediately grab your rss feed as I can’t in finding your email subscription link or
    e-newsletter service. Do you’ve any? Kindly permit me understand in order that I could subscribe.
    Thanks.

    My web-site … Charla

  18. Danelle Stacy

    Wow, this piece of writing is fastidious, my sister is analyzing these
    kinds of things, so I am going to let know her.

    my blog post … 강남키스방사이트

  19. Alignment System

    Hello, Neat post. There’s an issue with your site in internet explorer, could check
    this? IE nonetheless is the market leader and a big section of folks will pass
    over your magnificent writing due to this problem.

    my page Alignment System

Leave a Reply

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