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.

2,056 comments

  1. wiki.cloudcabinet.co.za

    hello there and thank you for your info ? I have definitely picked up anything new from right here.
    I did however expertise some technical issues using this website, since I experienced to reload the web site a lot
    of times previous to I could get it to load correctly.
    I had been wondering if your hosting is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could
    damage your high-quality score if ads and marketing with Adwords.
    Anyway I am adding this RSS to my e-mail and could look out for much more of your respective intriguing content.

    Ensure that you update this again soon..

  2. idn poker

    whoah this weblog is excellent i love reading
    your posts. Stay up the great work! You realize, many people are searching round for this
    information, you can aid them greatly.

  3. Brian Spear

    trandate diamox astelin

  4. Evelyn Sims

    Hi there! This blog post couldn’t be written much better!
    Looking at this post reminds me of my previous roommate!
    He constantly kept talking about this. I am going to forward this article to him.
    Pretty sure he’s going to have a very good read.
    Thank you for sharing!

  5. Robert Mullins

    desyrel yasmin aldactone

  6. idnpoker.com

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

  7. Judith Ashe

    Hi! I’ve been following your website for a long time
    now and finally got the bravery to go ahead and give you a shout out from Huffman Texas!
    Just wanted to say keep up the good work!

  8. idnpoker 88

    Thanks a lot for sharing this with all folks you actually
    realize what you are speaking about! Bookmarked. Kindly additionally
    discuss with my website =). We can have a link alternate arrangement between us

  9. Bertha Ramos

    Hi, I do think this is a great web site. I stumbledupon it 😉 I am going to return once again since I book-marked
    it. Money and freedom is the greatest way to change,
    may you be rich and continue to help others.

  10. minecraft server

    It is really a nice and useful piece of information.
    I’m glad that you shared this helpful info with us.

    Please keep us up to date like this. Thank you ffor sharing.

  11. twitter trend topic

    Beyler ne zaman geldigini �nemi yok bence saat �nemi yok siteye giris yaptiktan sonra geliyor mu geliyor bosverin gerisini

  12. Jerome Samaniego

    Hello! Someone in my Myspace group shared this site with us so I came to look
    it over. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers!
    Exceptional blog and amazing design and style.

  13. appsplit.com

    Hello, i think that i noticed you isited my
    blog thus i came to “go ack the choose”.I’m trying to
    in findung issues to enhance my web site!I assume its adequate
    to use a few of your ideas!!

  14. zjychy.com

    Thanks for giving your ideas inn this article.
    The other factor is that each time a problem occurs with a laptop or computer motherboard, people should not goo ahdad and take risk with
    repairing the item themselves because iff it is not done properly it can lead to permanent
    damage to the full laptop. It is almost always safe just to approach any dealeer of a laptop for aany repair
    of iits motherboard. They have technicians with
    an know-how in dealing with mobile computer motherboard challenges
    and can have the right analysis annd undertake repairs.

  15. Melissa Lee

    eulexin keflex glucophage

  16. 카지노

    I am now not positive where you are getting your information, however good
    topic. I needs to spend some time learning more or figuring out more.
    Thank you for fantastic info I used to be searching for this information for my mission.

Leave a Reply

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