LoginSignup
43
45

More than 5 years have passed since last update.

LINE BOT API を使い、匿名チャットルームを作る

Last updated at Posted at 2016-04-08

準備や登録方法などは他に書いてる方が沢山いるため、省きます

やっていること

  • BOTへの発言を、BOTを友人追加している人たちに一斉送信

line.png

処理内容

  1. メッセージを受け取ったらMIDをファイル等に保存
  2. 保存されているMID全てに受け取ったtextを一斉配信

誰かを招待する

動作を確認したら、https://developers.line.me にあるBOTのQRコードの画像を保存し
その画像をLINE経由などで友人に送りつけましょう
友だち追加→QRコード→ライブラリ→保存したQRコード
と指定すればBOTが表示されます
(QRコード送ると年齢認証の手間を省ける)

動かしたコード

<?php
$midFile = dirname(__FILE__)."/mids";
$json = json_decode(file_get_contents("php://input"), true);
$mids = explode(PHP_EOL, trim(file_get_contents($midFile)));
$newMids = array();
if (!isset($json["result"])) {
    exit(0);
}
foreach ($json["result"] as $result) {
    $newMids[] = $result["content"]["from"];
}
$messages = array();
foreach ($json["result"] as $result) {
    if (!isset($result["content"]["text"])) {
        continue;
    }
    if (1 > strlen($result["content"]["text"])) {
        continue;
    }
    $messages[] = array(
        "contentType" => 1,
        "text" => $result["content"]["text"],
    );
}
if (0 == count($messages)) {
    exit(0);
}
$mids = array_merge($newMids, $mids);
$mids = array_unique($mids);
file_put_contents($midFile, implode(PHP_EOL, $mids));

$body = json_encode(
array(
    "to" => array_values($mids),
    "toChannel" => 1383378250,
    "eventType" => "140177271400161403",
    "content" => array(
        "messageNotified" => 0,
        "messages" => $messages,
    ),
)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://trialbot-api.line.me/v1/events");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json; charset=UTF-8",
"X-Line-ChannelID: LINE_CHANNEL_ID",
"X-Line-ChannelSecret: LINE_CHANNEL_SECRET",
"X-Line-Trusted-User-With-ACL: LINE_CHANNEL_MID",
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
43
45
3

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