LoginSignup
36
31

More than 5 years have passed since last update.

LINE BOT APIで今日のランチを検索する

Posted at

LINE BOT APIが公開されたのでこれは遊ぶしかない!ということで作ってみました。

位置情報を送るとその住所周辺のランチを検索して送ってくれるボット

IMG_4425.jpg

LINE BOT APIの基本的な使い方は既に色々な方が書かれているのでそちらにお任せして、ざっくりと書いてきます。
登録ができれば以下が取得出来ると思います。
・Channel ID
・Channel Secret
・MID

まずは検索するためにGoogle Custom Search API を使用するのでそちらの準備をします。
こちらこちらを参考にさせて頂きました。
ここで以下の2つを取得します。
・GoogleAPIキー
・検索エンジンID

次に上記で取得したAPIキー等を以下のコードの各所に当て込んでコールバックで動かせば完成です。
※HTTPクライアントとしてGuzzleHttp\Clientを使用しているのでcomposer require guzzlehttp/guzzleしてください。

<?php
require_once __DIR__ . '/./vendor/autoload.php';

try {
    $req = file_get_contents('php://input');
    $req = json_decode($req);
    $link = getLink($req);
    $to = $req->{"result"}[0]->{"content"}->{"from"};
    file_put_contents('tmp/req', $to, FILE_APPEND);

    $client = new \GuzzleHttp\Client();
    $client->post('https://trialbot-api.line.me/v1/events', [
        'headers' => [
            'Content-Type' => 'application/json; charset=UTF-8',
            'X-Line-ChannelID' => '[Channel ID]',
            'X-Line-ChannelSecret' => '[Channel Secret]',
            'X-Line-Trusted-User-With-ACL' => '[MID]',
        ],
        'body' => json_encode([
            'to' => [$to],
            'toChannel' => '1383378250',
            'eventType' => '138311608800106203',
            'content' => [
                "contentType" => 1,
                "toType" => 1,
                'text' => $link
            ]
        ])
    ]);
} catch (Exception $e) {
    file_put_contents('tmp/error', $e->getMessage(), FILE_APPEND);
}

function getLink($post_data)
{
    try {
        $address = mb_substr($post_data->result[0]->content->location->address, 11);
        preg_match('/([\x{3005}\x{3007}\x{303b}\x{3400}-\x{9FFF}\x{F900}-\x{FAFF}\x{20000}-\x{2FFFF}]*)/u', $address, $matches);
        $q = urlencode($matches[1] . ' ランチ');

        file_put_contents('tmp/req', $matches[1] . ' ランチ' . PHP_EOL, FILE_APPEND);
        $url = 'https://www.googleapis.com/customsearch/v1?key=[GoogleAPIキー]&cx=[検索エンジンID]&q=' . $q;

        $search_result = json_decode(file_get_contents($url));
        $result = $search_result->items[mt_rand(0, 9)];
        return $result->title . PHP_EOL . $result->link;
    } catch (Exception $e) {
        return '芋でも食っとけ';
    }
}

軽く試しただけなのでかなりソースは雑です。検索クエリ生成の部分とか適当なので精度もあまり高くありません。
ですが、やはりLINEでボットが作れるというのはかなり可能性感じますね。

36
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
31