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.

1.542 comments

  1. Angeles

    I am really impressed with your writing skills as well as with the layout on your blog.
    Is this a paid theme or did you modify it yourself? Anyway keep up the
    excellent quality writing, it is rare to see a great blog like
    this one nowadays.

  2. pet food

    Your world is best off without one and make certain that happens, it is very important hold the right medication at hand.
    Given this information, it is safe to visualize that quite a number of animals in a typical animal shelter are housebroken, and maybe even trained to follow a list of instructions.

    Twenty page dog training e-books may cover a few basics to encourage people to purchase a course or
    possibly a more intense manual.

  3. Hester

    Wonderful article! That is the type of information that are meant to be shared across the net.
    Disgrace on the search engines for not positioning
    this publish upper! Come on over and consult with my website .
    Thanks =)

  4. Felipa

    Woah! I’m really digging the template/theme of this blog.

    It’s simple, yet effective. A lot of times it’s very hard to
    get that “perfect balance” between superb usability and visual appeal.
    I must say you’ve done a fantastic job with this. Also, the blog loads extremely quick
    for me on Chrome. Superb Blog!

  5. receitas com leite condensado

    This site was… how do I say it? Relevant!! Finally
    I have found something which helped me. Thanks a lot!

  6. 66.42.50.240

    This paragraph is in fact a fastidious one it helps
    new internet users, who are wishing in favor of blogging.

  7. long coat men

    What’s up to all, how is the whole thing, I think every one is getting more
    from this site, and your views are pleasant in support of new visitors.

  8. healthy diet plans for weight loss

    I like the helpful information you supply to your articles.

    I will bookmark your weblog and check once more right here regularly.
    I am moderately certain I’ll be told lots of new stuff right here!
    Good luck for the next!

  9. Albsol Freelance

    If you are looking for a Highly Creative, Knowledgeable
    and Passionate Team, you have reached the right place!!” Specializing in digital partnership, we believe that your success is our success.

    http://freelance.albsol.com

  10. best treadmill under 1000

    Having read this I thought it was very enlightening. I appreciate you taking the
    time and energy to put this content together.
    I once again find myself spending a lot of time both reading
    and posting comments. But so what, it was still worth it!

  11. Kathlene

    If you wish for to get a great deal from this article then you have to apply such techniques
    to your won webpage.

  12. Amos Helmore

    Hello there! This post could not be written much better!
    Looking through this post reminds me of my previous roommate!
    He always kept preaching about this. I will send this post to him.
    Pretty sure he will have a great read. I appreciate you
    for sharing!

  13. Watch Jav Online Free - JavMama

    Howdy! I realize this is kind of off-topic however I needed to ask.

    Does building a well-established blog such as yours require a massive amount work?
    I’m completely new to blogging but I do write
    in my journal everyday. I’d like to start a blog so I can share my own experience and views online.
    Please let me know if you have any kind of suggestions or tips
    for new aspiring blog owners. Appreciate it!

  14. pills

    For most up-to-date ews you have to go to see world wide web aand on the web I found
    this website as a fknest web page for hottdst updates.

  15. Mackenzie

    Howdy! This article couldn’t be written any better!
    Looking at this article reminds me of my previous roommate!
    He always kept talking about this. I most certainly will forward this post to him.

    Fairly certain he’s going to have a good read. Thank you for sharing!

  16. Elida

    Howdy! Would you mind if I share your blog with my twitter group?

    There’s a lot of folks that I think would really appreciate your content.

    Please let me know. Thank you

  17. Joann

    If you wish for to obtain much from this paragraph then you have to apply such techniques to your won webpage.

  18. Lucia

    Hi there! Would you mind if I share your blog with my twitter group?

    There’s a lot of people that I think would really enjoy your content.
    Please let me know. Thanks

  19. Adam

    Hi it’s me, I am also visiting this web site regularly, this
    web page is genuinely fastidious and the people are truly
    sharing nice thoughts.

  20. Jimmy

    This is a really good tip particularly to those fresh to the blogosphere.
    Short but very precise information… Appreciate your sharing this one.
    A must read post!

  21. Willis

    bookmarked!!, I like your web site!

  22. Xavier

    I don’t know whether it’s just me or if perhaps everybody else experiencing problems with your website.
    It appears like some of the written text in your
    posts are running off the screen. Can someone else please provide feedback and let me know if this is happening to them as
    well? This might be a problem with my internet browser because I’ve had this happen previously.
    Kudos

  23. 假期行李寄存

    Your method of telling everything in this post is genuinely nice, every one can simply
    know it, Thanks a lot.

  24. badoo premium besplatno

    Wow, this article is pleasant, my sister is analyzing
    these things, thus I am going to convey her.

  25. Massage and Spa in Maikokōen station

    Do you have a spam problem on this website; I also am a blogger, and I was curious about your situation; many of us have created some nice practices and we are looking to trade methods with others,
    be sure to shoot me an email if interested.

  26. badoo premium ipa free download

    I know this web page presents quality depending articles or reviews and
    additional material, is there any other web site which provides these
    things in quality?

Tinggalkan Balasan

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