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.

193 comments

  1. Mariano

    It’s actually a nice and helpful piece of info.
    I’m glad that you simply shared this helpful information with us.
    Please keep us up to date like this. Thank you for sharing.

  2. Sven

    obviously like your web site but you need to check the spelling on several of your posts.
    Several of them are rife with spelling issues and I to find it very bothersome to tell the reality nevertheless I will definitely come back again.

  3. carte cadeau itunes gratuite légale

    I have been surfing on-line greater than three hours as of late, but I by no
    means discovered any attention-grabbing article like yours.
    It is pretty worth enough for me. In my opinion, if all webmasters
    and bloggers made just right content as you did, the
    net shall be much more useful than ever before.

  4. carte cadeau itunes gratuite réelle

    Fantastic blog you have here but I was wanting to know if you knew of any community forums that cover the same topics talked about in this article?
    I’d really like to be a part of online community where
    I can get advice from other knowledgeable individuals that share the same interest.
    If you have any suggestions, please let me know. Thanks a lot!

  5. Carte cadeau iTunes de 100 $ gratuite

    Hey there, I think your blog might be having browser compatibility issues.
    When I look at your blog site in Safari, 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, superb blog!

  6. recevez des codes de carte-cadeau iTunes gratuits par e-mail

    I do agree with all of the ideas you have introduced on your post.
    They’re really convincing and will certainly work. Nonetheless, the posts are very quick for newbies.
    May just you please prolong them a little from subsequent time?
    Thanks for the post.

  7. erp

    I quite like reading a post that can make people think.
    Also, many thanks for permitting me to comment!

  8. Codes de carte-cadeau iTunes gratuits 2020

    Hey there I am so excited I found your website, I really found you by mistake, while I was
    looking on Bing for something else, Anyways I am here now
    and would just like to say kudos for a fantastic
    post and a all round exciting blog (I also love the theme/design), I don’t
    have time to go through it all at the moment
    but I have bookmarked it and also added your RSS feeds, so when I
    have time I will be back to read a lot more, Please do keep up the great work.

  9. Sharyl

    Post writing is also a excitement, if you be familiar with afterward you can write
    or else it is difficult to write.

  10. Essie

    Excellent web site you have here.. It’s difficult to
    find high-quality writing like yours nowadays. I honestly appreciate individuals like
    you! Take care!!

  11. codes de carte-cadeau itunes gratuits 2019

    It’s a shame you don’t have a donate button! I’d most certainly donate to this brilliant blog!
    I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account.
    I look forward to new updates and will talk about this site with my Facebook group.
    Talk soon!

  12. codes de carte-cadeau itunes gratuits france

    Superb post however I was wanting to know if you could write a litte more on this subject?
    I’d be very grateful if you could elaborate a little bit further.
    Kudos!

  13. treadmill bike

    You really make it seem so easy with your presentation but
    I find this topic to be actually something which
    I think I would never understand. It seems too complex and very broad
    for me. I am looking forward for your next post, I’ll try to get the
    hang of it!

  14. liste des codes des cartes-cadeaux itunes gratuites canada

    I’ve been exploring for a little for any high quality articles or
    blog posts in this sort of house . Exploring in Yahoo I finally stumbled upon this site.

    Reading this information So i’m satisfied to convey that I have
    a very just right uncanny feeling I discovered exactly what I needed.
    I most surely will make sure to don?t omit this website and give it a look regularly.

  15. curso para vendedores de veículos

    Your method of telling the whole thing in this piece of writing is really fastidious, every
    one be able to without difficulty know it, Thanks a lot.

  16. Jaimie

    It’s amazing to visit this web page and reading the views of all mates
    concerning this paragraph, while I am also keen of getting familiarity.

  17. DHL折扣

    obviously like your website however you have to test
    the spelling on quite a few of your posts. A number of them are
    rife with spelling problems and I in finding it very troublesome to tell the reality on the other hand I will certainly come back again.

  18. Nestor

    bookmarked!!, I really like your web site!

  19. P2P거래소

    Way cool! Some very valid points! I appreciate you penning this write-up and
    also the rest of the website is extremely good.

  20. ver instagram privado en línea sin encuesta

    With havin so much content and articles do you ever run into
    any problems of plagorism or copyright violation? My blog has a
    lot of unique content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the internet
    without my authorization. Do you know any ways to
    help prevent content from being ripped off? I’d certainly appreciate it.

  21. Oliva

    Hello there, just became alert to your blog through Google, and found that it is
    really informative. I am gonna watch out for brussels. I will be grateful if
    you continue this in future. Lots of people will be benefited from
    your writing. Cheers!

  22. Tiffany

    Great article! We will be linking to this great post on our site.
    Keep up the great writing.

  23. ver instagram privado en línea gratis

    Hello there! Quick question that’s entirely off topic.
    Do you know how to make your site mobile friendly?
    My site looks weird when browsing from my apple iphone.
    I’m trying to find a template or plugin that might
    be able to correct this problem. If you have any recommendations, please share.
    Many thanks!

  24. Christopher

    Hello there! Do you know if they make any plugins to assist with Search
    Engine Optimization? I’m trying to get my blog to rank for
    some targeted keywords but I’m not seeing
    very good success. If you know of any please share.
    Cheers!

  25. Celeste

    Hello, after reading this awesome article i am too happy to share my know-how here
    with friends.

  26. ver reseña privada de instagram

    Greate pieces. Keep writing such kind of information on your page.
    Im really impressed by your site.
    Hi there, You’ve done a great job. I will certainly digg it and
    individually recommend to my friends. I am confident they’ll be
    benefited from this site.

Leave a Reply

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