Membuat Telegram Bot Menggunakan PHP : Long Polling

Sebelum membaca post ini, pastikan anda sudah memahami konsep dasar Telegram BOT API. Saya telah membuat post tentang ini sebelumnya.

Apa Saja yang Diperlukan untuk Long Polling

Untuk membuat program long polling pertama kita menggunakan Telegram BOT API, kita memerlukan :

  1. Web Server (bisa local atau hosting)
  2. Koneksi internet yang lancar
  3. Scheduler untuk melakukan request ke setiap beberapa detik sekali (Windows sudah memiliki fitur bawaan Windows Scheduler)
  4. Aplikasi Telegram. Download aplikasinya di

Pada tutorial ini, kita akan membuat bot yang dapat membalas sebuah pesan sederhana. Kita akan dapat mengatur balasan sesuai dengan pesan yang kita kirimkan melalui bot.

Tahapan Pembuatan Telegram Bot dengan Metode Long Polling

  1. Buka aplikasi Telegram, kemudian cari user @BotFather.
  2. Klik tombol /start di bagian bawah chat.
  3. Klik /newbot untuk membuat bot baru. BotFather akan meminta anda untuk mengetik nama dan username bot baru.
  4. Setelah memasukkan nama dan username, anda akan menerima pesan yang berisi token dari bot anda.
    Membuat Telegram Bot
  5. Selamat, anda baru saja membuat sebuah bot. Namun tentu saja, tanpa melakukan tindak lanjut apapun, bot ini tidak berguna, karena belum diprogram. Untuk membuat bot ini hidup, kita perlu membuat project di workspace. Jika anda belum tahu cara membuatnya, silahkan membaca post ini : #1 Tutorial Pemrograman Web – Menginstall XAMPP Server. Mari kita namakan folder project baru tersebut longpolling. Di dalam folder longpolling, kita buat sebuah file dengan nama index.php.
  6. Copy dan paste kode php di bawah ini ke dalam file index.php tersebut.
  7. <?php
    $token = '<YOUR BOT TOKEN>';
    $apiLink = "$token/";
    $update = file_get_contents($apiLink.'getUpdates');
    $updateArray = json_decode($update, TRUE);
        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 />
            file_get_contents($apiLink . "sendmessage?chat_id=$chat_id&text=You just sent ".$text);
            echo 'Response sent.<br /><br />';
    } else echo 'No new Updates';

    Ganti <YOUR BOT TOKEN> di baris kedua dengan token yang dikirim oleh telegram BotFather.

  8. Sekarang kita coba jalankan script tersebut. Buka browser anda, kemudian ketik url localhost/longpolling. Anda seharusnya melihat hasil seperti ini :
    Membuat Telegram Bot
  9. Kembali ke aplikasi Telegram, cari nama bot anda. Contoh yang saya buat, usernamenya adalah dryanchristoph_bot. Buka pesan di bot tersebut, lalu klik Start.
  10. Tidak akan ada balasan setelah melakukan klik Start. Namun jangan kuatir, tinggal selangkah lagi untuk bot tersebut bisa menjawab pesan kita.
    Membuat Telegram Bot
  11. Jalankan lagi script tadi lewat browser, ketik localhost/longpolling pada browser anda.
  12. Hasilnya, akan muncul teks di halaman web yang berisi data user dan teks yang dikirim. Di akhir, ada teks : “Response Sent.”.
    Membuat Telegram Bot
  13. Bersamaan dengan tahap sebelumnya, seharusnya anda juga mendapat notifikasi pesan telegram. Periksa pesan tersebut, dan begitulah bot baru anda bekerja.
    Membuat Telegram Bot
  14. Coba refresh scriptnya lagi di browser anda, maka updates terakhir akan hilang lagi. Sekarang anda dapat mencoba mengirim pesan apapun ke bot tersebut, kemudian jalankan kembali script di browser anda, maka bot akan memberikan respon.

Tapi tunggu dulu, bot macam apa yang memerlukan kita untuk selalu menjalankan script ketika ada user yang mengirim pesan? Namun memang begitulah konsep dari long polling. kita harus selalu melakukan pengecekan setiap beberapa detik sekali, untuk mengetahui ada atau tidak user yang mengirim pesan ke bot kita. Untuk itu, kita memerlukan Scheduler yang aplikasinya sudah ada di aplikasi bawaan Windows, yang bernama Windows Scheduler. Aplikasi ini akan membantu kita menjalankan script tersebut otomatis setiap beberapa detik sekali tanpa perlu repot – repot membuka browser lagi. Saya telah membuat post terpisah tentang ini : Membuat Windows Scheduler Untuk Menjalankan Program Otomatis.

Jadi begitulah bagaimana cara membuat Telegram Bot yang dapat membalas chat kita menggunakan metode long polling. Jika ada pertanyaan, silahkan tanya di kolom komentar ya.


  1. adult friand finder

    This post is worth everyone’s attention. How can I find out

  2. cell phone unlocker

    Well written & done myy friend.
    I started writing a bblog myself in the past few weeks aand realized many bloggers merely
    rehash old ideas but add vvery little of benefit. It’s terrific to see an educational post of some
    genuine value to your readers and I.
    It is actually oon my list of factors I need to replicate being a new blogger.
    Audience engagement and cobtent qality aree king.
    Many terrific suggestions; you’ve certainly goot on my list of blogs to watch!

    Carry onn the fantastic work!

  3. Stephania

    Admiring the dedication you put into your blog and in depth
    information you offer. It’s awesome to come across a blog every once in a
    while that isn’t the same unwanted rehashed material. Great read!

    I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  4. 제주출장안마

    It’s very easy to find out any topic on net
    as compared to books, as I found this article at this web site.

  5. Agen Dominoqq

    Do you have any video of that? I’d want to find out some
    additional information.

  6. 출장안마

    Fine way of describing, and pleasant post to take
    facts concerning my presentation subject, which i am going to convey in institution of higher education.

  7. Shad Berning

    Travelling is something that you desire to generally have as much information on that you can, you would like to constantly know good ways to travel in order to save time and money. This article is to function as a location where you can obtain lots of ideas and insight to how you can traveling far better in the future. When flying, usually have a bottle of water helpful. Enjoying lots of fluids will be sure that your system keeps hydrated in the airline flight. The air within the cabin is very dried up, playing damage along with your system. Don’t replace alcohol or caffeine intake for h2o, because this can certainly make dehydration even worse. Require a translation tool when you are traveling to some nation that doesn’t articulate your natural terminology. This could be as a magazine or perhaps a telephone software. When you might find that a majority of folks articulate The english language in sizeable metropolitan areas, it could be really different in tiny municipalities or non-urban locations. Wanting to articulate inside the language of the country is actually appreciated with the residents. Journey throughout the away-optimum periods. Hotels and plane tickets are usually much more costly throughout the peak summer months. Also, well-known places is really so more than-crowded throughout the summer season that it takes the pleasure out of it. In the event you vacation in the off-optimum several weeks you can save funds on airfare and hotels and you can prevent the crowds of people. When you go to go to family, be described as a polite invitee and do not assume they will likely make all of your sightseeing and tours strategies to suit your needs. A lot of people think they may be there being entertained, which happens to be naturally an improper assumption and produces poor sensation. As an alternative, research your options beforehand, enable your hosts understand what you’re intending to do, encourage but don’t oblige these people to come with you, and spend your time with each other in great will, realizing you are as being a gracious guest. If you’re understanding of the aroma of cleaning solutions (or simply don’t like them!) try taking some little candles along with you on your journey. It will help cover up the scent in the products the maids use as well as the aromas can also help unwind you. Some scents can even sooth you and provide you with a better night’s rest. In the event you set these tips into place, you are able to avoid lots of the problems, anxieties, and sleepless evenings that come with organising a trip. Be assured that you are completely ready and prepared appear departure day. There is no must invest a great deal time worrying.

  8. Claudio

    I’m not sure exactly why but this weblog is loading incredibly slow
    for me. Is anyone else having this issue or is it a problem on my end?
    I’ll check back later and see if the problem still exists.

  9. 출장마사지

    Fantastic goods from you, man. I’ve understand your stuff previous to and you’re just extremely fantastic.
    I actually like what you have acquired here, really like what you are
    stating and the way in which you say it. You make it enjoyable and you still
    take care of to keep it smart. I can not wait to read much more from you.

    This is actually a terrific site.

  10. agen Poker Online

    Somebody essentially assist to make significantly posts
    I’d state. This is the very first time I frequented your web page and up
    to now? I amazed with the research you made to create this particular post extraordinary.

    Magnificent task!

  11. Imprezy integracyjne Łódź

    Hey There. I found your blog using msn. This is an extremely well written article. I?ll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will certainly return.

  12. sex tips

    I think this is among the most vital information for me.
    And i am glad reading your article. But wanna remark on some
    general things, The website style is ideal, the articles is really nice : D.

    Good job, cheers

  13. joker 123

    hi!,I like your writing very a lot! proportion we keep in touch
    more approximately your article on AOL? I require a specialist in this house to solve my problem.
    Maybe that is you! Taking a look ahead to see you.

  14. 하나약국비아그라

    Excellent site you have got here.. It’s hard to find high quality writing like yours nowadays.
    I seriously appreciate people like you! Take care!!

  15. Fresh Prime Keto Diet

    When some one searches for hhis essential thing, thus he/she desires to be available that in detail, thus that thing is maintined
    over here.

  16. google

    For hottest news you have to pay a visit world-wide-web and on world-wide-web I found this site as a best
    site for latest updates.

  17. financial Derivative

    Yesterday, while I wass at work, my sister stole my iphone and tested to see if it can survive a 30
    foot drop, just so she can be a youtube sensation. My iPad is now broken and she
    has 83 views. I know this is entirely ooff topic but
    I had to share it wth someone!

  18. situs Slot yang Banyak Bonus

    you’re really a good webmaster. The website loading velocity is amazing.
    It kind of feels that you’re doing any unique trick.
    In addition, The contents are masterpiece. you have performed a excellent activity on this topic!

  19. u27

    I’m not that much of a internet reader to be honest but your blogs really nice, keep it
    up! I’ll go ahead and bookmark your site to come back in the future.

  20. Keira

    Howdy! Someone in my Myspace group shared this site with us so I came to
    check it out. I’m definitely loving the information.
    I’m book-marking and will be tweeting this to my followers!
    Wonderful blog and wonderful design and style.

  21. How to get 30 days Free Trial?

    I know this web site provides quality based articles or reviews
    and other material, is there any other web page which presents these kinds of stuff in quality?

  22. plumbing repair check this

    I’m not sure where you’re getting your info, but good topic. I needs to spend some time learning more or understanding more. Thanks for excellent information I was looking for this info for my mission.

  23. 제주출장안마예약

    Hi there! This blog post couldn챠t be written much better! Looking through this article reminds me of my previous roommate! He continually kept talking about this. I will forward this post to him. Fairly certain he’s going to have a very good read. I appreciate you for sharing!

  24. lawn service Omaha

    I’ve been browsing online more than three hours today, yet
    I never found any interesting article like yours. It’s pretty worth enough for me.

    In my opinion, if all website owners and bloggers made good content as you did, the
    internet will be a lot more useful than ever

  25. porn

    This is my first time pay a quick visit at here and i am truly happy to read everthing at one place.

  26. meteorite for sale

    These are genuinely fantastic ideas in about blogging. You
    have touched some good points here. Any way keep up wrinting.

  27. informative post

    Every weekend i used to go to see this web site, because i wish for enjoyment, as this this web site conations truly pleasant funny material

  28. Harrison Hernsheim

    It is perfect time to make some plans for the future and it’s time to be happy.

    I have read this post and if I could I wish to suggest
    you few interesting things or suggestions. Perhaps you could write next articles referring to this article.
    I wish to read more things about it! by

    My blog post: Harrison Hernsheim

  29. М ы д а р и м В а м л o т e p e й н ы й б и л е т ! П е р е х о д и т е и з а б е р и т е : THRT2651933TUJE

    П о з д р а в л я е м В а с с П о б е д о й в Г о с Л о т о ! О т к р ы т ь В а ш в ы и г р ы ш н ы й б и л е т : NFDAW2651933NFDAW

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *