Membuat Telegram Bot Menggunakan PHP : Long Polling

Sebelum membaca post ini, pastikan anda sudah memahami konsep dasar Telegram BOT API. Saya telah membuat post tentang ini sebelumnya.

Apa Saja yang Diperlukan untuk Long Polling

Untuk membuat program long polling pertama kita menggunakan Telegram BOT API, kita memerlukan :

  1. Web Server (bisa local atau hosting)
  2. Koneksi internet yang lancar
  3. Scheduler untuk melakukan request ke telegram.org setiap beberapa detik sekali (Windows sudah memiliki fitur bawaan Windows Scheduler)
  4. Aplikasi Telegram. Download aplikasinya di telegram.org.

Pada tutorial ini, kita akan membuat bot yang dapat membalas sebuah pesan sederhana. Kita akan dapat mengatur balasan sesuai dengan pesan yang kita kirimkan melalui bot.

Tahapan Pembuatan Telegram Bot dengan Metode Long Polling

  1. Buka aplikasi Telegram, kemudian cari user @BotFather.
  2. Klik tombol /start di bagian bawah chat.
  3. Klik /newbot untuk membuat bot baru. BotFather akan meminta anda untuk mengetik nama dan username bot baru.
  4. Setelah memasukkan nama dan username, anda akan menerima pesan yang berisi token dari bot anda.
    Membuat Telegram Bot
  5. Selamat, anda baru saja membuat sebuah bot. Namun tentu saja, tanpa melakukan tindak lanjut apapun, bot ini tidak berguna, karena belum diprogram. Untuk membuat bot ini hidup, kita perlu membuat project di workspace. Jika anda belum tahu cara membuatnya, silahkan membaca post ini : #1 Tutorial Pemrograman Web – Menginstall XAMPP Server. Mari kita namakan folder project baru tersebut longpolling. Di dalam folder longpolling, kita buat sebuah file dengan nama index.php.
  6. Copy dan paste kode php di bawah ini ke dalam file index.php tersebut.
  7. <?php
    $token = '<YOUR BOT TOKEN>';
    
    $apiLink = "https://api.telegram.org/bot$token/";
    $update = file_get_contents($apiLink.'getUpdates');
    $updateArray = json_decode($update, TRUE);
    
    if($updateArray['result']){
        foreach($updateArray['result'] as $key=>$val){
            $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 />';
            
            file_get_contents($apiLink.'getUpdates?offset='.($update_id+1));
        }
        
    } else echo 'No new Updates';
    
    ?>

    Ganti <YOUR BOT TOKEN> di baris kedua dengan token yang dikirim oleh telegram BotFather.

  8. Sekarang kita coba jalankan script tersebut. Buka browser anda, kemudian ketik url localhost/longpolling. Anda seharusnya melihat hasil seperti ini :
    Membuat Telegram Bot
  9. Kembali ke aplikasi Telegram, cari nama bot anda. Contoh yang saya buat, usernamenya adalah dryanchristoph_bot. Buka pesan di bot tersebut, lalu klik Start.
  10. Tidak akan ada balasan setelah melakukan klik Start. Namun jangan kuatir, tinggal selangkah lagi untuk bot tersebut bisa menjawab pesan kita.
    Membuat Telegram Bot
  11. Jalankan lagi script tadi lewat browser, ketik localhost/longpolling pada browser anda.
  12. Hasilnya, akan muncul teks di halaman web yang berisi data user dan teks yang dikirim. Di akhir, ada teks : “Response Sent.”.
    Membuat Telegram Bot
  13. Bersamaan dengan tahap sebelumnya, seharusnya anda juga mendapat notifikasi pesan telegram. Periksa pesan tersebut, dan begitulah bot baru anda bekerja.
    Membuat Telegram Bot
  14. Coba refresh scriptnya lagi di browser anda, maka updates terakhir akan hilang lagi. Sekarang anda dapat mencoba mengirim pesan apapun ke bot tersebut, kemudian jalankan kembali script di browser anda, maka bot akan memberikan respon.

Tapi tunggu dulu, bot macam apa yang memerlukan kita untuk selalu menjalankan script ketika ada user yang mengirim pesan? Namun memang begitulah konsep dari long polling. kita harus selalu melakukan pengecekan setiap beberapa detik sekali, untuk mengetahui ada atau tidak user yang mengirim pesan ke bot kita. Untuk itu, kita memerlukan Scheduler yang aplikasinya sudah ada di aplikasi bawaan Windows, yang bernama Windows Scheduler. Aplikasi ini akan membantu kita menjalankan script tersebut otomatis setiap beberapa detik sekali tanpa perlu repot – repot membuka browser lagi. Saya telah membuat post terpisah tentang ini : Membuat Windows Scheduler Untuk Menjalankan Program Otomatis.

Jadi begitulah bagaimana cara membuat Telegram Bot yang dapat membalas chat kita menggunakan metode long polling. Jika ada pertanyaan, silahkan tanya di kolom komentar ya.

12.254 comments

  1. moje psychologie

    First off I want to say great 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 mind prior
    to writing. I’ve had a difficult time clearing my mind
    in getting my thoughts out. I truly do take pleasure
    in writing but it just seems like the first 10 to 15 minutes are
    generally lost simply just trying to figure out how to begin.
    Any recommendations or hints? Kudos!

  2. f1immigration.com

    Your style is very unique in comparison to other folks I have read stuff
    from. Thank you for posting when you have the opportunity, Guess I’ll just
    bookmark this blog.

  3. BIT LY

    I really like what you guys are up too. This sort of clever
    work and coverage! Keep up the fantastic works guys I’ve added
    you guys to our blogroll.

  4. Free Roblox Robux

    Hi, everything is going perfectly here and ofcourse every one is sharing data, that’s genuinely fine, keep up writing.

  5. CHECK HERE

    Hello, its pleasant paragraph on the topic of media print, we all be familiar with media is a wonderful source of facts.

  6. BIT LY

    Thank you for the auspicious writeup. It in fact was a amusement account
    it. Look advanced to far added agreeable from you!
    By the way, how could we communicate?

  7. 유튜브 음원 추출 사이ㅡ

    Very great post. I just stumbled upon your blog and wished to mention that I have really enjoyed surfing around your weblog posts.
    After all I’ll be subscribing to your feed and I am hoping you write
    once more soon!

  8. Ivykam

    [url=https://propeciaafinasteride.com/]generic propecia prescription[/url] [url=https://forcepharmacy.com/]recommended canadian pharmacies[/url] [url=https://cialistore.com/]how to order cialis from canada[/url] [url=https://amoxicillintrimox.com/]how to order amoxicillin online[/url] [url=https://yasmintab.com/]yasmin pill pharmacy[/url] [url=https://amoxicillindrug.com/]amoxil 250[/url] [url=https://synthroidlevo.com/]synthroid 88 mcg[/url] [url=https://clomidoral.com/]where can i get clomid online[/url] [url=https://hicialis.com/]cialis online pharmacy india[/url] [url=https://fildenasildenafil.com/]price of viagra 2018[/url] [url=https://buyazithromycinzithromax.com/]azithromycin otc usa[/url] [url=https://saleviagra.com/]order viagra united states[/url] [url=https://zyloprimallopurinol.com/]order allopurinol[/url] [url=https://finasteridefinpecia.com/]propecia over the counter australia[/url] [url=https://tetracyclinepill.com/]tetracycline purchase online[/url]

  9. espiral

    I was recommended this website by my cousin. I’m
    now not certain whether this submit is written by way of him as nobody else recognise such
    targeted about my difficulty. You are incredible! Thank you!

  10. sex In the woods

    Dex…we were doing so good. I promised to not politics at your funeral…you opened up about the Mandalorian…

    Then you go and post this white hot garbage opinion. Why you gotta be this way

    WHY DO YOU PUSH ME AWAY LIKE THIS!

  11. Arcade Hunter MOD APK

    Therefore, the player needs to get acquainted with every character
    so as to be able to win in all situations.

  12. Hobby

    Your way of explaining all in this paragraph is really good, every one can without difficulty know it,
    Thanks a lot.

  13. show cam sex

    I use the support style one because of problems with my
    legs, and feel grate at the end of the day. In her research she found that 56 percent of divorce cases involved
    one party having an obsessive interest in pornographic websites.

    He went through the Hell of chronic British racism
    against Black Africans, from the day he started university
    to several years down the line, all by himself, without ever
    having any family to turn to. I’m having an affair with
    a married man. In the final analysis, the record provided by prehistoric studies
    in Southern Africa shows the high interior plateau lands to have played a leading part in the evolution of Man the tool-maker.
    Had I reported this phenomenon in my working days, I am sure
    I would have been scoffed at and summarily dismissed as a
    nut case. When women are working in Saudi Arabia they are required to have a
    separate area for their offices and relaxation, the company is inspected on a
    regular basis by the “ministry” to ensure that these rules are not broken!

  14. mobilarian alternative

    Membuat Telegram Bot Menggunakan PHP : Long Polling – Dryan Christoph Personal Website
    is one of the best and we actually referred our hundred or thousands of members to your
    site.
    If you dont mind please refer them to our site if they want to download movies?
    https://lucidire.com

  15. Katherin

    This paragraph is genuinely a good one it helps new internet visitors, who are wishing in favor of blogging.

  16. zprávy

    I am regular visitor, how are you everybody? This paragraph posted
    at this site is truly fastidious.

  17. Legal Injectable Steroids For Sale

    Top 5 Best Steroid Cycles For 2019

    You might be inflicting harm to your physique that you just can not reverse.

    Instead, use wholesome choices such as good diet and train. If you could have used anabolic steroids and are having well being issues,
    see your doctor to get the right therapy. After narrowing your
    list to protected and legally permitted steroids, learn evaluations concerning the brands on your list.
    Many bodybuilding professionals share their views and thoughts about
    particular manufacturers. You get a superb opportunity to
    search out out what professionals are saying about brands you are considering.

    Regardless of the nickname, most are familiar with
    using anabolic steroids within the general population. But what results do
    anabolic steroids have on the human body? In this module,
    we are going to discover the intended makes use of and potential unwanted side effects of the misuse of anabolic steroids.

    The information found in this research suggests a potential pattern shift from clandestine conferences to easily ordering drugs off of the internet to partake in AAS abuse.

    The fact that the medicine on the web sites reviewed on this research had been solely
    supplied in injectable varieties raises the priority even higher for the
    chance of blood borne pathogens, similar to Hepatitis B, Hepatitis C, and HIV.

    An interesting observe, not only was this anabolic hormone first synthesized for equestrian use the drug Boldenone- Undecylenate and the commerce name Equipoise is
    shared by a champion race horse that carried the same name.
    If you’re utilizing anabolic steroids and not using a physician’s prescription,
    cease.
    Pertinent to the route of injection, abusers of
    steroids could subscribe to risky injection practices, making them extra vulnerable
    to blood borne pathogens similar to hepatitis B, hepatitis
    C, and HIV/AIDS. Signs and signs of hepatitis C vary from asymptomatic to chronic issue.

    Many well being complement manufacturers have realized the growing importance of this
    useful hormone and are providing a range of testes boosting supplements to satisfy the wants of end users.

    Whether you wish to bulk your muscle mass or enhance your bodily strength, you will discover a testes booster available in the market.
    While this enables you entry to numerous products, it makes your
    alternative actually tough. You ought to buy wisely in order to pick the best supplement in your specific well being
    needs.

    Testosterone

    Meanwhile, exercise fanatics Tom Platz and Mike Mentzer used
    steroids to push their exercise regimens beyond the outer limits of human possibility.
    Use of anabolic steroids can subsequently result in a number of harmful
    bodily unwanted effects with shrunken testicles
    and male breast growth most likely. Scientists also seen that it helps
    decrease glucocorticoids like cortisol, which eat away at
    muscle mass especially throughout stress or disease. And finally, just
    like all anabolic steroids, you possibly can anticipate a boost in nitrogen retention in the muscles, making
    it easier to build lean muscle mass and more durable to lose
    it again.
    Eight of the ten websites recovered met inclusion criteria for the research.

    They found that 87% of websites supplied a number of different types of steroids.
    None of the websites they investigated required a prescription for such medications, but as a substitute
    included a disclaimer that customers have been topic to local
    laws. The web sites even offered resources on tips on how
    to take these drugs, together with stacking and pyramiding information. Additionally, not one of
    the drugs supplied on the reviewed websites had been oral meds; they were all injectable options .
    These findings must be of paramount curiosity to the healthcare supplier, significantly to those
    caring for at-danger populations.
    This legal steroid is used for enhanced power,
    stamina, muscle achieve, aid from joint pains,
    quick recovery and for bulking and cutting cycles.

    This method will increase the manufacturing of red blood cells, enhances the protein synthesis and nitrogen retention which helps
    you give further power and gain in muscular tissues.
    Horse steroids, anabolic steroids for a horse right; properly certain but
    in reality no, not so much, in-fact we may simply as easily call horse steroids cow
    steroids or higher yet, athletic steroids. You see ultimately
    it all boils down to who or what’s utilizing it; whereas certain anabolic drugs were first developed for horses, in many situations a use
    in people would quickly be discovered too. A prime instance is that of Equipoise in-reality, not
    solely is this one of the best instance but when there may be
    an anabolic steroid that’s greatest labeled a horse steroid it is that of EQ.

    This must all the time pathology extended durations, it can headset user — not feeling large enough or robust sufficient.

    If needed, the active development steroid other choices that roids, Stackers, Weight
    gave them a battery of exams that they did on an iPad, on a touchscreen pc.

    I do consider in the possibility of change within the not so distant future.

    My view on this, by the best way, is shared by
    many of the distinguished unbiased authorities in the field.

    In addition to those effects, steroid users are more prone to excessive-threat behaviors.

    A prognosis of steroid abuse is typically primarily based on a
    urine or blood sample.
    The ease with which customers can obtain such high-danger medicines should spur
    more research into the measures that might be taken to prevent such dangerous behaviors.
    As testosterone is a systemic hormone, it is associated
    with side effects that span the complete body. From gingivitis to increased
    urination, AAS abuse may cause a litany of unwanted symptoms.

    Patients could present with extreme pimples and other dermatologic complaints.

    What Are Steroids?

    Even although the grip would strengthen using
    steroids would continue to rise and inevitably result
    in how we perceive bodybuilding right now. Legendary
    bodybuilders similar to Sergio Oliva, Dave Draper and Larry Scott have been displaying physiques not
    like any had ever seen but as soon as once more, the 1960’s would pale as compared for what was to come.
    As Vince Lombardi is to soccer so is Eugene Sandow to bodybuilding but what does this should do with steroids?
    We can confidently say Sandow didn’t use synthetic anabolic
    steroids, in any case, they weren’t out there until the late 1930’s but there have been other
    comparable methods out there at the time. McBride, Carson and Coward investigated the purchase
    of AASs over the Internet.
    In line with reviews, narrow your record additional to a few merchandise that obtain maximum optimistic
    suggestions. Subsequently, the body doesn’t form new muscle tissue and wholesome bones.
    A one who experiences this condition must take steroids to enhance the manufacturing of the mentioned physique features.

    During this span, competitors downplayed the unfavorable
    beauty unwanted effects of the available steroids, similar to bloating and acne.
    Former chemistry teacher Frank Zane, who claimed the trophy at three Olympias starting in 1977,
    introduced a brand new degree of precision to drug dosages
    and timing.

    Understand Precisely What Steroids Are

    This module is intended to inform the healthcare professional of the supposed usages and potential detrimental effects of the abuse of anabolic
    steroids. Since 2004, producers of prohormones have taken several different methods to maintain their merchandise on the market.
    One strategy is to make use of estrogen derivatives and illicitly add different undeclared anabolic steroids to those.

    A second approach is the usage of plant-based mostly phytoandrogens , which are presently obtainable over-the-counter within the United States.

    Examples of phytoandrogens embody triterpenoids and pine pollen. A third method is thru using “designer steroids” which are specifically produced to bypass the legal restrictions
    on anabolic steroids and prohormones, while maintaining
    androgenic and anabolic actions. There are some legitimate medical
    makes use of for anabolic steroids, together with the remedy
    of anemia and to reverse protein loss in patients who’ve extended immobilization following
    extreme sickness, trauma, or surgical procedure.
    Anabolic steroids are also used for appetite stimulation and maintenance of muscle mass in sufferers with ailments corresponding to cancer and AIDS.
    It is important to note that anabolic steroids are nothing however synthetic options of testosterone.
    In different phrases, they are chemical substitutions of pure testosterone that are meant to improve potency.
    Additionally, there are several bodily conditions and side effects that some individuals complain of and
    suffer from when they’re using anabolic steroids. Although this isn’t essentially true, this is likely one of the main causes that bodybuilders,
    and those that raise in general, are drawn to using anabolic steroids.
    I by no means knew that a product like Crazymass’s D-Anaoxn would be obtainable with
    out prescription and would be legal. Nowadays, it looks as if every little
    thing that is being advertised has a catch and may have health dangers.

    Testosterone And Its Esters

    Initially the person might complain of generalized malaise, ache, weakness, nausea,
    vomiting, and liver enlargement/tenderness. This usually occurs in the
    first 21 days of infection, in any other case generally known as
    the preicteric section. The patient then might enter a part with the presentation of basic jaundice, clay coloured stools, and dark
    urine, which is the icteric part. Finally, in the posticteric section, fatigue and liver
    enlargement may continue for several months . As discussed above, abusers of
    AASs are extra prone to mood swings, hostility, and violence.

    Aggression during use and depression when the
    steroids are discontinued is frequent. Many abusers report
    that they partake in steroids purely for beauty functions,
    quite than elevated muscle strength, supporting the truth
    that many probably undergo from muscle dysmorphia.

    One generally used laboratory advertises a urine check for
    40 different anabolic compounds. Professional sports activities carry out
    rigorous checks by way of blood and urine to determine
    athletes which might be abusing AASs and different performance-enhancing medicine.
    Anti-Doping Agency budgeted $2 million per yr to analysis the areas of AAS and different doping agents (hormones, oxygen transport-enhancing
    substances, and genetic doping, among others). Despite this research within the detection of steroids and
    other efficiency-enhancing substances, new compounds are regularly being developed which might be
    undetectable. Anabolic steroids, extra appropriately known as anabolic-androgenic steroids
    or AAS, are prolific in current society. According to Ip et al.
    , “the global lifetime prevalence fee of AAS use is 3.three%, and it is estimated that 2.9-4 million Americans aged years old have used AAS . Patients may use AASs for increased muscle mass, improved appearance, and elevated confidence.
    One day my friend confirmed me how he has gained massive muscle mass simply after 3 months of use of this legal steroid. The better part is that buying this product is straightforward and hassle free, you don’t need any sort of prescription for purchasing this product. Now I am extra satisfied as I actually have used this steroid and have gained lean muscle mass. Taking this legal steroid is straightforward and don’t have any type of unwanted effects. In just six weeks of time span, this legal steroid helped me achieve seven kilos of strong muscle mass. I even have tried other supplements as properly however none of them help me gain this much muscle mass in such a brief time period. Moreover, I also noticed that after taking Deckadrolone, I am feeling stronger.

    Also visit my page :: Legal Injectable Steroids For Sale

  18. cbd oils

    Excellent beat ! I wish to apprentice while you amend your web site, how can i
    subscribe for a blog site? The account helperd mee a acceptable
    deal. I had been tiny bit acquainted of this your broadcast offered bright clear
    idea

  19. aecbet

    เว็บไซต์ปากทางเข้า AECBET ผู้ให้บริการพนันออนไลน์ครบวงจร ที่จะขึ้นเป็นอันดับ 1
    ของทวีปเอเชีย เพราะอะไรพวกเราถึงมั่นใจและก็วางเป้าสูงขนาดนั้น นั่นเป็นเพราะว่าเราให้ความใส่ใจกับทุกความมั่นใจ สร้างความเชื่อมั่นและมั่นใจ ทุกบริการ ทุกภาพลักษณ์ ทุกการดูแลรักษาฐานลูกค้า พร้อมด้วยเปิดรับลูกค้าใหม่ๆเสมอโดยเหตุนั้น เราจะไม่หยุดพัฒนากระทั่งกำลังจะถึงวัตถุประสงค์ แม้กระทั้งถึงเป้าแล้วพวกเราก็จะ ขยายความสามารถตนเองขึ้นไปอีก

  20. Link

    hey there and thank you for your information – I have certainly picked up anything new from right here. I did however expertise a few technical issues using this web site, as I experienced to reload the web site a lot of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I am complaining, but sluggish loading instances times will often affect your placement in google and can damage your high quality score if advertising and marketing with Adwords. Anyway I’m adding this RSS to my e-mail and could look out for much more of your respective exciting content. Make sure you update this again soon..

  21. Learn Software Engineering

    What’s up to every one, for the reason that I am actually
    keen of reading this weblog’s post to be updated
    regularly. It contains nice material.

  22. mobile εφαρμογές

    This is a very good tip particularly to those fresh to the blogosphere.
    Short but very accurate info… Appreciate your sharing this one.
    A must read post!

  23. sexy webcam chat

    You’ve seen my shoes and clothing collection .
    Don’t worry I’ve got your present sorted >xx>

  24. Free Piano Sheet

    I needed to thank you for this excellent read!! I absolutely enjoyed every little bit of it.
    I have got you saved as a favorite to check out new
    things you post…

Tinggalkan Balasan

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