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.

115 comments

  1. Ernesto

    Thankfulness to my father who stated to me on the topic of this
    webpage, this website is genuinely remarkable.

  2. Neal

    Good web site you have here.. It’s difficult to
    find quality writing like yours these days. I seriously appreciate individuals like you!
    Take care!!

  3. ver la aplicación privada de instagram reddit

    What i don’t understood is in truth how you’re now not really much more well-favored
    than you may be right now. You’re so intelligent. You
    recognize thus significantly in relation to this topic, made me for my part consider it from numerous numerous angles.
    Its like men and women aren’t involved unless it is one thing to accomplish with
    Lady gaga! Your individual stuffs great. Always take care of it up!

  4. Lona

    Hey I am so grateful I found your web site, I really found you by error,
    while I was searching on Digg for something else,
    Regardless I am here now and would just like to say thank you for a fantastic
    post and a all round thrilling blog (I also love the theme/design), I don’t have time to read through it all at the moment but I have
    bookmarked it and also added in your RSS feeds, so when I have time I will be back to read much more, Please do
    keep up the awesome work.

  5. Pedro

    Hello just wanted to give you a quick heads up. The text in your article seem to be running off
    the screen in Internet explorer. I’m not sure if this is a format
    issue or something to do with browser compatibility but I figured I’d post
    to let you know. The style and design look great though!
    Hope you get the issue fixed soon. Kudos

  6. Theresa

    It’s awesome to pay a visit this web page and reading the views of all mates about
    this paragraph, while I am also zealous of getting experience.

  7. Elyse

    We are a bunch of volunteers and opening a new scheme in our community.
    Your site offered us with helpful information to work on. You’ve done an impressive
    task and our entire community will likely be grateful to you.

  8. Les

    Wonderful blog! I found it while surfing around on Yahoo News.
    Do you have any tips on how to get listed in Yahoo News? I’ve
    been trying for a while but I never seem to get
    there! Thank you

  9. Angel

    I could not refrain from commenting. Well written!

  10. Leonora

    Right away I am ready to do my breakfast,
    later than having my breakfast coming again to read additional news.

  11. Fred

    I’m really enjoying the theme/design of your web site.
    Do you ever run into any browser compatibility problems?
    A couple of my blog readers have complained about my site not working
    correctly in Explorer but looks great in Chrome.
    Do you have any recommendations to help fix this
    issue?

  12. Rolland

    What’s up, I wish for to subscribe for this web site to take hottest updates,
    thus where can i do it please help.

  13. King

    great publish, very informative. I wonder why the other specialists of this sector don’t understand this.
    You should proceed your writing. I’m sure, you have a huge readers’ base already!

  14. Berenice

    Does your website have a contact page? I’m having problems locating it but, I’d like to shoot you an email.
    I’ve got some ideas for your blog you might be interested in hearing.
    Either way, great blog and I look forward to seeing it improve over time.

  15. Derrick

    That is a very good tip particularly to those fresh to the blogosphere.
    Short but very precise info… Thanks for sharing this one.
    A must read article!

  16. Ashli

    My brother recommended I may like this website.
    He was totally right. This publish truly made
    my day. You cann’t believe simply how so much time I had spent for this information! Thanks!

  17. Emilio

    I like the helpful info you provide in your articles. I will
    bookmark your weblog and check again here regularly.
    I am quite certain I will learn many new stuff right here!

    Best of luck for the next!

  18. Bart

    Good response in return of this issue with genuine arguments and describing everything regarding that.

  19. Kaley

    Excellent weblog here! Also your website quite a bit up
    fast! What web host are you using? Can I am getting your affiliate hyperlink in your host?

    I desire my website loaded up as fast as yours lol

  20. Lynette

    My spouse and I stumbled over here from a different web page and thought I may as well check
    things out. I like what I see so i am just following you.

    Look forward to checking out your web page for a second time.

  21. Joanna

    It’s the best time to make some plans for the long run and it
    is time to be happy. I’ve read this post and if I could I
    wish to suggest you some attention-grabbing issues or tips.
    Maybe you can write next articles regarding this article.

    I desire to read even more issues approximately it!

  22. Ladonna

    Hello to all, it’s truly a nice for me to pay a visit this web site, it consists of helpful Information.

  23. Simon

    Hi there, I found your blog by the use of Google at the same time
    as searching for a related subject, your website got here
    up, it appears to be like good. I’ve bookmarked it in my google bookmarks.

    Hi there, just become alert to your blog through Google, and found that it is truly informative.
    I’m gonna be careful for brussels. I will appreciate if
    you proceed this in future. A lot of other
    folks will probably be benefited from your writing. Cheers!

  24. Carl

    Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something.
    I think that you can do with some pics to drive the message home a bit,
    but instead of that, this is magnificent blog. A great read.

    I’ll certainly be back.

  25. Lynwood

    Write more, thats all I have to say. Literally, it seems as though you relied
    on the video to make your point. You clearly know what youre talking about, why throw away your intelligence on just posting videos to your blog when you could be giving us something enlightening to read?

Leave a Reply

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