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.

15.976 comments

  1. 188bet ทางเข้า

    Very quickly this website will be famous amid all blogging and site-building users, due to it’s good content

  2. https://aswqs10p4dy.blogspot.com/

    Quality articles or reviews is the secret to
    interest the users to visit the site, that’s what this web page is providing.

  3. 1xBet

    Hey just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading correctly.
    I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same results.

  4. papa's pizza

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

  5. dQ3rR1uS1O7

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your
    point. You obviously know what youre talking about, why waste your intelligence on just posting videos
    to your blog when you could be giving us something informative to
    read?

  6. 카지노

    I blog often and I seriously appreciate your content.
    This article has really peaked my interest.

    I am going to take a note of your site and keep checking for new details about once per week.
    I opted in for your RSS feed too.

  7. sexlog

    It’s an remarkable paragraph in support of all the web
    users; they will obtain advantage from it I am sure.

  8. Wannonce

    I go to see each day some blogs and sites to read articles,
    however this blog provides quality based content.

  9. ベラジョン

    I all the time used to read paragraph in news papers but now as I am a user of internet so
    from now I am using net for articles, thanks to web.

  10. eJ1H5vL8aH3

    Thank you for the auspicious writeup. It in fact was a amusement account
    it. Look advanced to more added agreeable from you! However,
    how can we communicate?

  11. trò chơi

    This is really interesting, You’re a very skilled blogger. I’ve
    joined your rss feed and look forward to seeking more of your excellent post.
    Also, I’ve shared your website in my social networks!

  12. CRk0ytz0V/ZsF0cZ9S0

    My brother recommended I may like this web site. He was totally right.
    This submit truly made my day. You cann’t consider just how so much
    time I had spent for this information! Thank you!

  13. 솔레어카지노

    Howdy this is kind of of off topic but I was wanting to know if blogs use WYSIWYG editors or if you
    have to manually code with HTML. I’m starting a blog soon but have
    no coding know-how so I wanted to get advice from someone with experience.
    Any help would be enormously appreciated!

  14. online betting apps in india

    Hello friends, how is all, and what you desire to say
    on the topic of this article, in my view its actually awesome
    in support of me.

  15. beginner poker tips

    hey there and thank yоu for youur info – I’ve
    definitely picke up something new from right here. I did however expertise a few
    tecnical issues using this site, since I experienced
    to reload the site lotѕ of times previous to Ι could gеt it to lopad
    correctly. I had been wondering if your hosting is OΚ?
    Not that I am comρⅼaining, but sluggish loading instances times will s᧐metimes affeϲt your placement in gopgle ɑnd can damage your high-quality score
    if aads and marketing with Adwords. Anyway I am adԀing this RSS to
    my e-mail andd can look out for a lot more of your respective
    excitiing content. Ensure that yoou update
    this again very soon.

    My web site … beginner poker tips

  16. ドラクエ x カジノ

    Hey! Quick question that’s entirely off topic. Do you know how to make your
    site mobile friendly? My blog looks weird when viewing from my iphone 4.
    I’m trying to find a template or plugin that might
    be able to correct this problem. If you have any suggestions, please share.
    Thanks!

  17. เกมยิงปลา

    First off I would like to say wonderful blog! I had a quick question that I’d
    like to ask if you don’t mind. I was curious to know
    how you center yourself and clear your head prior to writing.
    I have had a difficult time clearing my mind in getting
    my ideas out there. I do enjoy writing however it just seems like the first 10 to 15 minutes tend to be wasted simply just trying to figure out
    how to begin. Any ideas or tips? Appreciate it!

  18. 10bet online casino

    I know this if off topic but I’m looking into starting my own weblog 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 suggestions or advice would
    be greatly appreciated. Kudos

  19. harlan music room

    Hi there, I think your web site may be having internet browser compatibility problems.
    When I take a look at your web site in Safari,
    it looks fine however, if opening in IE, it has some overlapping issues.
    I merely wanted to provide you with a quick heads up! Other than that, wonderful site!

  20. xổ số miền nam

    Wow, that’s what I was searching for, what a stuff! present here
    at this blog, thanks admin of this web page.

  21. https://r4g4bhi21e.blogspot.com/

    Every weekend i used to visit this web page, for the reason that i want
    enjoyment, as this this website conations actually good funny material too.

  22. русское порно

    Woah! I’m really enjoying the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s challenging to
    get that “perfect balance” between usability and visual appearance.
    I must say you’ve done a awesome job with this. Additionally, the blog loads
    super quick for me on Internet explorer. Exceptional Blog!

  23. houseboat rentals

    I know this web site gives quality based posts and other information, is there any other web site which offers
    these kinds of information in quality?

  24. taxi transfer nice airport

    Appreciating the commitment you put into your site and detailed information you offer.
    It’s great to come across a blog every once in a while
    that isn’t the same unwanted rehashed material.
    Wonderful read! I’ve bookmarked your site and I’m
    adding your RSS feeds to my Google account.

    my webpage: taxi transfer nice airport

  25. slot deposit pulsa

    Slot Deposit Pulsa Terpercaya Dan Slot Terlengkap
    Indo787
    slot deposit pulsa
    Slot deposit pulsa tanpa potongan slot online resmi
    Indo787, salah satu pihak penyelengara agen judi online terbaik

  26. evolution gaming

    Hi I am so happy I found your webpage, I really found you by error, while I was researching on Google for something
    else, Regardless I am here now and would
    just like to say cheers for a fantastic post and a all round entertaining blog (I also love the theme/design), I don’t have time to read it
    all at the minute but I have book-marked it and also included
    your RSS feeds, so when I have time I will be back to read more, Please do keep up
    the excellent b.

Tinggalkan Balasan

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