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.

13.514 comments

  1. 제왕카지노

    Thank you for sharing your thoughts. I truly appreciate your efforts and
    I am waiting for your further write ups thank you once again.

  2. jackpot

    This post is in fact a nice one it assists new web viewers, who
    are wishing in favor of blogging.

  3. カジノ x ボーナス 条件

    you are actually a excellent webmaster. The site loading pace is incredible.
    It seems that you are doing any distinctive trick.
    Furthermore, The contents are masterwork. you’ve
    done a excellent activity on this topic!

  4. Cash Offer Please

    Cool blog! Is your theme custom made or did you download it from
    somewhere? A theme like yours with a few simple tweeks would really make my
    blog shine. Please let me know where you got your design. Cheers

  5. titanium rings

    You’re so interesting! I do not believe I have read through something like this before.
    So nice to find someone with a few genuine thoughts on this issue.
    Really.. thanks for starting this up. This website is something that’s needed on the
    web, someone with some originality!

  6. 카지노사이트

    Hi there, yup this piece of writing is genuinely good and
    I have learned lot of things from it regarding blogging.

    thanks.

  7. kickr climb

    I do not know if it’s just me or if everyone else encountering problems with your
    site. It appears as though some of the text within your posts are running off the screen. Can somebody
    else please provide feedback and let me know if this is
    happening to them too? This may be a issue with my browser because I’ve had this happen before.
    Thank you

  8. television ratings

    of course like your website however you have to test the spelling on quite a few of your posts.

    A number of them are rife with spelling problems and I in finding it
    very bothersome to tell the reality however I will definitely come back again.

  9. 007카지노

    Hey there are using WordPress for your blog platform? I’m new to
    the blog world but I’m trying to get started and create
    my own. Do you need any html coding knowledge to make your own blog?
    Any help would be really appreciated!

  10. diffusion definition biology

    Hey there, I think your blog might be having browser compatibility issues.
    When I look at your blog in Chrome, it looks fine but when opening in Internet Explorer, it has some
    overlapping. I just wanted to give you a quick
    heads up! Other then that, superb blog!

  11. ビットスターズ

    May I simply say what a comfort to find an individual who truly understands what they’re
    talking about over the internet. You actually know how to bring an issue to light
    and make it important. More people should look at this and understand this side of your story.

    It’s surprising you’re not more popular since you most certainly have the gift.

  12. juice cleanse

    Just desire to say your article is as astonishing.
    The clarity to your put up is just spectacular and i can think you’re an expert on this
    subject. Fine along with your permission let me to snatch your
    feed to stay up to date with imminent post. Thanks one million and please carry on the rewarding work.

  13. 퍼스트카지노

    Wow that was unusual. I just wrote an really long comment but after I
    clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that
    over again. Anyway, just wanted to say fantastic blog!

  14. 빅카지노

    It’s going to be finish of mine day, except before ending I am reading this fantastic post to improve my know-how.

  15. 우리카지노

    Hello, I enjoy reading through your article post.
    I wanted to write a little comment to support you.

  16. 솔레어카지노

    Hey there would you mind sharing which blog platform you’re working with?

    I’m looking to start my own blog soon but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems
    different then most blogs and I’m looking for something completely unique.
    P.S Sorry for getting off-topic but I had to ask!

  17. birds for sale

    Wow, wonderful blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your
    site is magnificent, let alone the content!

  18. ジパングカジノ勝てない

    Currently it seems like Drupal is the preferred blogging platform available right now.
    (from what I’ve read) Is that what you are using on your blog?

  19. french tip nails

    Great blog here! Also your web site loads up fast!
    What web host are you using? Can I get your affiliate link to your
    host? I wish my site loaded up as fast as yours
    lol

  20. 코인카지노

    Hey There. I found your blog using msn. This is an extremely well written article.
    I will be sure to bookmark it and return to read more of your
    useful information. Thanks for the post. I will definitely
    return.

  21. Payday loans

    Right away I am ready to do my breakfast, when having my breakfast coming over again to read more news.

  22. Titanium watch

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get
    three emails with the same comment. Is there any way you can remove me from that service?
    Bless you!

  23. titanium armor

    WOW just what I was searching for. Came here by searching for titanium armor

  24. 메리트카지노

    Greetings from Ohio! I’m bored to death at work so I decided to check out your website on my iphone during lunch break.
    I love the information you provide here and can’t wait to take a look when I get home.
    I’m amazed at how quick your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyways, wonderful site!

  25. バカラ カジノ

    I am sure this piece of writing has touched all the internet
    viewers, its really really nice post on building up new website.

  26. 우리카지노

    I was suggested this web site via my cousin. I am no
    longer sure whether this post is written by means of him as no
    one else understand such precise about my problem. You’re incredible!
    Thanks!

  27. 더킹 카지노

    Hello there, You’ve done a fantastic job.
    I will definitely digg it and personally
    suggest to my friends. I’m sure they’ll be
    benefited from this web site.

  28. kaleidos makeup

    Pretty section of content. I just stumbled upon your weblog and in accession capital to say that I acquire
    actually enjoyed account your blog posts. Anyway I will be subscribing to your feeds or even I success you get
    entry to constantly fast.

  29. 베트웨이

    Do you have any video of that? I’d love to find out more details.

  30. 더킹 바카라

    It’s a pity you don’t have a donate button! I’d most certainly donate to
    this outstanding blog! I suppose for now i’ll settle for bookmarking and adding
    your RSS feed to my Google account. I look forward to fresh updates and will
    talk about this blog with my Facebook group. Talk soon!

Tinggalkan Balasan

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