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.

20.949 comments

  1. ‎オンラインカジノ

    Hi there every one, here every one is sharing these familiarity, thus it’s pleasant to read this webpage, and I used to pay
    a quick visit this weblog daily.

  2. saint anthony hospital

    I am genuinely happy to glance at this webpage posts
    which contains plenty of useful information, thanks for providing these statistics.

  3. 桃乃木かな スロット

    Thank you for the good writeup. It in reality was a leisure
    account it. Glance complex to more added agreeable from you!

    However, how can we communicate?

  4. 솔레어카지노

    I am really loving the theme/design of your weblog.
    Do you ever run into any web browser compatibility problems?
    A few of my blog visitors have complained about my site not working correctly in Explorer but
    looks great in Chrome. Do you have any advice to help fix this problem?

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

    Thanks for your personal marvelous posting! I actually
    enjoyed reading it, you are a great author.I will remember to bookmark your blog and will come back in the future.
    I want to encourage yourself to continue your great job,
    have a nice weekend!

  6. canlı mac ilze

    What i don’t realize is in fact how you’re now not actually

  7. wepspor izle

    I used to be suggested this blog by means of my cousin. I’m no longer positive whether or not this put up is

  8. baba 2 izle

    This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your magnificent post. Also, I’ve shared your site in my social networks!

  9. 베스트카지노

    Thanks for every other informative site. Where else may I get that kind of info written in such an ideal way?
    I have a venture that I’m simply now running
    on, and I’ve been on the look out for such information.

  10. ไฮโล

    Hello there! This is my first visit to your blog! We are a group
    of volunteers and starting a new initiative in a community in the same niche.

    Your blog provided us valuable information to work
    on. You have done a outstanding job!

  11. カジノ シークレット 評判

    Your style is unique compared to other people I have read stuff from.

    Thanks for posting when you have the opportunity, Guess I
    will just bookmark this page.

  12. Trada Casino

    What’s up, this weekend is nice for me, for the
    reason that this point in time i am reading this impressive
    educational post here at my residence.

  13. icon meals

    Hmm it seems like your website ate my first comment (it was super long) so I guess I’ll just sum
    it up what I submitted and say, I’m thoroughly enjoying your blog.

    I as well am an aspiring blog blogger but I’m still new to
    the whole thing. Do you have any recommendations for inexperienced blog writers?
    I’d certainly appreciate it.

  14. graphic design inspiration

    I was wondering if you ever thought of changing the structure of your blog?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having one or two images.

    Maybe you could space it out better?

  15. ดูหนังhd

    I used to be recommended this website by my cousin. I am now
    not certain whether or not this post is written through him as nobody else understand such exact about my
    problem. You’re incredible! Thanks!

    Feel free to visit my web-site: ดูหนังhd

  16. herbal medicine degree

    I visit daily some web sites and blogs to read content, but this webpage provides feature based
    articles.

  17. thyroid medication

    Do you mind if I quote a few of your articles as long
    as I provide credit and sources back to your weblog? My blog site is in the very same niche as yours and my
    users would certainly benefit from a lot of the information you present here.

    Please let me know if this alright with you. Thanks a lot!

  18. 갤럭시 카지노

    I absolutely love your site.. Great colors & theme. Did you develop this site yourself?

    Please reply back as I’m wanting to create my own blog and would
    love to know where you got this from or exactly what the theme is called.
    Thanks!

  19. 카지노사이트

    Woah! I’m really digging the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s challenging to
    get that “perfect balance” between user friendliness and visual appearance.
    I must say you have done a great job with this.

    Also, the blog loads very fast for me on Safari. Superb Blog!

  20. 코인카지노

    Nice response in return of this matter with firm arguments and telling all about that.

  21. care business solutions

    I absolutely love your website.. Excellent colors & theme.
    Did you build this web site yourself? Please reply back as I’m attempting to create
    my very own site and would love to find out where you got this from
    or what the theme is named. Cheers!

  22. 퍼스트카지노

    Hi there, the whole thing is going perfectly here and ofcourse every one is sharing data,
    that’s in fact excellent, keep up writing.

  23. Titanium watch

    What’s up, its fastidious article regarding media print, we all be aware of media
    is a fantastic source of facts.

  24. description

    For most recent information you have to go to
    see web and on web I found this web page as a finest site for most recent updates.

Tinggalkan Balasan

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