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.

71.151 comments

  1. 코인카지노

    Hi there, after reading this awesome article i am also happy to share my familiarity here with
    mates.

  2. emergency electrician near me

    This is very interesting, You are a very skilled blogger.
    I have joined your rss feed and look forward to seeking more of your great post.

    Also, I have shared your web site in my social networks!

    Take a look at my blog; emergency electrician near me

  3. Data Sgp

    Hi there it’s me, I am also visiting this website daily, this web page is genuinely fastidious and the viewers are
    actually sharing nice thoughts.

    Also visit my web-site Data Sgp

  4. Anupama

    Anirudh creates fire in his room and screams for help.

    Here is my web site Anupama

  5. lisa armatrong

    I love looking through an article that can make people think.
    Also, many thanks for allowing me to comment!

    My web site … lisa armatrong

  6. Data Sgp

    I do not know whether it’s just me or if perhaps everyone else experiencing issues with your website.

    It appears like some of the written text on your content are
    running off the screen. Can somebody else please provide feedback and let me know if this is happening
    to them too? This may be a issue with my web browser
    because I’ve had this happen previously. Cheers

    My homepage – Data Sgp

  7. baltimore medical examiner

    My partner and I stumbled over here from a different
    web address and thought I should check things out.
    I like what I see so i am just following you. Look forward to
    going over your web page for a second time.

  8. pengeluaran sgp

    My family members always say that I am wasting my time here at web,
    but I know I am getting know-how everyday by reading thes nice content.

    My web site … pengeluaran sgp

  9. electrical certificate Landlords

    Write more, thats all I have to say. Literally, it seems as though
    you relied on the video to make your point. You definitely know what youre talking about, why throw
    away your intelligence on just posting videos to your site when you could be giving us something informative to read?

    my homepage :: electrical certificate Landlords

  10. desi Tv box

    Later at night she gives the reality check to family about Cafe’s success to which Anupamaa agrees.

    Review my blog – desi Tv box

  11. Data hk

    I think this is one of 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

    Feel free to surf to my web-site … Data hk

  12. Keuaran Sgp

    I was more than happy to uncover this web site. I want to to
    thank you for ones time for this particularly fantastic read!!
    I definitely savored every part of it and i also have you saved to
    fav to see new stuff in your blog.

    Look at my web-site; Keuaran Sgp

  13. Private Adhd diagnosis

    When I originally left a comment I seem to have clicked on the -Notify me when new comments are added-
    checkbox and now each time a comment is added I get four emails with
    the exact same comment. Perhaps there is a way you can remove me from that service?
    Thanks a lot!

    Feel free to visit my webpage Private Adhd diagnosis

  14. Toto Hk

    Incredible points. Solid arguments. Keep up the good work.

    My webpage … Toto Hk

  15. togel singapore

    After checking out a handful of the articles on your website, I truly appreciate your
    way of writing a blog. I added it to my bookmark website list and will
    be checking back soon. Take a look at my website
    as well and tell me what you think.

    Feel free to visit my page – togel singapore

  16. Togel hongkong

    A fascinating discussion is definitely worth comment.
    I do believe that you should write more on this subject matter, it might not be a taboo matter but usually people do not talk about such issues.
    To the next! Kind regards!!

    Here is my blog post Togel hongkong

  17. mD9fS6wM1I9

    It’s going to be end of mine day, but before ending I am reading this great piece of writing to increase my experience.

  18. BollyFun Tv

    Another likely contestant of the show is Sherine Singh, who featured in the music video Bedardi Se Pyaar Ka.

    Have a look at my web blog :: BollyFun Tv

  19. Venus

    Thanks for finally writing about > Membuat Telegram Bot Menggunakan PHP : Long Polling –
    Dryan Christoph Personal Website Venus

  20. Desi Tv Serials

    When I heard that the show will be aired on Bengali
    television, I was really really happy.

    Here is my web page – Desi Tv Serials

  21. psychiatrist uk

    What’s up to every body, it’s my first go to see of this website; this blog includes remarkable
    and actually good material in support of readers.

    Here is my website; psychiatrist uk

  22. Toto Hk

    Thank you a bunch for sharing this with all folks you really recognize what you are speaking about!
    Bookmarked. Kindly also visit my site =). We will have a hyperlink exchange arrangement among us

    Here is my blog Toto Hk

  23. Togel Hongkong

    Hey! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing a few months of hard work due to no data backup.
    Do you have any solutions to prevent hackers?

    Here is my web blog – Togel Hongkong

  24. Desi Tv Serials

    Seeing that Kavya is trying to part the family using
    Geeta, Anupamaa politely asks Geeta to leave, infuriating
    Kavya.

    Also visit my homepage – Desi Tv Serials

  25. togel Singapore

    Howdy very nice website!! Guy .. Excellent .. Superb ..
    I will bookmark your blog and take the feeds additionally?
    I am happy to seek out numerous useful info here in the publish,
    we’d like develop extra techniques in this regard, thanks for sharing.
    . . . . .

    My homepage – togel Singapore

  26. totobet Hk

    I do trust all the ideas you’ve offered in your post. They are
    very convincing and will certainly work. Still, the posts are
    very quick for beginners. May just you please lengthen them a little from next time?
    Thank you for the post.

    Also visit my blog post: totobet Hk

Tinggalkan Balasan

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