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.

47.901 comments

  1. game đánh bài

    My brother suggested I might like this blog. He
    was entirely right. This post actually made my day. You can not imagine just how much time I had spent for this info!
    Thanks!

  2. harvard law school

    Hello there! I know this is kind of off topic but I was wondering if you knew where I could locate a captcha plugin for my comment
    form? I’m using the same blog platform as yours and I’m having difficulty finding one?

    Thanks a lot!

  3. ทางเข้าvwin

    Ahaa, its good discussion about this post at this place at this webpage, I have read all that, so at this time me also commenting at
    this place.

  4. カジノ ディーラー

    Thanks for sharing your info. I truly appreciate your efforts and
    I will be waiting for your next write ups thank you once again.

  5. indian betting sites

    Marvelous, what a web site it is! This weblog provides helpful
    facts to us, keep it up.

  6. 원엑스벳

    You ought to take part in a contest for one of the finest sites on the net.
    I’m going to highly recommend this site!

  7. phpfox social network

    It’s remarkable to pay a quick visit this web site and reading
    the views of all mates about this piece of
    writing, while I am also eager of getting familiarity.

  8. poker king

    Thank you for the auspicious writeup. It in fact was a amusement account it.
    Look advanced to more added agreeable from you!
    By the way, how could we communicate?

  9. Live Casino House

    Greetings from Idaho! I’m bored at work so I decided to check out
    your site on my iphone during lunch break.
    I really like the information you provide here and can’t wait to take a
    look when I get home. I’m amazed at how quick your blog loaded on my
    cell phone .. I’m not even using WIFI, just 3G
    .. Anyhow, superb blog!

  10. Game bài

    I am not sure where you’re getting your information, but good
    topic. I needs to spend some time learning more or understanding more.

    Thanks for fantastic information I was looking for this info for my mission.

  11. time in michigan

    This piece of writing will assist the internet
    people for creating new web site or even a blog from start to end.

  12. 더킹카지노

    I absolutely love your site.. Great colors & theme.
    Did you create this website yourself? Please reply back as I’m
    hoping to create my own personal website and want to know where you got this from or what the theme is called.
    Many thanks!

  13. 더나인카지노

    Thanks for sharing your thoughts about 메리트카지노.
    Regards

  14. 에비앙카지노

    Asking questions are in fact good thing if you are not understanding something completely, but this
    piece of writing gives pleasant understanding yet.

  15. カジノ シークレット 出 金 条件

    Today, I went to the beachfront with my kids. I found a sea
    shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She
    placed the shell to her ear and screamed. There was a hermit crab
    inside and it pinched her ear. She never wants to go back!

    LoL I know this is totally off topic but I had to tell someone!

  16. バカラ

    Please let me know if you’re looking for a article author for your site.

    You have some really great articles and I feel I would be a good asset.
    If you ever want to take some of the load off, I’d absolutely love
    to write some material for your blog in exchange for a link back to mine.
    Please send me an e-mail if interested. Cheers!

  17. Bandar Togel Online

    It’s actualky a great and useful piece of info. I’m glad that you simply shared this
    helpful info with us. Pleade keep us informed lijke this.
    Thanks for sharing.

    Feel free too surf to my blog post Bandar Togel Online

  18. SLOTPG

    Highly descriptive blog, I enjoyed that bit. Will there be a part 2?

  19. sexygame

    It’s difficult to find well-informed people for
    this subject, but you seem like you know what you’re talking about!
    Thanks

  20. 우리카지노

    Hi! This is my first comment here so I just wanted to give a
    quick shout out and say I really enjoy reading through
    your blog posts. Can you suggest any other blogs/websites/forums that cover the
    same topics? Appreciate it!

  21. 솔레어카지노

    I know this if off topic but I’m looking into starting my own weblog and was curious
    what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet savvy so I’m not 100% sure. Any recommendations or advice would be greatly appreciated.

    Kudos

  22. black friday expressvpn

    hey there and thank you for your information –
    I have definitely picked up anything new from right here.
    I did however expertise several technical issues using this web site, as I experienced to
    reload the website lots of times previous to I could get it to load correctly.
    I had been wondering if your web 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 advertising and marketing with
    Adwords. Well I’m adding this RSS to my email
    and could look out for much more of your respective intriguing
    content. Ensure that you update this again soon.

  23. home appliances list

    If some one wants expert view on the topic of blogging then i advise
    him/her to visit this weblog, Keep up the nice job.

  24. オンラインカジノ

    Hey are using WordPress for your site platform? I’m new to
    the blog world but I’m trying to get started and create my own. Do you need
    any coding expertise to make your own blog?
    Any help would be really appreciated!

  25. 에비앙카지노

    Hello, Neat post. There is a problem with your web
    site in internet explorer, would test this?
    IE still is the marketplace leader and a huge component to
    folks will omit your fantastic writing because of this problem.

  26. 미스터스 alexya footjob 착용 팬티와 주머니

    Hey there! I could have sworn I’ve been to this
    website before but after reading through some of the post I realized it’s new to me.

    Anyways, I’m definitely happy I found it and I’ll be bookmarking and checking back frequently!

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

    Thank you a bunch for sharing this with all people
    you really understand what you are talking about!
    Bookmarked. Please also discuss with my web site =).
    We may have a link change arrangement between us

  28. ブラックジャック

    If you want to grow your experience simply keep visiting this web site and be updated with
    the newest gossip posted here.

  29. happyluke tặng 100k

    It’s enormous that you are getting ideas
    from this paragraph as well as from our argument made at this place.

Tinggalkan Balasan

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