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

  1. PGSLOT

    What’s up to every one, the contents present at this website
    are genuinely awesome for people experience, well, keep up the nice work fellows.

  2. 먹튀검증업체

    Excellent blog you’ve got here.. Itís hard to find high-quality writing like yours nowadays. I truly appreciate individuals like you! Take care!!

  3. www.google.dz

    Because the admin of this web site is working, no question very shortly it will be renowned, due to its feature contents.

  4. see Here Grow Gums Back Naturally

    Pretty nice post. I simply stumbled upon your blog and wished to
    say that I have really loved browsing your weblog posts.
    In any case I’ll be subscribing for your feed and I’m hoping you write once more soon!

  5. 먹튀검증

    Hi, Neat post. There is an issue together with your website in web explorer,
    would test this? IE still is the market leader and a big section of other people will miss your wonderful writing
    because of this problem.

  6. continue reading this

    Hey are using WordPress for your site platform?
    I’m new to the blog world but I’m trying to get started and set up my own. Do you require any coding expertise to make your own blog?
    Any help would be really appreciated!

  7. chatbulate

    Dropped my a random stream hung out was chatting saw they were getting donos for some kind of procedure though
    oh cool so I gave em 150$ chick looks dead in camera and says wow is that
    it? I kid you not pissed me off guess who’s contacting my card and getting
    it back twitch

  8. porn chats

    pornvi caughtcheatingporn jetsonsporn free1080pporn realteenporn freeonlineporn kitchenporn navajoporn dirtytalkingporn sleepoverporn kattleyaporn interactiveporngames
    lilyraderporn straightgayporn blackmalepornstars pornmagazine clownpo…

  9. https://freecamtocamsex.com

    In the age of technology, on-line courting sites help you
    find locals with the identical pursuits. At YesCams, now we
    have users of each age from 18 on up, from all backgrounds, and
    intercourse preference, making it very easy to locate the ultimate intercourse partner for live amateur intercourse cams.
    If you are searching for a website with tons of users searching for grownup fun,
    tons of options, and no hidden fees, then look no further.

    There are some individuals who fear being out in the open, especially in unfamiliar areas (and referred to as agoraphobia) or who concern individuals (like therapists) themselves (and referred to as anthropophobia or sociophobia, the latter being extra of a concern of social situations).
    There are quantity of ways to entry such services, you’ll be able
    to either use a skype application, messenger service, or chat by way of webcam or use an best technique of e-mail.
    When you do have an anxiety or phobia; if you’re feeling more comfortable in speaking
    by writing; if you’re very busy; or want to
    benefit from these other options then converse to a counsellor at Plus
    Guidance who will work with you at figuring out yourself in the best way doable.
    There are other individuals who really feel extra comfortable communicating through the written, somewhat than the spoken phrase.

  10. 먹튀검증사이트

    There are many methods to go about finding
    your true self, one of these is actually connecting on your own physically
    through self-massage. As mentioned earlier, the BLS says how the therapeutic massage industry is projected to raise its quantity of practitioners by 19% approximately
    2018. However, if you work with tall clients or clients of varying height and size,
    you could possibly appreciate a massage table that is certainly over the industry standard.

  11. Rough sex Gifs

    The iconic scene features Biggs’ character
    Jim setting up a webcam in his room so that he can watch Nadia,
    an exchange student, undress. Pornhub has built a safe site that won’t bog you down with viruses, features almost every performer
    and category of smut you can imagine, and, best of all, it’s fast.
    But when it comes to gifting/tipping models, it’s important to keep in mind that the brand still profits
    off of these exchanges. An entrepreneur named Stuart Lawley applied for
    the rights to run .xxx in 2004, and thanks to opposition from the Bush administration and
    nations including Brazil, it still has not been approved.
    For would-be porntreprenuers, there is one catch: ICM’s policies for
    .xxx say that only “sponsored community” domains will actually become live Web sites.
    Now it’s a much more integrated community in many ways.
    How much will you charge per domain name?
    It’s not going to slow down your ability to lock down a name you
    choose. CNET sat down with Seitz last Friday at the .nxt conference, organized by
    longtime ICANN-watcher Kieren McCarthy, where scores of hopeful applicants gathered to figure out how
    to raise money and piece together a compelling application.

  12. 먹튀검증업체

    Oh my goodness! Amazing article dude! Thank you so much, However I am experiencing problems with your RSS. I donít understand why I can’t subscribe to it. Is there anybody else having the same RSS problems? Anyone that knows the answer will you kindly respond? Thanx!!

  13. chatterbaitcams

    Post what you want because at the end of the day the guy that tells
    you it’s slutty is following 100 half naked girls

  14. free live adult chat

    Some girls often pick goals that don’t earn much income during performance of the goal –
    for example, “Anal fuck the wall 10 min”. For example, “Anal fuck the wall 10 min” could
    be one of these, if you also had options like tipping options to speed up
    or slow down. So the HTC One S wins cheapest overall price, but
    the HTC One X gets you a lot of bang for your buck — so I call this category
    a tie between the two One series handsets. Nelson:
    Tough break for The Caustic Siren and Colby Sol, but hopefully we will see these two
    have another crack at it as this was a fantastic
    match up until the ending. It’s feasible that Clemson guard John Simpson will be on the board for the Ravens’ first two picks.
    You should be able to input a number and a description of the goal, which will update for you as people tip.
    Or you can post regular shit – people just like having access
    to private things.

  15. check coverage time

    You made some really good points there. I checked on the web for more info about the issue and
    found most individuals will go along with your views on this web site.

  16. Samara

    Hello colleagues, its enormous article concerning teachingand entirely defined,
    keep it up all the time.

    Here is my site … سئو سایت حرفه ای (Samara)

  17. https://freesexvideocam.com/

    Catfishing’ is where a person adopts a false persona online
    in order to deceive and manipulate people. To be fair,
    there are many people who accuse the new government
    of simply blaming Italy’s woes on impoverished
    outsiders. A company running a centre will be paid up to €40 a day
    for each resident – offering handsome returns for those who keep the costs
    down. He points out that the Mafia are doing good business through the contracts
    awarded for running the migrant centres. In the cafe in Palagonia, tempers are still running extremely high.
    Police arrived at the apartment to discover a scene so shocking that,
    three years later, the place is still boarded up.
    However, while spiritual gurus must sit and listen to birds, I can still refresh
    my brain and jerk off at the same time. Here’s what I’ve got,
    ‘ an unidentified man from Amsterdam wrote while uploading
    eight images of Charlie to the website.

  18. Rummy Online

    I was suggested this web site by my cousin. I’m not sure whether this post is written by him as no one else know such detailed about my trouble.
    You are incredible! Thanks!

  19. Effie

    This design is wicked! You definitely know how to keep a reader amused.
    Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!)
    Great job. I really loved what you had to say, and more than that, how you presented it.
    Too cool!

    Check out my blog … بازارگردی آنلاین – Effie,

  20. Judykam

    [url=http://buytretinoinretina.com/]tretinoin paypal[/url] [url=http://prednisoneprednisolone.com/]prednisone cost[/url] [url=http://levitravardena.com/]can i buy levitra without prescription[/url] [url=http://citamoxifen.com/]nolvadex otc[/url] [url=http://amoxicillindrug.com/]amoxicillin 500mg capsule generic[/url] [url=http://chloroquinelab.com/]chloroquine 200[/url] [url=http://saleviagra.com/]buy viagra online mastercard[/url] [url=http://buyazithromycinzithromax.com/]zithromax 250 mg canada[/url] [url=http://zyloprimallopurinol.com/]zyloprim otc[/url] [url=http://avodartpill.com/]generic dutasteride[/url]

  21. Entertainment

    Great goods from you, man. I have understand your stuff previous to and you’re just too fantastic.

    I actually like what you’ve acquired here, really like
    what you are saying and the way in which you say it.
    You make it entertaining and you still take care of to keep it sensible.
    I can not wait to read much more from you. This is really a wonderful site.

  22. Marie

    Checked some of y’all sex facts & the report came back is that
    y’all not even like that hate to hear It!!

  23. buy cheap windows 7 pro product key

    Hey! This is my first visit to your blog! We are a group of volunteers and starting a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a extraordinary job!

Leave a Reply

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