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.

11.555 comments

  1. voyance gratuite immediate par telephone

    Wonderful beat ! I wish to apprentice while you amend your
    site, how can i subscribe for a blog web site? The account helped
    me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright
    clear concept

  2. motivational video

    Hey! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  3. music for free

    Hello there! This article couldn’t be written any better!

    Going through this post reminds me of my previous roommate!
    He continually kept talking about this. I am going to forward this information to him.
    Fairly certain he’ll have a very good read. Many thanks for sharing!

    Also visit my blog music for free

  4. Easy learn english

    When I initially left a comment I seem to have clicked on the -Notify me
    when new comments are added- checkbox and from now
    on whenever a comment is added I get 4 emails with the exact same
    comment. Perhaps there is an easy method
    you can remove me from that service? Many thanks!

  5. ncfamft.com

    Hi excellent blog! Does running a blog similar to this require a large amount of
    work? I have absolutely no expertise in coding however I was hoping to start my own blog soon. Anyhow,
    if you have any ideas or tips for new blog owners please share.
    I know this is off topic however I just needed to ask.
    Cheers!

    Here is my blog – what is kratom (ncfamft.com)

  6. cse.google.com.cy

    Heya i’m for the primary time here. I found this board and I to find It truly
    helpful & it helped me out a lot. I am hoping to offer one thing back and help others like you helped me.

  7. عسل

    This is a topic that is near to my heart… Thank you! Where are
    your contact details though?

  8. bdsm kontakte schweiz

    Great beat ! I would like to apprentice while you amend your web site, how can i subscribe for a weblog web site?

    The account helped me a appropriate deal. I were a little
    bit acquainted of this your broadcast provided shiny
    transparent idea

  9. Unblocked

    Hello i am kavin, its my first occasion to commenting anyplace, when i read this piece of writing i thought i could also create comment due to this brilliant paragraph.

  10. pkv terpercaya

    Yes! Finally someone writes about daftar qq online.

  11. cam Chat porn

    Babiš, Kellner, šmejc, Kučera, Dospiva, Tykač, Baudiš, Křetínský, Komárek, Vítek.

    :)))) oni Máj každý XX miliard dohromady na 10 milionů
    bytů… Jim se zeptejte proč nepomáhají…

  12. 789win

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

  13. finance

    Appreciate the recommendation. Will try it out.

  14. mobilarian

    The best place to share and download softwares in the internet.

    lucidire .com
    https://lucidire.com

    Thank you for any other excellent post. The place else may just anybody get that
    type of information in such a perfect means of writing?
    I’ve a presentation subsequent week, and I’m on the look for such
    info.

  15. kütahya escort

    Link exchange is nothing else but it is just placing the other person’s web site link
    on your page at suitable place and other person will also do same for
    you.

  16. slot

    Hi there to all, as I am in fact keen of reading
    this blog’s post to be updated on a regular
    basis. It consists of nice material.

  17. Annakam

    [url=http://viagrasildenafilotc.com/]online viagra order india[/url] [url=http://tetracyclineonline.com/]terramycin for cats petsmart[/url]

  18. club w88 dashboard

    Hurrah! In the end I got a website from where I know how to genuinely take helpful information concerning my study and
    knowledge.

  19. click here

    Link exchange is nothing else but it is simply placing the other person’s blog
    link on your page at suitable place and other person will also do same for you.

  20. SEO KONTOL

    Undeniably imagine that which you said. Your favorite justification seemed to be on the internet the easiest thing to take note
    of. I say to you, I certainly get annoyed at the same time as other folks consider worries
    that they plainly do not realize about. You controlled to hit the nail upon the top and defined out the entire
    thing with no need side-effects , people could take a signal.
    Will probably be back to get more. Thanks

  21. Deposit Pulsa

    An outstanding share! I have just forwarded this onto a colleague who had been conducting a little research on this.
    And he in fact ordered me breakfast because I discovered it for him…
    lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanks for spending some time to talk about this issue here on your website.

  22. https://webcamsexlivefree.com/

    The Asian sailors of the Honshu were a mixed congregation, as in any branch of the military: of every legal age and every walk of life.
    The threat of incarceration, to the sailors who were only
    informed of their objective weeks after they had already gotten to the maritime vicinity of the
    archipelago-nation, was simply unthinkable. Sharks were a
    growing concern as crew members who had survived the explosions
    and drowning were now finding that the local Selachimorpha population were ravenous.
    We have thousands of members of all ages, sizes, and races.

    A third initiative, a downloadable video game, helped mitigate shame felt by some young men who have sex
    with men, though the reduction in risky sexual behavior wasn’t
    statistically significant. After a few unanswered knocks, the manager opens the door to a gruesome discovery: the deceased body
    of a young woman, beaten and left naked at the foot of the bed.

  23. fluxmag

    I have been browsing on-line more than 3 hours as of late, but I never found any interesting article like
    yours. It’s lovely price enough for me. In my
    view, if all website owners and bloggers made just right content as you probably did, the net will probably be a
    lot more helpful than ever before.

  24. earn Bitcoin

    Hi there would you mind stating which blog platform you’re working with?

    I’m going to start my own blog in the near future but I’m having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m looking
    for something completely unique. P.S My apologies for being off-topic but I had to ask!

  25. Faustino

    What i do not realize is if truth be told how
    you are now not really a lot more well-liked than you might be now.
    You are very intelligent. You realize therefore considerably when it comes
    to this matter, made me for my part imagine it from
    so many numerous angles. Its like men and women don’t seem to
    be involved except it’s one thing to do with Woman gaga!
    Your personal stuffs great. All the time maintain it up!

  26. macymcadoo.org

    Thanks for the good writeup. It in truth was once
    a leisure account it. Glance complex to far added agreeable from you!
    By the way, how could we communicate?

  27. düzce escort

    Hi there! I’m at work browsing your blog from my new iphone
    4! Just wanted to say I love reading through your blog and look forward to all
    your posts! Keep up the outstanding work!

  28. forex-watchers.com

    This post will help the internet viewers for building up new web site or even a blog from start to end.

  29. Best Free Live Porn

    you can not make me understood in language you speak.
    nothing is what we have to use for chatting about camera without japanese.

Tinggalkan Balasan

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