LoginSignup
39
43

More than 5 years have passed since last update.

LINE BOTを使ってアニメ情報を教えてくれるボットを作ってみた

Last updated at Posted at 2016-04-13

LINEのBOTが作れるBOT API Trial Accountが公開されて、一気にボット界隈が賑わってますね。話を聞いてとりあえず作ってみました。
せっかくなので少し前から妄想していたものを少し形にしてみました。

作ったのは今期放送しているアニメを教えてくれるボットです。

Screenshot_2016-04-14-01-00.png

こんな感じです。
「今期のアニメ」という単語に反応します。それ以外はあえて定型文を返すようにしました。

処理的には

  • アニメ用のAPIが存在するのでこちらから今期のアニメ情報を取得します。
  • そしてタイトルと公式サイトのURLを取得します。
  • 公式サイトのOGPタグを解析して画像が設定されていれば表示します。

これだけですね。簡単ですね。

ソースコード

callback.php
<?php
require_once('OpenGraph.php');
error_log("callback start.");

// アカウント情報設定
$channel_id = "[チャンネルID]";
$channel_secret = "[チャンネルシークレット]";
$mid = "[MID]";

// メッセージ受信
$json_string = file_get_contents('php://input');
$json_object = json_decode($json_string);
$content = $json_object->result{0}->content;
// ブロックされたときにもリクエストがあるので注意
$text = $content->text;
$from = $content->from;
$message_id = $content->id;
$content_type = $content->contentType;

// 受信メッセージに応じて返すメッセージを変更
$event_type = "138311608800106203";
if ($text == "今期のアニメ") {
    $content = "";
    $cours = ceil(date('m') / 3);
    $list = file_get_contents(sprintf('http://api.moemoe.tokyo/anime/v1/master/%d/%d', date('Y'), $cours));
    $list = json_decode($list, true);

    if (count($list)) {
        api_post_request("/v1/events", $event_type, json_encode(create_text(sprintf('今期のアニメは%s本ありますね', count($list)))));

        foreach ($list as $value) {
            $event_type = "140177271400161403";
            $content = array(
                'messageNotified' => 0,
                'messages' => array(),
            );

            $graph = OpenGraph::fetch($value['public_url']);
            $content['messages'][] = create_text(sprintf("%s\n%s", $value['title'], $value['public_url']));
            if ($graph && $image = $graph->image)
            {
                if (0 === strpos($image, 'http'))
                {
                    $content['messages'][] = create_image($image);
                }
            }
            api_post_request("/v1/events", $event_type, json_encode($content));
        }
        $content = "";
    } else {
        api_post_request("/v1/events", $event_type, json_encode(create_text(sprintf("情報がないです><\nごめんなさい"))));
    }
} else { // 上記以外はtext送信
    $content = json_encode(create_text("えーと。\nごめんなさいちょっとわからないです\n今期のアニメのことだったらわかりますよ!\n今期のアニメって言ってね"));
}

if ($content) {
    api_post_request("/v1/events", $event_type, $content);
}

error_log("callback end.");

function api_post_request($path, $event_type, $content) {
    $url = "https://trialbot-api.line.me{$path}";
    $headers = array(
        "Content-Type: application/json",
        "X-Line-ChannelID: {$GLOBALS['channel_id']}",
        "X-Line-ChannelSecret: {$GLOBALS['channel_secret']}",
        "X-Line-Trusted-User-With-ACL: {$GLOBALS['mid']}"
    );

    $post = <<< EOM
{
    "to":["{$GLOBALS['from']}"],
    "toChannel":1383378250,
    "eventType":"{$event_type}",
    "content":{$content}
}
EOM;

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($curl);
    error_log($output);
}

function create_text($text) {
    $text = array(
        'toType' => 1,
        'contentType' => 1,
        'text' => $text,
    );

    return $text;
}

function create_image($url) {
    $image = array(
        "toType" => 1,
        "contentType" => 2,
        "originalContentUrl" => $url,
        "previewImageUrl" => $url,
    );

    return $image;
}

ベースとなるプログラムは下の参考記事にも挙げているLINE BOT API Trialでできる全ての事を試してみたです。これを改造しました。
ちょっと自分とコーディング方法が違ったので所々おかしなところがあるかも知れないです。

次はこれをもっと発展させて、人気のアニメを教えてくれるようにしたいですね

余談

本題とは関係無いんですが、ブロックしたり、ブロック解除したりするとなんとcallbackがあるみたいなんです。リクエストの中身まで見てないのでなんとも言えませんが、もしかすると誰がブロックしたのかわかるかも知れないですね。

それと「ToMiCo」と言うのは、自分が管理している同人コミュニティです。

参考記事

39
43
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
39
43