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.

266 comments

  1. smellgood stockholm

    Pretty nice post. I just stumbled upon your blog and wished to say that I have truly enjoyed browsing your
    blog posts. After all I will be subscribing to your feed and
    I hope you write again very soon!

  2. skäggolja

    Hello just wanted to give you a quick heads up.

    The words in your content seem to be running off the screen in Internet explorer.

    I’m not sure if this is a formatting issue or something
    to do with internet browser compatibility but I figured I’d post to let you know.
    The design and style look great though! Hope you get the problem resolved soon. Cheers

  3. skäggolja

    The other day, while I was at work, my sister stole
    my iphone and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views.
    I know this is totally off topic but I had to share
    it with someone!

  4. Marguerite

    This post was amazing i try to read your blog very often, and
    you’re constantly coming out with pretty great stuff.
    I embedded this on my facebook, and my followers
    really liked it. Keep up the very good work 🙂

  5. smellgood stockholm

    I loved this post! i actually read your blog very often, and you’re consistently coming out with a lot of great stuff.

    I contributed this on my blog, and my followers adored it.

    I really admire the good work 🙂

  6. skäggolja gör skägg mjuk

    I really liked this post i actually read your blog very often, and you’re constantly coming out with a
    lot of great stuff. I shared this on my facebook, and
    my followers loved it. I really admire the great work 🙂

  7. smellgood.se/

    This design is spectacular! You obviously know how
    to keep a reader entertained. 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!

  8. smellgood.Se/

    hey there and thank you for your info – I’ve definitely picked up anything new from right here.
    I did however expertise some technical issues using this website,
    since I experienced to reload the site many times previous to
    I could get it to load correctly. I had been wondering if your
    web host is OK? Not that I’m complaining, but slow loading instances times will sometimes affect your placement
    in google and could damage your quality score if advertising and marketing with
    Adwords. Anyway I’m adding this RSS to my email and can look out
    for much more of your respective interesting
    content. Ensure that you update this again soon.

  9. Shanon

    I loved this post! i try to read your blog pretty often, and you’re consistently coming out with some great stuff.
    I shared this on my facebook, and my followers adored it.
    I really admire the great work 🙂

  10. Nursery Rhymes

    Very rapidly this website will be famous amid all blogging users, due to it’s fastidious articles or reviews

  11. skäggolja stockholm

    This post was amazing i actually read your blog pretty often, and you’re constantly coming out with a lot
    of great stuff. I contributed this on my blog, and my followers adored it.
    Continue the good work 🙂

  12. Chana

    Hello, its pleasant piece of writing regarding media print, we all understand media
    is a fantastic source of data.

  13. sexo gratis albacete

    videos pornos grstis sexo gratis albacete sexo pagado sexo anal amateur vidios de pornos contactos mujeres manacor anuncios
    bilbao mujeres porno gay 18 revista porno chico busca
    chico fuengirola porno hombres articulos sexo porno para lesbianas porno gratis xx sexo malaga centro como hacer el sexo
    sexo en avila contactos mujeres manacor sexo juguetes porno incestos fotos sexo casero pregnant porno viedeos porno preguntas para
    conocer amigos contactos sexo toledo porno despedida de soltera
    porno con maduras paginas gratis de sexo videsos porno sexo porno duro mejores paginas videos porno videos porno gratis
    en youtube videos porno casero gratis sexo en vigo
    comic porno naruto porno hd movil videos porno gay hd
    sexo extremo duro juegos sexo android sexo
    de marruecos sexo gay ahora madrid milanuncios contactos mujeres
    valencia chico soltero busca novia sexo videos gratis videos porno gais gratis sexo sadomaso
    sexo erotico para mujeres sexo por la calle se busca chica porno amater hd pelis porno grstis

  14. elvenar adult game

    shemale porn game elvenar adult game adult porn game videos
    free sex games no download sex game roblox 2017 sex game
    for xbox 360 porn games gameplay naruto sex game adult swim weed
    game mobile friendly adult games unblocked sex games porn fighting games adult transformation games minute to win it adult games dream job sex game adult game
    porno yaoi porn games pregnant porn games best video game porn incest porn game best adult game ever
    japan porn game filf porn game adult game flash wands and
    witches adult game free download adult game family guy porn games animation game porn ps3 sex games 3d anime sex games
    samus adult game barbie sex games sword art online sex games game of
    thrones daenerys sex scenes adult games forum best
    sex pc game best sex game app all adult games hunger games porn parody free adult
    role playing games esl adult games spongebob sex game ebony sex games adult
    3d sex games best adult games patreon gear vr adult games adult mutant ninja turtles game sex at a baseball game all game of thrones sex party adult games online adult sex games

  15. sexo en huelva

    fotos porno movil sexo en huelva porno gratis sexo vidios pornos gays video sexo grati sexo anal diarrea contactos mujeres cantabria videos porno sexo extremo conocer gente madrid porno chupadas sexo con pasion sexo ora mujeres
    para despedidas de solteros porno faking gratis sexo tias buenas peli porno espanol porno gai videos sexos porno espanol hd
    chico busca chico malaga contactar mujeres maduras porno
    gratis de abuelas porno romania juguetes sexo anal sexo gratis en girona suegras porno selena gomez porno mejor escena de sexo porno mamas cachondas contacto mujeres videos
    sexo maduras gratis chica busca chico en lleida porno vintage
    frances videos porno negros gay porno hd porno lesbianas
    tijera porno racial porno latin sexo pollas grandes contactos mujeres
    bcn contactos en huelva con mujeres peliculas porno maduritas videos porno de abuelas transesuales porno porno gay
    de negros sexo con jovenes video porno gratid contacto de mujeres en algeciras sexo gratis barbosa silvia sicilia
    porno fotos porno maduras gratis

  16. SMS

    bookmarked!!, I like your blog!

  17. vimeo.com

    Calmees par cette assurance, toutes ces femmes suivirent les deputes a l’Assemblee nationale, assurant les gardes du corps qu’il allait arriver
    de Paris des gens qui les vengeraient des mauvais traitements qu’elles pretendaient en avoir eprouve.
    vimeo.com A partir de minuit, notre allure a ete ainsi ralentie afin que notre arriveequi va s’entourer de la pompe militaire obligatoiren’ait pas lieu a une heure
    trop matinale, au milieu de cette escadre ou l’on nous
    attend.

  18. Herbalife

    cette epoque, une de ses amies, excellente musicienne, comme elle-meme etait parfaite philologue, proposa a mademoiselle Smith de mettre leurs deux talents en communaute et
    d’elever une pension de compte a demi. Herbalife Ainsi se developpaient
    les funestes effets de cette guerre d’Autriche que Napoleon avait provoquee
    en Espagne, mais reconnaissons que les fautes de son allie avaient notablement aggrave les consequences de la sienne.

  19. year g

    I do agree with all of the ideas you have introduced to your post.
    They’re really convincing and can definitely work.
    Still, the posts are too quick for starters. May you please lengthen them a bit from subsequent time?
    Thank you for the post.

  20. http://tinyurl.com/y83b9be8

    I savour, lead to I found just what I was looking for.
    You have ended my four day lengthy hunt! God Bless you man. Have a nice day.
    Bye

  21. http://tinyurl.com/yc3hsetp

    First off I want to say wonderful blog! I had a quick question which I’d like to ask if you do not mind.

    I was curious to know how you center yourself and clear your thoughts before writing.
    I have had difficulty clearing my mind in getting my
    ideas out. I truly do take pleasure in writing but it just
    seems like the first 10 to 15 minutes are wasted simply just trying
    to figure out how to begin. Any recommendations or tips?
    Thank you!

  22. tinyurl.com

    WOW just what I was searching for. Came here by searching for cbd oil

  23. cbd oil that works 2020

    This design is steller! You certainly know how to keep a reader entertained.

    Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.
    I really loved what you had to say, and more
    than that, how you presented it. Too cool!

  24. cbd oil that works 2020

    Hey there just wanted to give you a quick heads up.

    The words in your content seem to be running off the screen in Internet explorer.
    I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I figured I’d post to let you know.
    The design look great though! Hope you get the issue resolved soon. Cheers

  25. Herbalife

    Les autres sont matelasses de viande rouge, et poussent devant eux un ventre cercle a grand-peine par
    leur ceinturon; ils ouvrent en clignotant leur petit oeil
    vert de mer enflamme de luxure, et ressemblent plutot a
    des hippopotames en culotte qu’a des creatures humaines. Herbalife Je vous envoie par le meme courrier une certaine satire nouvellement publiee; et en retour de trois shillings et six pences qu’il m’en coute, je vous prie,
    si vous venez a en deviner l’auteur, de tenir son nom secret, du moins quant a present.

Leave a Reply

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