LoginSignup
5

More than 5 years have passed since last update.

LINE Messaging API(v2) + API Gateway + lambda(python) で「非公式Apple整備済製品紹介」BOTを作った

Posted at

はじめに

クローラー/Webスクレイピング Advent Calendar 2016に参加していたせいか、ボット・クローラー Advent Calendar 2016に招待されましたので、何か書こうということで、2016年やり残した感のあるLINE BOTを作ってみました。

どんなBOTか

Appleの整備済製品を紹介するBOTを作りました。

LINE_developers.png

以下の特徴があります。

  • Reply APIを使い入力されたテキストを含む、Apple整備済製品のページをランダムに返信する
  • 「Mac」と入力したら、「Mac」を含む製品を検索する
  • 検索にヒットしなかった場合は、入力されたテキストをそのまま返信(おうむ返し)する

IMG_2687.PNG

使ってみようかなと思った心優しい方は、下記のQRコードから「友だち追加」してみてください。
QRコード.png

lambda(python)の実装

最終的にコードは以下のようになりました。

from __future__ import print_function
import requests
import json
import os
import boto3
import random

print('Loading function')

LINE_API_ENDPOINT = 'https://api.line.me/v2/bot/message/reply'

LINE_API_HEADERS = {
    'Authorization': 'Bearer ' + os.environ['LINE_CHANNEL_ACCESS_TOKEN'],
    'Content-type': 'application/json'
}


def lambda_handler(event, context):

    for event in event['events']:
        reply_token = event['replyToken']
        message = event['message']

        payload = {
            'replyToken': reply_token,
            'messages': []
        }

        items = get_items_by_keyword(message['text'])
        if len(items) == 0:
            payload['messages'].append({
                'type': 'text', 'text': message['text']
            })
        else:
            item = items[0]
            payload['messages'].append({
                'type': 'text', 'text': item['title'] + item['price'] + item['link']
            })

        response = requests.post(LINE_API_ENDPOINT, headers=LINE_API_HEADERS, data=json.dumps(payload))
        print(response.status_code)


def get_items_by_keyword(keyword=None):

    key = 'items.json'
    s3 = boto3.client('s3')
    response = s3.get_object(Bucket='apple-refurbished', Key=key)
    items = json.load(response['Body'])

    result = []
    for item in items:
        if item['title'].find(keyword) != -1:
            result.append(item)

    random.shuffle(result)
    return result

Messageing API -> Reply Message

API Referenceを参考にエンドポイント、ヘッダーなどを設定します。

Channel Access Token は環境変数から取得

Channel Access Token はLambdaの設定画面から環境変数として設定します。

Lambda_Management_Console.png

requestsはインストールされていないので、ZIPファイルに同梱してアップロード

requestsをプロジェクトディレクトリの直下にインストールします。

$ cd /path/to/project
$ pip install requests -t .

ディレクトリーツリーは以下のようになります。

.
├── lambda_function.py
├── requests
│   ├── __init__.py
│   ├── ...
└── requests-2.12.4.dist-info
    ├── ...

ソースコードと必要な外部ライブラリをZIPファイルに圧縮して、AWS LambdaのWebコンソールからアップロードします。

参考)デプロイパッケージの作成 (Python) - AWS Lambda

クローリングした結果は、別途、S3にJSON形式で保存

下記URLをクローリングした結果を定期にS3にJSON形式で保存するようにしておき、lambda関数からはそのJSONファイルを読み込むようにします。

おわりに

今回のネタでは、無理だと思いますが、何かいいアイデアがあれば実装して、LINE BOT AWARDSにでもエントリーできればいいなと思います。

ではでは。

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
5