การสร้าง LINE Bot แบบใช้ cURL ใน Yii Framework 2

wave
มานพ กองอุ่น 7 ก.ค. 2016 12:22:46 28,508

สวัสดีครับก็เป็นกระแสมาสักระยะแล้วสำหรับ LINE Bot ซึ่งตอนนี้เปิดให้ใช้งานแบบ Trial โดยยังเป็น Beta Version อยู่ ดังนั้นในบทเรียนรู้นี้มาลองทำความรู้จักกับ LINE Bot กัน กับการใช้งานผ่าน cURL กันก่อน (จริงๆ ตอนนี้มี PHP SDK) เรื่อง PHP SDK ค่อยว่ากันต่อไปครับ

ในที่นี้เราจะสร้าง LINE Bot ให้สามารถตอบโต้กับผู้ใช้งานได้ โดยใช้ API ของ wunderground เพื่อบอกสภาพอากาศ และกูรูถามตอบด้วย wikipedia API โดยให้ผู้ใช้พิมพ์คำว่า อากาศ:กรุงเทพมหานคร Bot ก็จะตอบสภาพอากาศมาให้ หรือ พิมพ์ อยากรู้:Yii Framework Bot ก็จะตอบมาให้เช่นกัน เป็นไงครับพอได้ไอเดียไหมครับ ลองทำตามดูนะครับ เพื่อเป็นแนวทางในการประยุกต์ใช้งานต่อไป

ก่อนใช้งานตรวจสอบ Server ด้วยนะว่ามีการเปิดการใช้งาน cURL ของ PHP Extension หรือยังถ้ายังก็เปิดการใช้งานก่อนนะครับ
(จริงๆ ไม่ต้องใช้ Yii2 ก็ได้ครับ สร้างไฟล์ callback.php เลยก็ได้นะ ^ ^)

สมัครใช้งาน LINE Bot

สมัครใช้งาน LINE Bot โดยเข้าเว็บไซต์ https://developers.line.me/channels 

จากนั้น Add Company

เมื่อ Add Company เสร็จแล้ว กดปุ่ม Start

จากนั้นกดปุ่ม Start ในส่วนของ BOT API Trial Account

และกดปุ่ม Start อีกครั้ง เพื่อยอมรับว่านี้เป็น Beta อยู่นะจะยกเลิกตอนไหนก็ได้ จากนั้นกรอก ชื่อ Channel และกดปุ่ม Create

จากนั้นก็จะได้ LINE Bot เรียบร้อยแล้ว

ส่วนที่สำคัญคือ

  • Channel ID
  • Channel Secret
  • MID
  • Callback URL ต้องเป็น https:// เท่านั้น และต้องระบุ Port :433 ด้วยนะ (ปกติ https ก็ 433 อยู่แล้ว)

ทดสอบโดยการกดปุ่ม Verify หากไม่มีข้อผิดพลาดก็จะปรากฏดังนี้ (ต้องสร้าง Controller Line และ action Callback ก่อนนะ)

จะเห็นว่ามี Success. สีเขียวๆ หากมี Error สีแดงก็ต้องตรวจสอบให้ถูกต้อง ถึงขั้นตอนนี้ก็เป็นอันว่าเตรียม LINE Bot เรียบร้อยล่ะ

รายงานสภาพอากาศด้วย wunderground API

ก่อนอื่นเรามาสมัคร API สำหรับการตรวจสอบสภาพอากาศกันก่อนนะครับ โดยเข้าเว็บไซต์ http://api.wunderground.com/weather/api จากนั้นสร้าง Key เมื่อทำตามขั้นตอนจะได้ดังนี้

กูรูถามตอบด้วย wikipedia API

สำหรับ Wikipedia API ไม่ต้องสร้าง Key หรือ AppID ใดๆ เพียงเลือก Format ในการ Response และรายละเอียดที่ต้องการเท่านั้น สามารถดูเพิ่มเติมได้ที่ https://th.wikipedia.org/w/api.php

โดยในที่นี้เราจะให้ Response ออกมาในรูปแบบ JSON โดยมี URL ในการ Request ดังนี้

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=PHP
  • en คือภาษาที่ใช้แสดงผลในที่นี้เราจะให้สามารถอ่านได้ทั้ง ไทยและ English (th,en)
  • titles คือข้อความหรือเรื่องที่ค้นหา

ตัวอย่างเมื่อมีการ Response

{"batchcomplete":"","query":{"pages":{"24131":{"pageid":24131,"ns":0,"title":"PHP","extract":"PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. Originally created by Rasmus Lerdorf in 1994, the PHP reference implementation is now produced by The PHP Group. PHP originally stood for Personal Home Page, but it now stands for the recursive backronym PHP: Hypertext Preprocessor.\nPHP code may be embedded into HTML code, or it can be used in combination with various web template systems, web content management systems and web frameworks. PHP code is usually processed by a PHP interpreter implemented as a module in the web server or as a Common Gateway Interface (CGI) executable. The web server combines the results of the interpreted and executed PHP code, which may be any type of data, including images, with the generated web page. PHP code may also be executed with a command-line interface (CLI) and can be used to implement standalone graphical applications.\nThe standard PHP interpreter, powered by the Zend Engine, is free software released under the PHP License. PHP has been widely ported and can be deployed on most web servers on almost every operating system and platform, free of charge.\nThe PHP language evolved without a written formal specification or standard until 2014, leaving the canonical PHP interpreter as a de facto standard. Since 2014 work has gone on to create a formal PHP specification.\nDuring the 2010s there have been increased efforts towards standardisation and code sharing in PHP applications by projects such as PHP-FIG in the form of PSR-initiatives as well as Composer dependency manager and the Packagist repository."}}}}

เอาละตอนนี้ก็ได้ตามความต้องการแล้วต่อไปมาเขียนโปรแกรมในฝั่ง Callback กัน

สร้าง Controller และ Callback Action

ผมสร้าง Controller ไว้ที่ frontend/controllers/LineController.php โดยมี Action Callback() ดังนี้

<?php
namespace frontend\controllers;

use Yii;
use yii\web\Response;

class LineController extends \yii\web\Controller
{
    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if ($action->id == 'callback') {
            $this->enableCsrfValidation = false; //ปิดการใช้งาน csrf
        }
    
        return parent::beforeAction($action);
    }
    

    public function actionCallback()
    {
        
        $json_string = file_get_contents('php://input');
        $jsonObj = json_decode($json_string); //รับ JSON มา decode เป็น StdObj
        $to = $jsonObj->{"result"}[0]->{"content"}->{"from"}; //หาผู้ส่ง
        $text = $jsonObj->{"result"}[0]->{"content"}->{"text"}; //หาข้อความที่โพสมา
        
        $text_ex = explode(':', $text); //เอาข้อความมาแยก : ได้เป็น Array
        
        if($text_ex[0] == "อยากรู้"){ //ถ้าข้อความคือ "อยากรู้" ให้ทำการดึงข้อมูลจาก Wikipedia หาจากไทยก่อน
            //https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=PHP
            $ch1 = curl_init();
            curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch1, CURLOPT_URL, 'https://th.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles='.$text_ex[1]);
            $result1 = curl_exec($ch1);
            curl_close($ch1);
            
            $obj = json_decode($result1, true);
            
            foreach($obj['query']['pages'] as $key => $val){

                $result_text = $val['extract'];
            }
            
            if(empty($result_text)){//ถ้าไม่พบให้หาจาก en
                $ch1 = curl_init();
                curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch1, CURLOPT_URL, 'https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles='.$text_ex[1]);
                $result1 = curl_exec($ch1);
                curl_close($ch1);
                
                $obj = json_decode($result1, true);
                
                foreach($obj['query']['pages'] as $key => $val){
                
                    $result_text = $val['extract'];
                }
            }
            if(empty($result_text)){//หาจาก en ไม่พบก็บอกว่า ไม่พบข้อมูล ตอบกลับไป
                $result_text = 'ไม่พบข้อมูล';
            }
            $response_format_text = ['contentType'=>1,"toType"=>1,"text"=>$result_text];
            
        }else if($text_ex[0] == "อากาศ"){//ถ้าพิมพ์มาว่า อากาศ ก็ให้ไปดึง API จาก wunderground มา
            //http://api.wunderground.com/api/yourkey/forecast/lang:TH/q/Thailand/%E0%B8%81%E0%B8%A3%E0%B8%B8%E0%B8%87%E0%B9%80%E0%B8%97%E0%B8%9E%E0%B8%A1%E0%B8%AB%E0%B8%B2%E0%B8%99%E0%B8%84%E0%B8%A3.json
            $ch1 = curl_init();
            curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch1, CURLOPT_URL, 'http://api.wunderground.com/api/yourkey/forecast/lang:TH/q/Thailand/'.str_replace(' ', '%20', $text_ex[1]).'.json');
            $result1 = curl_exec($ch1);
            curl_close($ch1);
            
            $obj = json_decode($result1, true);
            if(isset($obj['forecast']['txt_forecast']['forecastday'][0]['fcttext_metric'])){
                $result_text = $obj['forecast']['txt_forecast']['forecastday'][0]['fcttext_metric'];
            }else{//ถ้าไม่เจอกับตอบกลับว่าไม่พบข้อมูล
                $result_text = 'ไม่พบข้อมูล';
            }
            
            $response_format_text = ['contentType'=>1,"toType"=>1,"text"=>$result_text];
        }else if($text == 'บอกมา'){//คำอื่นๆ ที่ต้องการให้ Bot ตอบกลับเมื่อโพสคำนี้มา เช่นโพสว่า บอกมา ให้ตอบว่า ความลับนะ
            $response_format_text = ['contentType'=>1,"toType"=>1,"text"=>"ความลับนะ"];
        }else{//นอกนั้นให้โพส สวัสดี
            $response_format_text = ['contentType'=>1,"toType"=>1,"text"=>"สวัสดี"];
        }

        // toChannel?eventType
        $post_data = ["to"=>[$to],"toChannel"=>"1383378250","eventType"=>"138311608800106203","content"=>$response_format_text]; //ส่งข้อมูลไป
        
        $ch = curl_init("https://trialbot-api.line.me/v1/events");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charser=UTF-8',
            'X-Line-ChannelID: YOUR ChannelID',
            'X-Line-ChannelSecret: YOUR ChannelSecret',
            'X-Line-Trusted-User-With-ACL: YOUR MID'
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        
    }
}
?>

Code ด้านบนเป็นเพียงแนวทางหนึ่งนะครับสามารถประยุกต์เพิ่มเติมได้ (มีอะไรดีๆ ก็ช่วยแชร์ด้วยนะครับ)

ทดสอบการใช้งาน

ทำการ Scan Channel เพื่อเชื่อมต่อ

จากนั้นทดสอบพิมพ์

อากาศ:กรุงเทพมหานคร

หรือพิมพ์ อยากรู้:Yii Framework

หรือพิมพ์ บอกมา

หรือพิมพ์อย่างอื่น เช่น สวัสดี

บทสรุป

LINE Bot API ยังอยู่ในขั้นตอนของการทดสอบ Beta Version ซึ่งยังไม่ Stable LINE อาจมีการยกเลิกการใช้งานเมื่อไหร่ก็ได้ การใช้งาน LINE Bot ต้องมี Web ที่เป็น SSL ซึ่งก็มีข้อจำกัดอยู่ แต่เพื่อความปลอดภัยก็คงต้องปรับใช้ SSL กันนะครับ

เพื่อนๆ มีไอเดียดีๆ หรือนำไปประยุกต์ใช้ก็สามารถมาแชร์กันได้นะครับ ตอนหน้าคงเป็นเรื่องการใช้งาน LINE Bot PHP SDK ครับค่อยติดตามกันนะครับ

ท้ายนี้ก็หวังเป็นอย่างยิ่งว่าเพื่อนๆ จะสามารถนำไปประยุกต์ใช้งานกับงานของตัวเองได้นะครับ


ความคิดเห็น

หากบทเรียนรู้มีความผิดพลาดประการใด หรือมีข้อเสนอแนะกรุณาแจ้ง contact@programmerthailand.com

เขียนบทเรียนรู้ของคุณ

รายละเอียด
  • ดู 28,508
  • รักเลย 0
  • หมวดหมู่ Yii Framework 2 (Yii2)
  • เขียนเมื่อ
  • แก้ไขเมื่อ
  • Tags yii line bot
ข้อมูลผู้เขียน
มานพ กองอุ่น

มานพ กองอุ่น

เป็นสมาชิกเมื่อ: 18 ธ.ค. 2009

เนื้อหาที่เกี่ยวข้อง