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.170 comments

  1. desi tv

    Anirudh comes by dressing up as Krishna.

    my web blog … desi tv

  2. Eileen

    I really love your blog.. Excellent colors & theme. Did you develop this website yourself?
    Please reply back as I’m looking to create my own personal
    blog and want to learn where you got this from or
    just what the theme is named. Appreciate it!

    My web-site; toto hk – Eileen

  3. 더나인카지노

    Wonderful work! That is the kind of information that are supposed to
    be shared across the net. Shame on Google for now not positioning this publish upper!
    Come on over and seek advice from my website .

    Thank you =)

  4. Big boss 15

    Later on Paritosh decides to move out with Kinjal for privacy when Rakhi convinces him for this and assures that even Anupamaa supported her
    in this decision.

    Check out my webpage – Big boss 15

  5. pengeluaran sgp

    Great goods from you, man. I’ve understand your stuff previous
    to and you are just too magnificent. I really like what you have acquired here, really like what you’re stating and the way in which
    you say it. You make it entertaining and you still care for to keep it sensible.
    I cant wait to read much more from you. This is actually a tremendous site.

    Here is my site: pengeluaran sgp

  6. Leonora

    Awesome article.

    Feel free to surf to my website :: totobet hk – Leonora

  7. data sgp

    Yesterday, while I was at work, my sister stole my iphone and tested
    to see if it can survive a thirty foot drop, just so she can be
    a youtube sensation. My iPad is now broken and she has 83 views.
    I know this is completely off topic but I had to share it with someone!

    Stop by my site – data sgp

  8. local locksmith car

    I have to thank you for the efforts you have put in penning this blog.
    I really hope to view the same high-grade blog posts by
    you later on as well. In fact, your creative writing abilities has motivated me to get my very own website now 😉

    my web page: local locksmith car

  9. Pengeluaran Sgp

    Hello There. I found your blog the use of msn. This is a really smartly written article.

    I’ll make sure to bookmark it and return to read extra of your useful information. Thanks for the post.
    I will definitely return.

    My web-site: Pengeluaran Sgp

  10. totobet sgp

    My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress on a variety
    of websites for about a year and am worried about switching to another platform.
    I have heard very good things about blogengine.net.
    Is there a way I can import all my wordpress
    content into it? Any help would be really appreciated!

    Feel free to surf to my web blog; totobet sgp

  11. อนิเมะ

    hello there and thank you for your information – I’ve certainly
    picked up something new from right here. I did however expertise several technical issues
    using this web site, as I experienced to reload the web site many times previous to I could get it
    to load properly. I had been wondering if your hosting is OK?
    Not that I am complaining, but sluggish loading instances
    times will very frequently affect your placement in google and can damage your high
    quality score if ads and marketing with Adwords. Anyway I am adding this RSS to my email and can look out for a lot more of your respective fascinating content.
    Ensure that you update this again very soon.

  12. Totobet Hk

    Marvelous, what a webpage it is! This webpage presents useful facts to us, keep it
    up.

    Also visit my web blog: Totobet Hk

  13. pengeluaran Hk

    Howdy just wanted to give you a quick heads up. The text in your post seem
    to be running off the screen in Safari. I’m not sure if this is a format issue
    or something to do with browser compatibility but I figured I’d post to let you know.
    The style and design look great though! Hope you get the issue solved soon. Kudos

    Feel free to surf to my web-site; pengeluaran Hk

  14. Melisa

    Why people still use to read news papers when in this technological world everything is
    existing on web?

    Also visit my page … pengeluaran sgp (Melisa)

  15. Abdul

    I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored material stylish.

    nonetheless, you command get got an shakiness over that you wish be delivering
    the following. unwell unquestionably come further formerly again since exactly the
    same nearly very often inside case you shield this increase.

    Also visit my web-site; keluaran hk (Abdul)

  16. cbd vape Juice online

    Greate article. Keep posting such kind of info on your page.
    Im really impressed by your blog.
    Hello there, You’ve done a great job. I’ll definitely digg
    it and individually suggest to my friends. I am sure
    they’ll be benefited from this website.

    my page :: cbd vape Juice online

  17. Data sgp

    Great blog here! Also your web site loads up fast!
    What web host are you using? Can I get your affiliate link to your host?
    I wish my web site loaded up as quickly as yours lol

    my blog post: Data sgp

  18. Totobet Sgp

    Admiring the time and energy you put into your site and in depth information you provide.
    It’s good to come across a blog every once in a while that isn’t the same outdated rehashed information. Wonderful read!
    I’ve saved your site and I’m including your RSS feeds to my
    Google account.

    Have a look at my web-site: Totobet Sgp

  19. Keuaran Sgp

    Thank you for another wonderful post. The place else may anyone get
    that kind of info in such an ideal means of writing?
    I have a presentation subsequent week, and I’m at the look for such information.

    Feel free to visit my homepage Keuaran Sgp

  20. Data Sgp

    I loved as much as you will receive carried out right here.
    The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get bought an shakiness over
    that you wish be delivering the following. unwell unquestionably come more formerly again since exactly the same nearly very often inside case you shield this increase.

    Here is my blog Data Sgp

  21. best skincare Sets near me

    Nice post. I learn something totally new and challenging on websites I
    stumbleupon every day. It’s always useful to read through content from other writers and use a little something from their web sites.

    Feel free to surf to my blog; best skincare Sets near me

  22. Keuaran Sgp

    I do believe all of the concepts you’ve presented for your post.

    They are really convincing and can definitely work. Nonetheless, the posts are too short for novices.
    May you please prolong them a bit from subsequent time?
    Thanks for the post.

    my homepage Keuaran Sgp

  23. 510 cbd vape cartridge

    Thanks for every other informative website. The place else may just I am getting that type
    of information written in such a perfect means? I have a
    project that I’m simply now operating on, and
    I’ve been at the look out for such information.

    My page 510 cbd vape cartridge

  24. cbd cats arthritis

    I just like the valuable info you provide for your articles.
    I will bookmark your weblog and check again here frequently.
    I am slightly sure I’ll learn many new stuff right right here!
    Good luck for the next!

    Look into my homepage; cbd cats arthritis

  25. adult adhd private assessment

    Hi there! Someone in my Facebook group shared this site with us so I came to take a look.

    I’m definitely loving the information. I’m book-marking and will be tweeting
    this to my followers! Fantastic blog and terrific design and style.

    My website – adult adhd private assessment

Tinggalkan Balasan

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