สร้าง LINE Notify สำหรับ Post ลงกลุ่มใน LINE Group

wave
มานพ กองอุ่น 4 พ.ย. 2016 11:24:57 85,538

บทเรียนรู้นี้เป็นการทดสอบการเขียนโปรแกรมใน Yii2 เพื่อส่งข้อมูลเข้า LINE Group โดยใช้ Notify Bot โดยเป็นการดึงข้อมูลจากฐานข้อมูลแล้วส่งข้อมูลเข้ากลุ่ม (เป็นตัวอย่างการทดสอบ) โดยมีขั้นตอนต่างๆ ดังนี้

  1. เข้า LINE Notify Login เพื่อสร้าง Token และ Bot
  2. เพิ่ม LINE Notify เข้าใน LINE Group
  3. เขียนโปรแกรมใน Yii2 เพื่อเลือกข้อมูลสำหรับส่ง Notify
  4. สร้าง Cronjob ให้สคริปทำงานตามรอบที่ต้องการ
  5. ทดสอบการใช้งาน

หมายเหตุ rate limit อยู่ที่ 1,000 ครั้งต่อชั่วโมง

เข้า LINE Notify Login เพื่อสร้าง Token และ Bot

เข้าระบบที่ https://notify-bot.line.me/th/ จากนั้นไปที่ เมนูขวาบน เลือก My page

จากนั้นคลิกที่ปุ่ม Generate token

จากนั้นใส่ชื่อ Bot และเลือกกลุ่มที่ต้องการให้ Bot ทำงาน จากนั้นกดปุ่ม Generate Token

จะปรากฏ Popup รหัส Token

คัดลอกไว้ก่อนครับหรือเปิดหน้านี้ทิ้งไว้ก่อน ค่อยเอาไปใส่ใน Yii2 อีกครั้งครับ

เพิ่ม LINE Notify เข้าใน LINE Group

ก่อนที่จะให้ LINE Notify ทำงานให้ทำการ Invite LINE Notify ในกลุ่มก่อนนะครับ โดยเข้า LINE App ในโทรศัพท์แล้ว เข้าไปกลุ่มที่เราสร้างขึ้น จากนั้นคลิกลูกศรชี้ลงที่มุมขวาบนจากนั้นเลือก Invite แล้วค้นหา LINE Notify จากนั้นก็เพิ่มเข้ามาใน Group ได้เลยครับ จะปรากฏข้อความดังนี้

เขียนโปรแกรมใน Yii2 เพื่อเลือกข้อมูลสำหรับส่ง Notify

สร้างตาราง line_bot แล้ว Generate Model LineBot ให้เรียบร้อย

ทดลองสร้าง controllers ดังนี้ frontend\controllers\LineBotController แล้วเขียนโปรแกรมดังนี้

<?php

namespace frontend\controllers;

use frontend\models\LineBot;
use frontend\modules\forum\models\Thread;
use yii\helpers\Url;

class LineBotController extends \yii\web\Controller
{

    public function actionCurl()
    {
        /*
         * ส่งจาก Forum
         */
        $last_thread = LineBot::findOne(['type' => 'forum']);
        $thread = Thread::find()->orderBy(['id' => SORT_DESC])->one();
        if(!$last_thread){
            $last_thread = new LineBot();
            $last_thread->type = 'forum';
            $last_thread->last_id = $thread->id;
            $last_thread->save();
            $message = $thread->subject.' '.Url::to('https://www.programmerthailand.com/forum/view/'.$thread->id);
            $res = $this->notify_message($message);

        }else{
            if($last_thread->last_id != $thread->id){
                $message = $thread->subject.' '.Url::to('https://www.programmerthailand.com/forum/view/'.$thread->id);
                $res = $this->notify_message($message);
                $last_thread->last_id = $thread->id;
                $last_thread->save();
            }
        }


    }

    public function notify_message($message)
    {
        $line_api = 'https://notify-api.line.me/api/notify';
        $line_token = 'YOUR-TOKEN';

        $queryData = array('message' => $message);
        $queryData = http_build_query($queryData,'','&');
        $headerOptions = array(
            'http'=>array(
                'method'=>'POST',
                'header'=> "Content-Type: application/x-www-form-urlencoded\r\n"
                    ."Authorization: Bearer ".$line_token."\r\n"
                    ."Content-Length: ".strlen($queryData)."\r\n",
                'content' => $queryData
            )
        );
        $context = stream_context_create($headerOptions);
        $result = file_get_contents($line_api, FALSE, $context);
        $res = json_decode($result);
        return $res;
    }

}

เมื่อเรียก url http:://your-url/line-bot/curl ระบบก็จะทำงาน

สร้าง Cronjob ให้สคริปทำงานตามรอบที่ต้องการ

ในที่นี้ใช้ Cpanel มี Cronjob มาให้ แล้วเราก็สามารถเรียก request url ได้ โดยตั้งค่าต่างๆ ในที่นี้จะให้ทำงานทุกๆ 15 นาที ดังนี้

wget -q -O /dev/null "https://YOUR-DOMAIN/line-bot/curl" > /dev/null 2>&1

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

ทดสอบการใช้งานจะเห็นว่ามีข้อความส่งเข้า LINE Group ดังนี้

ปรับปรุงการส่งแบบใช้ cURL

ปรับปรุงการส่งแบบใช้ cURL ในขั้นตอนต่างๆ เช่น เมื่อมีการตั้งกระทู้ใหม่ เมื่อเขียน Blog ใหม่ และ เมื่อเขียน Tutorial ใหม่

ตัวอย่าง class นี้ใน frontend/components/Main.php

<?php
namespace frontend\components;

use frontend\modules\blog\models\Post;
use frontend\modules\forum\models\Thread;
use frontend\modules\tutorial\models\Post as Tutorial;
use Yii;
use yii\helpers\Url;

class Main
{
    public function simpleSlug($str)
    {
        $slug = preg_replace('@[\s!:;_\?=\\\+\*/%&#]+@', '-', $str);
        $slug = mb_strtolower($slug, Yii::$app->charset);
        $slug = trim($slug, '-');
    
        return $slug;
    }

    public function line($id = null, $type = null)
    {
        $message = "message=ชุมชนนักพัฒนา&imageThumbnail=".Url::to(Yii::getAlias('@web').'/images/programmerthailand_social.jpg', true)."&imageFullsize=".Url::to(Yii::getAlias('@web').'/images/programmerthailand_social.jpg', true)."";

        if($type == 'forum'){
            $model = Thread::findOne($id);
            if($model){
                $message = "message=".$model->subject.' '.Url::to('https://www.programmerthailand.com/forum/view/'.$model->id.'/'.$model->subject)."&imageThumbnail=".$this->getFirstImage($model->description)."&imageFullsize=".$this->getFirstImage($model->description)."";
            }
        }

        if($type == 'blog'){
            $model = Post::findOne($id);
            if($model){
                $message = "message=".$model->title.' '.Url::to('https://www.programmerthailand.com/blog/view/'.$model->id.'/'.$model->title)."&imageThumbnail=".$this->getFirstImage($model->content)."&imageFullsize=".$this->getFirstImage($model->content)."";
            }
        }

        if($type == 'tutorial'){
            $model = Tutorial::findOne($id);
            if($model){
                $message = "message=".$model->title.' '.Url::to(['/tutorial/post/view', 'id' => $model->id], true)."&imageThumbnail=".$this->getFirstImage($model->content)."&imageFullsize=".$this->getFirstImage($model->content)."";
            }
        }

        $line_api = 'https://notify-api.line.me/api/notify';
        $line_token = 'Yc7Eรหัสของคุณ4qSx';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"https://notify-api.line.me/api/notify");
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'message='.$message);
        // follow redirects
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-type: application/x-www-form-urlencoded',
            'Authorization: Bearer '.$line_token,
        ]);
        // receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec ($ch);

        curl_close ($ch);
        //var_dump($server_output);
        //echo Yii::getAlias('@webroot').'/images/programmerthailand_social.jpg';
    }

    public function getFirstImage($content) {

        $first_img = '';
        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
        $first_img = isset($matches[1][0]) ? $matches[1][0] : Url::to(Yii::getAlias('@web').'/images/programmerthailand_social.jpg', true);

        if(empty($first_img)) {
            $first_img = Url::to(Yii::getAlias('@web').'/images/programmerthailand_social.jpg', true);
        }
        return $first_img;
    }
}

จากนั้นทำการ register component ใน frontend/config/main.php

//...
'components' => [
//..
'main' => [
            'class' => 'frontend\components\Main'
        ],
//...
],

เวลาเรียกใช้งาน เช่นตอนตั้งกระทู้ใหม่ (create)

public function actionCreate()
    {
        $model = new Thread();
        if($model->load(Yii::$app->request->post())){
            $model->user_id = Yii::$app->user->getId();

            if($model->save()){

                Yii::$app->getSession()->setFlash('success', 'ตั้งคำถามเรียบร้อยแล้ว');

                Yii::$app->main->line($model->id, 'forum');//ส่ง line notify

                return $this->redirect(['/forum/q/view', 'id' => $model->id]);
            }

        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

สามารถนำไปประยุกต์ใช้ต่อไปนะครับ

##################

เขียนส่งแบบ PHP ธรรมดา สำหรับท่านที่ไม่ได้ใช้ Yii Framework

<?php
function sendToLine($message){
        

        $line_api = 'https://notify-api.line.me/api/notify';
        $line_token = 'Yc7Eรหัสของคุณ4qSx';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"https://notify-api.line.me/api/notify");
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'message='.$message);
        // follow redirects
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-type: application/x-www-form-urlencoded',
            'Authorization: Bearer '.$line_token,
        ]);
        // receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec ($ch);

        curl_close ($ch);
}

sendToLine('ข้อความของคุณ');

?>

อ้างอิง
https://medium.com/@aofiee/notify-bot-line-me-%E0%B9%83%E0%B8%8A%E0%B9%89-line-%E0%B8%A3%E0%B8%B1%E0%B8%9A-order-%E0%B8%87%E0%B8%B2%E0%B8%99-afe56f898fc#.esm0dspcv
http://stackoverflow.com/questions/13259530/using-cron-jobs-to-visit-url


ความคิดเห็น

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

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

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

มานพ กองอุ่น

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

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