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.

6.354 comments

  1. have a peek at this web-site Porsche Taycan Wiki

    Thanks on your marvelous posting! I seriously enjoyed reading it,
    you might be a great author.I will always bookmark your blog and will come back
    in the future. I want to encourage yourself to continue your great job, have a nice morning!

  2. 10 reason to learn english

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

  3. Adultfrienfinger

    I like the helpful info you provide in your articles.
    I will bookmark your weblog and check again here regularly.
    I’m quite sure I’ll learn many new stuff right here!
    Best of luck for the next!

  4. Charline

    Great web site. Lots of useful info here. I’m sending it
    to several friends ans additionally sharing in delicious.
    And obviously, thanks on your effort!

    My page; dr oz miracle fat burning pill; Charline,

  5. click here

    I know this if off topic but I’m looking into starting my own blog and
    was curious what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny?

    I’m not very web smart so I’m not 100% certain. Any recommendations
    or advice would be greatly appreciated. Thanks

  6. online dating sites

    My brother recommended I might like this blog. He was entirely right.
    This post actually made my day. You cann’t imagine just how much time
    I had spent for this information! Thanks!

  7. joker

    Awesome issues here. I am very glad to peer your article.
    Thank you so much and I’m having a look ahead to contact you.
    Will you please drop me a mail?

  8. 광주 오피업체

    We offer most essential living options such as
    facility beds, sofas, air conditioners, refrigerators, etc.

    to the current trend, comparable to a rise in single-person households and frequent residential changes.

  9. No Strings Attached

    There’s certainly a great deal to learn about this issue.
    I love all of the points you made.

  10. บาคาร่า

    Ahaa, its pleasant conversation about this post here at this web site, I have read all that, so now me also commenting here.

  11. sexy cam live

    Super Model Chinese Girl Strip ON CAM pinaysexscandal s
    YDY4842BS3 …

  12. sbobet

    My family members all the time say that I am killing
    my time here at net, except I know I am getting experience daily by reading thes fastidious articles.

  13. Situs Slot Online Terbaik 2020

    Excellent post. I was checking constantly this blog and I
    am impressed! Extremely useful information specifically the
    last part 🙂 I care for such information a lot. I was looking for this particular info for
    a long time. Thank you and best of luck.

  14. online dating sites

    Hello there! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest writing a blog post or vice-versa?
    My site discusses a lot of the same topics as yours and I think we could greatly benefit from each other.
    If you might be interested feel free to send me an e-mail.
    I look forward to hearing from you! Excellent blog by the way!

  15. web page

    Aw, thiss was an incredibly good post. Spending some time
    and actual effort tto create a top notch article…
    but what can I say… I procrastinate a lot
    and never seem tto get anything done.
    web page

  16. Fermelique Skin Care

    I enjoy you because of your whole efforts on this site.
    My mom enjoys carrying out internet research and it’s easy to understand why.
    Many of us notice all regarding the dynamic way you give precious steps
    through the blog and welcome contribution from some other people about
    this concern while our own child is always understanding a lot.
    Take pleasure in the rest of the year. You’re the one conducting
    a superb job.[X-N-E-W-L-I-N-S-P-I-N-X]I’m extremely inspired with your writing skills
    and also with the layout for your blog. Is this a paid theme or did you
    customize it yourself? Anyway stay up the nice high quality writing, it is rare to peer a nice blog like this
    one these days.

    my blog … Fermelique Skin Care

  17. vps

    I’m really loving the theme/design of your weblog. Do you ever
    run into any internet browser compatibility issues? A couple
    of my blog audience have complained about my blog
    not working correctly in Explorer but looks great in Firefox.

    Do you have any ideas to help fix this issue?

  18. www.google.az

    Thank you, I’ve recently been searching for information about this subject
    for a long time and yours is the best I have came upon so far.
    But, what about the conclusion? Are you sure in regards to the
    supply?

  19. Abel Pontarelli

    Hello there, I found your web site via Google while searching for a related topic, your web site came up, it looks good. I have bookmarked it in my google bookmarks.

  20. บาคาร่า

    Right now it looks like Expression Engine is the preferred blogging platform out there right now.
    (from what I’ve read) Is that what you’re using on your blog?

  21. Corporate Identity Creation Services Providers

    Nice post. I learn something new and challenging on websites I stumbleupon everyday.
    It’s always helpful to read articles from other authors and practice something from other web sites.

  22. mother in law sex

    chatrooms for singlesdating sites without registrationfemale searching malefind people on dating
    sitesonline cam room

  23. Legit Online Casinos

    However, it’s important to notice that these
    figures are drawn from hundreds of hundreds of
    transactions.

  24. read more

    Excellent post. I was checking constantly this weblog and I’m inspired!
    Very helpful information specially the remaining part 🙂 I maintain such
    information much. I used to be seeking this particular
    info for a long time. Thanks and good luck.

Tinggalkan Balasan

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