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.

14.885 comments

  1. Jannie

    What’s up mates, pleasant piece of writing and pleasant arguments commented at this place,
    I am in fact enjoying by these.

  2. Turkish newspapers

    Greetings! I’ve been following your weblog for a while now and finally
    got the courage to go ahead and give you a shout out from Kingwood Texas!
    Just wanted to tell you keep up the excellent work!

  3. Gardenscapes codes Deutsch 2021

    Pretty portion of content. I just stumbled upon your blog and in accession capital to
    assert that I acquire in fact loved account your weblog posts.
    Anyway I will be subscribing for your feeds or even I fulfillment you
    get admission to constantly quickly.

    My blog … Gardenscapes codes Deutsch 2021

  4. Jay

    I’m gone to convey my little brother, that he should also pay a quick visit this blog on regular
    basis to get updated from newest news.

  5. عسل المجرى

    I really like what you guys tend to be up too.
    This kind of clever work and reporting! Keep up the good works guys I’ve incorporated you guys to my own blogroll.

  6. San-servis.com

    Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter
    updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like
    this. Please let me know if you run into anything. I truly enjoy
    reading your blog and I look forward to your new updates.

  7. Karine

    I do not even know how I ended up here, but I thought this put up was once great.
    I don’t recognise who you’re however definitely you are going to a well-known blogger for those who are not already.
    Cheers!

  8. Quinton

    Hi there, i read your blog from time to time and i own a similar one and i was
    just wondering if you get a lot of spam responses?
    If so how do you reduce it, any plugin or anything you can advise?
    I get so much lately it’s driving me crazy so any assistance is very much appreciated.

  9. Logan

    I love what you guys tend to be up too. This
    type of clever work and exposure! Keep up the very good works guys I’ve you
    guys to my personal blogroll.

  10. Annett

    Your method of telling everything in this paragraph is genuinely nice, every one can without difficulty know it, Thanks a lot.

  11. Lawerence

    Hi! I’m at work surfing around your blog fro my new iphone!
    Just wanted to say I love reading through your blog and look forward to all your posts!
    Carry on thee outstanding work!

    Also visit my site frse reverse cell phone lookup free results (Lawerence)

  12. binary options pro signals

    You are so awesome! I don’t believe I’ve read something like that before.

    So good to find someone with some unique thoughts on this topic.
    Seriously.. thank you for starting this up.
    This site is one thing that’s needed onn tthe internet, someone with
    some originality!

    my page :: binary options pro signals

  13. Curtis

    Excellent beat ! I wish to apprentice even as you amend your website,
    how can i subscribe for a weblog site? The account aided me a acceptable deal.
    I had been tiny bit familiar of this your broadcast provided vibrant clear idea

  14. accelerated surgical tech program

    Hey! Someone in my Facebook group shared this website with us so I came to look
    it over. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers!
    Superb blog and terrific design and style.

  15. Demetra

    I am regular visitor, how are you everybody? This article posted at this web page
    is genuinely fastidious.

  16. best male enhancement pills at walmart canada

    I like the helpful information you provide for your articles.
    I will bookmark your blog and take a look at again right here regularly.
    I am relatively certain I’ll be informed plenty of new
    stuff right here! Good luck for the following!

  17. Fred

    Have you ever thought abot publishing an e-book orr guuest authoring onn other websites?
    I have a blog centered on the same ideas you discuss and would really like to have you share some stories/information. I
    know my readers would enjoy your work. If you’re even remotely interested, feel
    free to shoot me an e-mail.

    my web page :: gloucester conservatories (Fred)

  18. Katherin

    Hi there! I could have sworn I’ve been to this site before
    but after browsing through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely happy I found it
    and I’ll be bookmarking and checking back often!

  19. alberto carpet cleaning

    Hi! Someone in my Myspace group shared this website with
    us so I came to take a look. I’m definitely enjoying the information. I’m
    book-marking and will be tweeting this to my followers!
    Superb blog and excellent design.

    My web site; alberto carpet cleaning

  20. Qq online

    Amazing! This blog looks just like my old one! It’s on a totally
    different subject but it has pretty much the same page layout and design. Excellent choice of colors!

  21. longtail pro one-time

    You actually make itt seem so easy with your presentation but I in finding this topic
    to be atually something that I believe I would by no means understand.
    It kind of feels too complicated and extremely
    wide for me. I am looking ahead for your subsequent
    post, I’ll try tto get the cling of it!

    my site … longtail pro one-time

  22. webpage

    you are truly a just right webmaster. The web site loading speed is incredible.
    It kind of feels that you are doing any unique trick.
    In addition, Thhe contents arre masterpiece. you have done a great activity in this subject!

    газовый водонагреватель астана
    webpage электрокотел
    астана

Tinggalkan Balasan

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