Made "Unofficial Apple Refurbished Product Introduction" BOT with LINE Messaging API (v2) + API Gateway + lambda (python)

Introduction

Bot Crawler Advent Calendar 2016 probably because I participated in Crawler / Web Scraping Advent Calendar 2016 I was invited to (/ advent-calendar / 2016 / bot), so I decided to write something, so I made a LINE BOT with a feeling that I left behind in 2016.

What kind of BOT

I made a BOT to introduce Apple's refurbished products.

LINE_developers.png

It has the following features.

--Randomly reply to Apple refurbished product pages, including text entered using the Reply API --Enter "Mac" and search for products that contain "Mac" --If the search is not hit, the entered text will be replied as it is.

IMG_2687.PNG

If you are kind enough to try using it, please try "Add friend" from the QR code below. QRコード.png

Implementation of lambda (python)

The final code looks like this:

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 Set the endpoint, header, etc. by referring to API Reference.

Get Channel Access Token from environment variable

Channel Access Token is set as an environment variable from the Lambda setting screen.

Lambda_Management_Console.png

requests is not installed, so upload it with the ZIP file

Install requests directly under the project directory.

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

The directory tree looks like this:

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

Compress the source code and required external libraries into a ZIP file and upload it from the AWS Lambda web console.

Reference) Create Deployment Package (Python) --AWS Lambda

The crawling result is saved separately in JSON format on S3

Make sure to save the result of crawling the following URL in S3 in JSON format on a regular basis, and read the JSON file from the lambda function.

in conclusion

I don't think it's possible with this story, but if you have any good ideas, I'd like to implement them and enter them in LINE BOT AWARDS. ..

See you soon.

Recommended Posts

Made "Unofficial Apple Refurbished Product Introduction" BOT with LINE Messaging API (v2) + API Gateway + lambda (python)
LINE BOT (Messaging API) development with API Gateway and Lambda (Python) [Part 2]
LINE BOT with Python + AWS Lambda + API Gateway
[LINE Messaging API] Create parrot return BOT with Python
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
[LINE Messaging API] Create a BOT that connects with someone with Python
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
Try implementing a Cisco Spark bot with AWS Lambda + Amazon API Gateway (Python)
I made a LINE BOT with Python and Heroku
Quickly take a query string with API Gateway-> Lambda (Python)
[LINE Messaging API] Issue channel access token v2.1 in Python
Create API with Python, lambda, API Gateway quickly using AWS SAM
I made a Chatbot using LINE Messaging API and Python
I made a Twitter Bot with Go x Qiita API x Lambda
I tried ChatOps with Slack x API Gateway x Lambda (Python) x RDS
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
[AWS] Create API with API Gateway + Lambda
Python calling Google Cloud Vision API from LINE BOT via AWS Lambda
How to make an artificial intelligence LINE bot with Flask + LINE Messaging API
Simple Slack API client made with Python
Serverless face recognition API made with Python
Easy REST API with API Gateway / Lambda / DynamoDB
Decision support system for elderly people made with LINE Messaging API + Serverless Framework
[Python] A story about making a LINE Bot with a practical manned function on its own without using Salesforce [Messaging API]
I made a stamp substitute bot with line
[AWS SAM] Create API with DynamoDB + Lambda + API Gateway
View images on S3 with API Gateway + Lambda
Create a LINE BOT with Minette for Python
I made a LINE Bot with Serverless Framework!
[AWS] Try tracing API Gateway + Lambda with X-Ray
Serverless LINE bot made with IBM Cloud Functions
Amazon API Gateway and AWS Lambda Python version
I made a Mattermost bot with Python (+ Flask)
Various memorandums when using sdk of LINE Messaging API with Python (2.7.9) + Google App Engine