17
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LINEからMessaging APIが新しくリリースされたそうなので相変わらず形態素解析をするだけのBOTを作った

Last updated at Posted at 2016-10-20

はじめに

以前にTrialアカウントで全く同じものを作ったのですが、「アカウント一斉削除すっぞ!!」というような脅しメールが来たので移行しました。

リポジトリ

私の作ったもの

LINEオフィシャルのSDK

BOT

9FlxYyqoOH.png

SDKのWikiページに乗ったらいいなぁなんて...

環境

  • Python3.5.2
  • Virtualenv
  • Flask
  • 夜のテンション
  • キチガイのテンション
  • 晩御飯食べてないけど開発意欲が半端ない

ソースコード

bot.py
# coding: utf-8

from __future__ import unicode_literals

from flask import Flask, request, abort

from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage

from janome.tokenizer import Tokenizer

import os, re, json

def load_env():
    try:
        with open('.env') as f:
            content = f.read()
    except IOError:
        content = ''

    for line in content.splitlines():
        m1 = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line)
        if m1:
            key, val = m1.group(1), m1.group(2)
            m2 = re.match(r"\A'(.*)'\Z", val)
            if m2:
                val = m2.group(1)
            m3 = re.match(r'\A"(.*)"\Z', val)
            if m3:
                val = re.sub(r'\\(.)', r'\1', m3.group(1))
            os.environ.setdefault(key, val)

load_env()

app = Flask(__name__)

line_bot_api = LineBotApi(os.environ.get('CHANNEL_ACCESS_TOKEN'))
handler = WebhookHandler(os.environ.get('CHANNEL_SECRET'))

@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-LINE-Signature']

    body = request.get_data(as_text=True)
    receive_json = json.loads(body)
    message = receive_json['events'][0]['message']['text']

    response_arrays = []
    t = Tokenizer()
    for token in t.tokenize(message):
        response_arrays.append(str(token))

    response = ''
    for item in range(len(response_arrays)):
        if len(response_arrays) == item + 1:
            response += str(response_arrays[item])
        else:
            response += str(response_arrays[item] + '\n')

    try:
        line_bot_api.reply_message(receive_json['events'][0]['replyToken'], TextSendMessage(text = response))
    except InvalidSignatureError:
        abort(400)

    return 'OK'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port = 8003, threaded = True, debug = True)
.env
CHANNEL_ACCESS_TOKEN='hogehoge' # めっちゃ長いやつ
CHANNEL_SECRET=''					# 今まで通り隠れてるやつ

LINE管理画面側の設定

案の定、HTTPSでないとダメなので頑張りましょう!

スクリーンショット 2016-10-21 午前0.45.56.png

LINE@の管理画面に頑張ってたどり着いて 「アカウント設定」 > 「Bot設定」 で自分の思うような設定をしましょう!

実際のレスポンス

FullSizeRender.jpg

とても見づらいですね...

最後に

なにかあればPullRequestなどドンドン出してほしいです!
あとLINEさんWikiページお願いします。

旧APIと今回の新APIでは request.headers['X-LINE-Signature'] があるのとないのではじめ焦りました。ちなみに旧APIでは request.headers['X-Line-Channelsignature'] に相当します。

17
19
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
17
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?