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 telegram.org setiap beberapa detik sekali (Windows sudah memiliki fitur bawaan Windows Scheduler)
  4. Aplikasi Telegram. Download aplikasinya di telegram.org.

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 = "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';
    
    ?>

    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.

11.554 comments

  1. joker123.net

    What’s Taking place i’m new to this, I stumbled upon this I have discovered It absolutely helpful and it has helped me out loads.
    I’m hoping to contribute & help different customers like its aided me.
    Good job.

  2. situs slot deposit pulsa Tanpa potongan

    Hey there! Do you use Twitter? I’d like to follow you if that would be ok.
    I’m absolutely enjoying your blog and look forward to new posts.

  3. สล็อตออนไลน์888

    Its such as you learn my thoughts! You seem to grasp so much about this, like you
    wrote the e book in it or something. I feel that you
    simply can do with some p.c. to power the message home a
    bit, however instead of that, this is great blog. An excellent read.
    I will certainly be back.

  4. addiction treatment

    Hiya! I know this is kinda off topic nevertheless
    I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa?
    My site covers a lot of the same topics as yours and I believe we could
    greatly benefit from each other. If you happen to be interested
    feel free to shoot me an email. I look forward to hearing from you!
    Wonderful blog by the way!

  5. PG SLOT

    I read this article fully about the comparison of latest and preceding technologies, it’s amazing article.

  6. 부산출장안마

    Greetings! Very helpful advice within this post! It is the little changes that will make the biggest changes. Many thanks for sharing!

  7. slot online

    Its like you learn my thoughts! You appear to grasp a
    lot about this, like you wrote the book in it or something.
    I feel that you just could do with a few p.c. to force the
    message house a little bit, however other than that, that is
    wonderful blog. A great read. I’ll definitely be back.

  8. PGSLOT

    I know this if off topic but I’m looking into starting my own weblog and was
    curious what all is required to get setup?
    I’m assuming having a blog like yours would cost a pretty penny?

    I’m not very web savvy so I’m not 100% positive. Any suggestions
    or advice would be greatly appreciated. Kudos

  9. YouTube.com

    I like the helpful info you provide to your articles. I will bookmark
    your weblog and test again here frequently.
    I am quite certain I’ll be informed a lot of new stuff right here!
    Good luck for the next!

  10. 바카라

    Remarkable things here. I am very happy to look your post.
    Thanks so much and I am having a look ahead to touch you.
    Will you please drop me a e-mail?

  11. เว็บบาคาร่า

    I’m now not certain where you are getting your info, but great topic.
    I must spend some time finding out much more or figuring out
    more. Thank you for fantastic info I was searching for this information for my mission.

  12. PEPEK BERDARAH

    Hello, i think that i noticed you visited my blog so i got here to return the desire?.I am
    trying to find issues to improve my site!I suppose its ok to make
    use of some of your concepts!!

  13. Merry

    WOW just what I was looking for. Came here by searching for guitar
    tone knob

  14. Podsluch w Telefonie

    My brother suggested I might like this website. He was totally right. This post truly made my day. You can not imagine just how much time I had spent for this information! Thanks!

  15. premium website builder

    I love it, I read it often and you’re always coming out with
    some great stuff. I shared this on my facebook and my
    followers love it! Keep up the great work.

    Here is my blog post; premium website builder

  16. เว็บพนันออนไลน์2021

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

  17. speakers

    The first house audio subwoofers had been developed in the Nineteen Sixties to add bass response to residence stereo techniques.

  18. best seller pillow

    I have read some just right stuff here. Certainly value bookmarking for revisiting.

    I surprise how a lot attempt you set to make this type of excellent informative site.

  19. seagate external hard disk

    Hello! This is my first comment here so I just wanted to give a quick shout out and say I truly enjoy reading your articles.
    Can you suggest any other blogs/websites/forums that cover the same subjects?
    Thank you!

  20. Nigeria Property

    Hi to all, the contents present at this web page are
    genuinely remarkable for people knowledge, well,
    keep up the nice work fellows.

  21. Edison

    If you are going for most excellent contents like myself, just pay a quick visit thks site daily because it provides
    feature contents, thanks

    Also visit my web page … takeaway food gloucester (Edison)

  22. tactical Walking staff

    That is a very good tip especially to those new to the blogosphere.

    Simple but very accurate information… Appreciate your sharing this
    one. A must read article!

  23. Voting T-shirts Import

    Wonderful beat ! I would like to apprentice while you amend your website, how could i subscribe for a blog website?

    The account aided me a acceptable deal. I had been tiny
    bit acquainted of this your broadcast offered bright clear concept

  24. 무료 영화 사이트

    Hi there, I found your site by way of Google while
    looking for a related topic, your site came up, it
    seems to be great. I have bookmarked it in my
    google bookmarks.
    Hello there, simply was aware of your blog through Google,
    and located that it is really informative.
    I’m gonna watch out for brussels. I’ll appreciate should you continue this in future.
    Lots of other folks can be benefited out of your writing.
    Cheers!

  25. 윈도우10 정품 코드

    Terrific work! This is the kind of information that should be shared
    around the net. Disgrace on Google for not positioning this submit higher!
    Come on over and consult with my website . Thanks =)

Tinggalkan Balasan

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