1時間でLINE BOTを作ってみた

1時間でLINE BOTを作ってみた

ちょっとだけ時間があったので、ノリと勢いでLINE BOTを作ってみました。
アカウント取得からオウム返しするBOTを作るまで、だいたい1時間程度でできました。

まずは、LINE@のアカウントを取得。

LINE Business Center
https://business.line.me/ja/

アカウント取得後、BOT設定のリクエスト設定を「利用する」に変更。
その後、「LINE Developersで設定する」でWebHook関連の設定へ

次にプログラムに必要なWebHookのCallback用のURLを設定し、API実行に必要な「Channel Secret」、「Channel Access Token」を取得します。
※Callback用のURLはSSLが必須です。

ここまでできればあとはプログラムを設置して、WebHookを受けられるようにすれば完了です。
そして、今回1時間で書いたプログラムがこんな感じ。


from flask import Flask
from flask import request

import requests
import json
import re

import hmac
import hashlib
import base64

CHANNEL_ACCESS_TOKEN = 'xxxx'
CHANNEL_SECRET = 'xxxx'
LINE_ENDPOINT = 'https://api.line.me/v2/bot'

def post(reply_token, messages):
        header = {
                "Content-Type": "application/json",
                "Authorization": "Bearer {}".format(CHANNEL_ACCESS_TOKEN)
        }
        payload = {
                "replyToken": reply_token,
                "messages": messages,
        }
        requests.post(LINE_ENDPOINT+'/message/reply', headers=header, data=json.dumps(payload))

def get_profile(user_id):
        header = {
                "Content-Type": "application/json",
                "Authorization": "Bearer {}".format(CHANNEL_ACCESS_TOKEN)
        }
        return json.loads(requests.get(LINE_ENDPOINT+'/profile/{}'.format(user_id), headers=header, data='{}').text)

def valdation_signature(signature, body):
        if isinstance(body, str) != True:
                body = body.encode()
        gen_signature = hmac.new(CHANNEL_SECRET.encode(), body.encode(), hashlib.sha256).digest()
        gen_signature = base64.b64encode(gen_signature).decode()

        if gen_signature == signature:
                return True
        else:
                return False

app = Flask(__name__)

@app.route("/test", methods=['GET'])
def test():
        return 'Test OK!', 404

@app.route("/callback", methods=['POST'])
def callback():
        if valdation_signature(request.headers.get('X-Line-Signature', ''), request.data.decode()) == False:
                return 'Error: Signature', 403
        app.logger.info('CALLBACK: {}'.format(request.data))

        for event in request.json['events']:
                # follow
                if event['type'] == 'follow':
                        if event['source']['type'] == 'user':
                                profile = get_profile(event['source']['userId'])
                        messages = [
                                {
                                        'type': 'text',
                                        'text': '追加してくれてあ(・∀・)り(・∀・)が(・∀・)と(・∀・)う!',
                                },
                                {
                                        'type': 'text',
                                        'text': 'これからよろしく!',
                                }
                        ]
                        if 'profile' in locals():
                                messages[0]['text'] = '{}さん\n'.format(profile['displayName'])+messages[0]['text']
                        post(event['replyToken'], messages)
                # Message
                elif event['type'] == 'message':
                        messages = [
                                {
                                        'type': 'text',
                                        'text': event['message']['text'],
                                }
                        ]
                        post(event['replyToken'], messages)
        return '{}', 200

if __name__ == "__main__":
        # context = ('cert/server.pem', 'cert/privkey.pem')
        # app.run(host='0.0.0.0', port=443, ssl_context=context, threaded=True, debug=True)
        app.run(host='0.0.0.0', port=8001, threaded=True, debug=True)

Python3で書いており、環境依存moduleは「requests」「flask」です。
機能的には友達追加した場合のメッセージと、入力された文字をオウム返しするようになっています。
自分の環境ではフロントにNGINXがいてそこでSSL解除しているため、Ptyhon側にSSLの設定が必要ありませんが、必要な場合は最下部の「context」にSSL追加して起動してください。


このような感じで、入力した文字をオウム返ししてくれます。
レスポンスが遅いときがありますがそれはAPI側が遅いみたいです。

1時間でここまで簡単にLINEBOT出来ました。
入力されたことに対してのレスポンス以外にも有料プランで直接メッセージを送ったりもできるそうなので、今後どのようなサービスが出てくるか楽しみです。

他の「develop」の記事を読む

Googleのデータセンター使ってます。

Googleのデータセンター使ってます。

一般の人にも理解できる、エンジニアの苦しみ

一般の人にも理解できる、エンジニアの苦しみ