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,808 comments

  1. Lynell Detwiler

    Very energetic post, I loved that a lot. Will there be
    a part 2?

    Feel free to surf to my web page 토토

  2. car Key online

    I think everything wrote was very logical. But, what about this?
    what if you added a little information? I am not suggesting your information is not good., but suppose you
    added a headline that makes people want more? I mean Creating Telegram Bot using PHP : Webhook and Localhost using Ngrok – Dryan Christoph Personal Website is a little plain. You might
    peek at Yahoo’s front page and note how they write article headlines to grab
    viewers to open the links. You might add a related video or a picture or two to get readers excited about everything’ve written. In my
    opinion, it might bring your posts a little livelier.

    Feel free to visit my web page – car Key online

  3. electricians near me

    Hi, I do think this is an excellent site. I stumbledupon it 😉 I will return yet
    again since I book marked it. Money and freedom is the best
    way to change, may you be rich and continue to help others.

    Here is my web blog electricians near me

  4. Thanh

    Howdy just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading correctly.

    I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same
    results.

    my web-site … car key cutting cost [Thanh]

  5. lipstick

    Do you have a spam issue on this website; I also am a blogger, and I was wanting to know your situation; we
    have created some nice procedures and we are
    looking to exchange solutions with other folks, please shoot me an email if interested.

    Feel free to surf to my web-site; lipstick

  6. Ilse Kroger

    Link exchange is nothing else except it is just placing the other person’s weblog link on your page at
    suitable place and other person will also do same for you.

    My web page … shortyzone.com

  7. best cbd Calming dog treats

    We are a group of volunteers and starting a new scheme in our community.
    Your site offered us with valuable information to work on. You’ve done an impressive job and our entire community will be thankful to you.

    My website; best cbd Calming dog treats

  8. autowatch ghost 2

    The autowatch ghost 2 car immobiliser operates by communicating with your vehicle’s ECU unit, and therefore is completely
    inaudible. This means that thieves can’t easily copy your keys or take your car’s
    ECU making them a prime victim of theft.

  9. Automotive locksmith

    Perhaps you already carry far several keys, including keys towards office,
    auto, gym lockers, filing cabinets and lots more.

    Do you absolutely need the bother of one more key?

    Electronic Entry tresses are far simpler.

    my blog post – Automotive locksmith

  10. best Cbd calming dog Treats

    I blog frequently and I really appreciate your information. The article
    has really peaked my interest. I will book mark your blog and keep checking for new information about once per
    week. I subscribed to your RSS feed as well.

    Stop by my website … best Cbd calming dog Treats

  11. how much does a psychiatrist cost uk

    Hiya! I know this is kinda off topic however , I’d figured I’d ask.
    Would you be interested in trading links or maybe guest writing a blog article or vice-versa?
    My blog covers how much does a psychiatrist cost uk lot of the same topics as yours and I think
    we could greatly benefit from each other. If you happen to be interested feel
    free to send me an e-mail. I look forward to hearing from you!

    Great blog by the way!

  12. avonuk

    Hi there to every body, it’s my first pay a quick visit
    of this weblog; this blog carries awesome and in fact excellent material
    in favor of visitors.

    Here is my blog – avonuk

  13. lipsticks uk

    At this time it sounds like Drupal is the top blogging platform available right
    now. (from what I’ve read) Is that what you’re using on your blog?

    my blog post – lipsticks uk

  14. lost Spare Car key

    Another popular YouTube video is ensure where shed to open a lost Spare Car key door which
    isn’t locked therefore do it by employing a tennis ball.

    The way the video paves the way is by punch just a little hole
    going directly to the middle of the bowling ball.

  15. Locks Smith

    Attractive section of content. I simply stumbled upon your web site and
    in accession capital to assert that I get in fact enjoyed account your weblog posts.
    Any way I will be subscribing for your feeds or even I fulfillment you access consistently
    fast.

    my page Locks Smith

  16. Ipv6 Proxy Buy

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

    Here is my page; Ipv6 Proxy Buy

  17. Jerold Haugh

    Hi, its good post about media print, we all know media is a impressive
    source of information.

    Here is my blog – 토토업체

  18. private psychiatry uk

    I got this web page from my pal who shared with me concerning this website and at the moment this time I am browsing this website and
    reading very informative posts at this time.

    Feel free to visit my site – private psychiatry uk

  19. Aleisha Le Messurier

    Magnificent goods from you, man. I’ve understand your stuff previous to and you
    are just too magnificent. I really like what
    you have acquired here, really like what you’re stating and the way in which you say it.
    You make it entertaining and you still take care of to keep it wise.
    I can not wait to read far more from you. This is
    actually a tremendous web site.

    My blog post; 먹튀검증

  20. double glazing replacement glass

    Nice post. I was checking continuously this blog and I am
    impressed! Extremely useful info specifically the last part 🙂 I care for such information a lot.
    I was seeking this certain information for a long time.

    Thank you and best of luck.

    my webpage double glazing replacement glass

  21. Renate

    Hello, I think your website might be having browser compatibility issues.
    When I look at your blog site in Ie, it looks fine but when opening
    in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, excellent blog!

    Look at my web page … Renate

  22. private Psychiatrist uk

    It’s a pity you don’t have a donate button! I’d certainly donate to this excellent blog!
    I guess for now i’ll settle for book-marking and
    adding your RSS feed to my Google account. I look forward to brand new
    updates and will share this blog with my Facebook group.
    Talk soon!

    Feel free to visit my homepage private Psychiatrist uk

Leave a Reply

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