Membuat Telegram Bot menggunakan PHP : Webhook dan Localhost via Ngrok

Pada postingan ini kita akan membuat Telegram bot menggunakan PHP, metode webhook, dan ngrok. Untuk membuat bot menggunakan metode webhook, kita perlu memahami konsep dasar metode webhook dan long polling. Saya telah menjelaskannya pada postingan ini : Membuat Telegram Bot Menggunakan PHP : Long Polling.

Pada tutorial ini, anda akan membuat webhook pada server localhost menggunakan metode webhook, dan tidak perlu memiliki server yang dihosting di internet.

Aplikasi yang Dibutuhkan

Untuk membuat Telegram bot menggunakan metode webhook dan PHP, kita memerlukan :

  1. Aplikasi Telegram. Download link : telegram.org.
  2. Ngrok. Download link : ngrok.com/download.
  3. PHP server (disarankan menggunakan XAMPP). Cek postingan saya tentang ini : #1 Tutorial Pemrograman Web – Menginstall XAMPP Server.

Menggunakan metode webhook, kita biasanya diharuskan untuk memiliki server atau website yang dihosting di internet, dan dapat diakses lewat internet kapanpun dan dimanapun.

Namun pada tutorial ini, kita tidak perlu hosting, karena terkadang biayanya cukup mahal. Hosting tersebut dapat digantikan dengan ngrok, sehingga kita tetap bisa menggunakan localhost. Saya akan jelaskan lebih lanjut pada bagian berikutnya.

Membuat Bot lewat Botfather

  1. Buka aplikasi Telegram, cari user @BotFather.
  2. Klik /start pada bagian bawah chat.
  3. Klik /newbot untuk membuat bot baru. BotFather akan menanyakan nama bot dan username.
  4. Setelah mengetikkan nama bot dan username, anda akan menerima chat yang berisi token bot.
    Creating Telegram Bot
  5. Selamat, anda baru saja membuat sebuah bot. Namun tentu saja bot tersebut tidak akan berfungsi apa apa karena belum diisi dengan program.

Membuat Program PHP untuk Telegram Bot

  1. Start apache web server pada localhost anda. Jika anda tidak tahu bagaimana melakukan ini, silahkan baca postingan ini : #1 Tutorial Pemrograman Web – Menginstall XAMPP Server.
  2. Untuk membuat bot tersebut hidup, kita perlu membuat sebuah project baru pada folder htdocs. Buatlah sebuah folder bernama webhook, lalu di dalam folder tersebut, lalu kita buat sebuah file baru bernama index.php.
  3. Copy dan paste script php ini ke dalam file index.php tersebut.
    <?php
    $content = file_get_contents("php://input");
    if($content){
        $token = '<YOUR BOT TOKEN>';
        
        $apiLink = "https://api.telegram.org/bot$token/";
        
        echo '<pre>content = '; print_r($content); echo '</pre>';
        $update = json_decode($content, true);
        if(!@$update["message"]) $val = $update['callback_query'];
        else $val = $update;
        
        $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 />';
    } else echo 'Only telegram can access this url.';
    
    ?>

    Ganti <YOUR BOT TOKEN> pada baris ke 4 dengan token yang dikirim oleh BotFather sebelumnya.

  4. Sekarang mari kita jalankan script tersebut. Buka browser anda, lalu ketik localhost/webhook. Anda akan melihat hasil seperti ini :
    testing webhook telegram bot 1

Setting ngrok

Konsep dasar dari ngrok adalah sangat sederhana. Dengan ngrok, anda bisa mengakses localhost anda dari internet, seolah – olah server anda dihosting di suatu tempat.

  1. Pertama – tama, kita download ngrok di sini.
  2. Extract file hasil download di komputer anda.
  3. Buka Windows Command Prompt (cmd), lalu masuk ke folder tempat anda extract file hasil download tersebut melalui cmd. Cek capture pada poin no. 4.
  4. Di dalam folder, ketik : ngrok.exe http 80
    set up ngrok
  5. Jika berhasil, anda akan melihat hasil seperti ini :
    ngrok started
  6. Periksa bagian ‘Forwarding’. Sekarang mari kita periksa hasilnya di browser. Pada contoh yang saya gunakan, saya perlu mengakses : https://d36fa284.ngrok.io/webhook.
  7. Yess, cukup mudah bukan untuk membuat localhost kita bisa diakses lewat internet. Anda tentu saja bisa mengaksesnya lewat perangkat manapun selama terhubung ke internet. Pada dasarnya, ngrok telah mengubah localhost anda menjadi d36fa284.ngrok.io yang dapat diakses lewat internet. Anda juga bisa cek project lain yang ada di folder htdocs anda dengan mengakses https://d36fa284.ngrok.io/<project apapun di dalam htdocs>.
  8. Sekarang, saya perlu memberi tahu Telegram, bahwa saya memiliki server yang berjalan pada https://d36fa284.ngrok.io. Buka browser anda, lalu ketik :

    https://api.telegram.org/bot<YOUR BOT TOKEN>/setwebhook?url=https://d36fa284.ngrok.io/webhook/

    Ganti <YOUR BOT TOKEN> dengan token bot anda. Jangan lupa tanda slash di akhir.

    Ganti juga d36fa284.ngrok.io sesuai dengan bagian ‘Forwarding’ pada ngrok anda.

  9. Selesai sudah kita melakukan setting ngrok dan webhook. Jika semuanya benar, anda seharusnya melihat hasil seperti ini :
    set webhook telegram bot
  10. Sekarang mari kita lihat log yang disediakan oleh ngrok. Buka localhost:4040 pada browser anda.
    ngrok log url
  11. Sekarang, setiap kali ada seseorang yang mengirimkan chat ke bot yang baru saja anda buat, bot tersebut akan memberikan balasan. Mari kita cek ke aplikasi Telegram.
    test bot webhook

Begitulah cara untuk membuat bot Telegram menggunakan metode webhook, namun tidak perlu memiliki website publik untuk menentukan url webhook. Anda bisa mengedit script php jika ingin bot memberikan respon yang berbeda sesuai kebutuhan. Jika anda memiliki pertanyaan atau kendala, silahkan tanyakan pada kolom komentar.

8.573 comments

  1. sabung ayam online s128

    Great goods from you, man. I’ve understand your stuff previous to and you’re just too
    wonderful. I actually like what you have acquired here, certainly like what you’re stating and
    the way in which you say it. You make it enjoyable and you still take
    care of to keep it smart. I can not wait to read much more from you.
    This is actually a tremendous web site.

  2. https://ajenako.com

    I pay a visit each day some blogs and websites to read articles or reviews,
    but this blog presents quality based content.

  3. klinika opava

    You really make it seem so easy with your presentation but I find this topic to be actually something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  4. Viro Max Ultra Reviews

    I do not even know how I ended up here, but I thought this post
    was good. I don’t know who you are but certainly you’re going to a famous blogger if you are not already 😉 Cheers!

    Also visit my site … Viro Max Ultra Reviews

  5. Jada

    Right here is the right webpage for anybody who
    wishes to find out about this topic. You understand a whole lot
    its almost hard to argue with you (not that I personally will need
    to…HaHa). You definitely put a fresh spin on a subject that’s been discussed for a long time.

    Wonderful stuff, just wonderful!

    Feel free to surf to my site … Jada

  6. ViroMax

    What’s up colleagues, fastidious post and nice arguments commented
    here, I am actually enjoying by these.

    Also visit my web page – ViroMax

  7. NeoPodz

    I regard something really interesting about your website so I saved
    to fav.

    My blog :: NeoPodz

  8. Moscatcher

    Have you ever thought about creating an ebook or guest authoring on other websites?
    I have a blog centered on the same topics you discuss and would
    love to have you share some stories/information. I know my readers would appreciate your work.

    If you are even remotely interested, feel free to send me
    an email.

    my blog post – Moscatcher

  9. Wawza Apple Cider Vinegar

    Thanks for any other informative site. Where else could I am getting that kind of info written in such a perfect means?
    I have a challenge that I’m simply now working on, and I have been at the look out
    for such information.

    Look at my blog post: Wawza Apple Cider Vinegar

  10. stefano ricci perfume

    WOW just what I was looking for. Came here by searching for christian dior yupoo

  11. 우리카지노계열

    I every time used to study post in news papers but
    now as I am a user of internet therefore from now I am using net for content, thanks to web.

  12. オンラインカジノ

    What a stuff of un-ambiguity and preserveness of valuable experience on the topic
    of unexpected emotions.

  13. ネットベットカジノ

    Hurrah! Finally I got a weblog from where I be capable of truly get useful facts regarding my study and knowledge.

  14. situs slot online terbaik

    I am extremely inspired together with your writing talents as neatly as with the format on your blog.

    Is this a paid subject matter or did you customize it your self?
    Anyway stay up the excellent quality writing, it is rare to peer a great blog like this one nowadays..

  15. hotelforrest.ru

    Hi there, just became alert to your blog
    through Google, and found that it is really informative.
    I’m gonna watch out for brussels. I will appreciate if you continue this in future.
    Numerous people will be benefited from your writing.
    Cheers!

    Also visit my blog: hotelforrest.ru

  16. Ulrike

    Way cool! Some extremely valid points! I appreciate you penning
    this post plus the rest of the site is also really good.

  17. Felisha

    Greetings! 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 useful information to work on. You have done a wonderful job!

  18. situs slot online

    Today, I went to the beachfront with my children. I found a
    sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell
    to her ear and screamed. There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is totally off topic but I had
    to tell someone!

  19. 카지노사이트

    I go to see daily a few sites and websites to read
    content, except this webpage gives feature based posts.

  20. judi nomor

    I like the valuable information you provide in your articles.
    I will bookmark your weblog and check again here frequently.
    I am quite certain I will learn a lot of new stuff right
    here! Best of luck for the next!

  21. minecraft server

    Please let me know if you’re looking for a article author for
    your blog. You have some really good articles and I believe
    I would be a good asset. If you ever want tto take some of the lload off, I’d really like too
    write some content for your blog in exchange for
    a linmk back to mine. Please shooot me an email iif interested.
    Kudos!

  22. agen judi slot online

    Terrific post however I was wondering if you could write a litte
    more on this topic? I’d be very thankful if
    you could elaborate a little bit further. Appreciate it!

Tinggalkan Balasan

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