Creating Telegram Bot using PHP : Long Polling

Before reading this post, make sure you have understood the basic concept of Telegram BOT API. I have created a post about this earlier.

What We Need for Long Polling

To make our first code using long polling concept of Telegram BOT API, we need :

  1. A web server (local or hosted)
  2. A good internet connection
  3. A scheduler to make a request to telegram.org every few seconds (Windows already has a built in Windows Scheduler)
  4. Telegram app, obviously. Download it on telegram.org.

In this tutorial, we will create a bot that can reply to our simple chat. We will be able to set the reply according to what we send.

Steps for Creating Long Polling Telegram Bot

  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. To make it 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 longpolling. Inside the folder, create a new php file called index.php.
  6. Copy and paste this php code into your index.php file.
    <?php
    $token = '<YOUR BOT TOKEN>';
    
    $apiLink = "https://api.telegram.org/bot$token/";
    $update = file_get_contents($apiLink.'getUpdates');
    $updateArray = json_decode($update, TRUE);
    
    if($updateArray['result']){
        foreach($updateArray['result'] as $key=>$val){
            $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 />';
            
            file_get_contents($apiLink.'getUpdates?offset='.($update_id+1));
        }
        
    } else echo 'No new Updates';
    
    ?>

    Replace <YOUR BOT TOKEN> on line 2 with your bot token sent from BotFather earlier.

  7. Now let’s try to run the script. Open your browser, open url localhost/longpolling. You should see something like this :
    Creating Telegram Bot
  8. Go to Telegram app, search for your bot in Telegram. In my case, I created the username dryanchristoph_bot. Open it and hit Start.
  9. You should see nothing after clicking Start. But don’t worry, it’s just a matter of time.
    Telegram Bot
  10. Run the script again via browser, type localhost/longpolling again.
  11. You should see some text containing user request data, ended with the text : “Response sent.”.
    Telegram Bot
  12. Along with the last step, You should also see that your Telegram app is receiving a new message. Click on it, and that’s how your bot works.
    Telegram Bot
  13. Try refreshing the script again, and the updates will be gone from the browser’s page. Now you can try to send a chat to the bot, then refreshing the script will send the response to the user.

But wait, what kind of bot needs a script to run every time someone send a message? Well, that is the concept of long polling. All you need to do next is to configure a Windows Scheduler, set the php script to run every few seconds, so you don’t have to run it manually. I have created a separate post about this here : Creating a Windows Scheduler to Run Programs Automatically. You can also check the script, and try to modify the response as much you want.

So that’s it about how to make your first functional Telegram bot using long polling. If you have any question, feel free to ask it on the comment section.

578 comments

  1. jam dinding

    Hi there to every body, it’s my first pay a quick visit of this blog; this weblog includes amazing and in fact fine stuff in favor of readers.

  2. Earnest

    This article gives clear idea designed for the new viewers of
    blogging, that truly how to do running a blog.

  3. Nina

    Quality articles is the main to attract the viewers to pay a quick visit the website, that’s what this web site is providing.

  4. Isobel

    It’s a pity you don’t have a donate button! I’d definitely donate to this superb
    blog! I suppose for now i’ll settle for bookmarking and
    adding your RSS feed to my Google account. I look forward to fresh updates and will
    share this blog with my Facebook group. Chat soon!

  5. Velma

    Hey there! I’m at work browsing your blog from my new iphone!
    Just wanted to say I love reading your blog and look
    forward to all your posts! Keep up the excellent work!

  6. Lien

    Hello, I think your site might be having browser compatibility issues.

    When I look at your blog site in Chrome, 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,
    terrific blog!

  7. Lolita

    It’s really a great and helpful piece of information. I am happy that
    you shared this useful info with us. Please keep us up to date like this.
    Thanks for sharing.

  8. Isaac

    Thanks for your marvelous posting! I definitely enjoyed reading it,
    you are a great author.I will ensure that I bookmark
    your blog and will eventually come back later in life.

    I want to encourage that you continue your great work, have a nice evening!

  9. slot depo via pulsa

    Hi, this weekend is pleasant for me, as this moment i
    am reading this fantastic educational paragraph here at
    my house.

  10. cbd

    This post gives clear idea for the new visitors of blogging, that in fact how to do blogging and site-building.

  11. Augustina

    This site was… how do I say it? Relevant!! Finally I’ve found something which helped me.
    Thanks a lot!

  12. agen casino online di indonesia

    Heya i am for the first time here. I found this board and I find It
    truly useful & it helped me out much. I hope to give
    something back and help others like you aided me.

  13. qq slot promo cashback 100

    With havin so much written content do you ever run into any issues of plagorism
    or copyright violation? My blog has a lot of unique content I’ve either authored myself or outsourced but
    it seems a lot of it is popping it up all over the web without
    my authorization. Do you know any ways to help protect against content
    from being stolen? I’d definitely appreciate it.

  14. campus apartments

    Some really fantastic work on behalf of the owner of this
    website, dead great written content.

  15. Larry

    Hi there Dear, are you actually visiting this site on a regular basis, if so
    then you will absolutely get fastidious know-how.

  16. best vpn 2020 uk

    Wow, that’s what I was looking for, what a stuff! present here
    at this weblog, thanks admin of this website.

  17. Ronda

    Howdy! Would you mind if I share your blog with my twitter group?
    There’s a lot of people that I think would really enjoy your content.
    Please let me know. Thank you

  18. verfahrensdokumentation gobd muster

    Having read this I thought it was very enlightening.
    I appreciate you finding the time and effort to put this informative article together.
    I once again find myself personally spending way too much time both reading and commenting.

    But so what, it was still worth it!

  19. index.html erstellen

    It’s a shame you don’t have a donate button! I’d definitely donate to this
    superb blog! I suppose for now i’ll settle for bookmarking and adding your RSS
    feed to my Google account. I look forward to brand new updates and will talk about this blog with my Facebook group.
    Chat soon!

  20. zortilonrel

    I dugg some of you post as I thought they were handy invaluable

  21. classifieds php

    constantly i used to read smaller posts which as well clear their motive, and that is also happening with this paragraph which I am reading
    now.

  22. Osvaldo Cervoni

    Does your website have a contact page? I’m having a tough time locating it but, I’d like to send you an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing. Either way, great site and I look forward to seeing it expand over time.

  23. click here to try again

    I definitely wanted to write a brief comment so as to appreciate you for all of the magnificent solutions you are posting at this website.
    My extended internet research has at the end of the day been honored with extremely good details to share with my company.
    I would believe that many of us readers actually are truly fortunate to exist
    in a wonderful site with so many brilliant professionals with very helpful guidelines.
    I feel very much grateful to have encountered your entire webpage and look forward to so
    many more thrilling times reading click here to try again.
    Thanks a lot once again for a lot of things.

  24. ViriliTrex Male Enhancement

    Greetings from Florida! I’m bored at work so I decided to
    browse your blog on my iphone during lunch break. I really like the info you provide here and can’t wait
    to take a look when I get home. I’m amazed at how fast your blog loaded on my
    phone .. I’m not even using WIFI, just 3G ..
    Anyhow, very good site!

    Here is my page – ViriliTrex Male Enhancement

  25. White Tulip Cream Review

    As I site possessor I believe the content material here is rattling magnificent , appreciate it for your hard work.
    You should keep it up forever! Best of luck.

    Here is my web blog; White Tulip Cream Review

  26. TestOnyx Reviews

    Thank you, I’ve recently been looking for information approximately this subject for a while and yours is the best I have
    discovered so far. However, what in regards to the conclusion? Are
    you certain in regards to the supply?

    Visit my website: TestOnyx Reviews

Leave a Reply

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