[PYTHON] I made my dog "Monaka Bot" with LineBot

Screenshot_20160408-151644.png

I tried LineBot. I'm sorry for the money, so I built it with GAE. I used Python / Flask because Java is awkward.

Project generation with GCP

If you are new to this, it will come out.

Preparing app.yaml

The source looks like this.

app.yaml


runtime: python27
api_version: 1
threadsafe: yes

- url: .*  # This regex directs all routes to main.app
  script: main.app

libraries:
- name: ssl
  version: latest

At first, it fits without adding the ssl library.

Implementation of callback

When the user talks to the bot, the API specified in the callback is called. It's like calling Line's API in a callback and sending text and photos. Please refer to the manual and other qiita for callback settings.

The source looks like this.

main.py


# -*- coding: utf-8 -*-

import logging, random
import requests

from flask import Flask, request,Response

app = Flask(__name__)
app.config.from_object(__name__)
app.logger.setLevel(logging.DEBUG)

LINE_ENDPOINT = "https://trialbot-api.line.me"
HEADERS = {
    "X-Line-ChannelID": "<See Basinc Information>",
    "X-Line-ChannelSecret": "<See Basinc Information>",
    "X-Line-Trusted-User-With-ACL": "<See Basinc Information>"
}

#Fixed message group
TALKS = [
    "Wow! Come on! !!",
    "Yeah ... I want to ...",
    "Pee! Pee!",
    "Where did the owner go",
    "Shinotomo ~~~",
    "Ngu ~ ngu ~~",
    "Hehehehehehehehe",
    "Uo ・ e ・ oU",
    "Licking licking",
    "I want to lick my dog's hand",
    "I wonder if the rice has fallen",
    "Easy and easy",
    "Look!",
    "dance! Dance dance! !!"
]

#Image group
IMAGES = [
    {"origin": "https://storage.googleapis.com/linebot-1275.appspot.com/monaka1.jpg ",
     "thumb": "https://storage.googleapis.com/linebot-1275.appspot.com/monaka1thum.jpg "}
]


@app.route("/")
def hello():
    return "line bot api"


@app.route("/callback", methods=["POST"])
def callback():
    # TODO Signature validation

    app.logger.info(request.json)
    app.logger.info(request.headers)
    req = request.json["result"][0]

    if req["eventType"] == "138311609100106403":
        """
The reception of friend requests comes here.
Send a thank-you message as soon as you apply.
TODO unverified
        """

        send_text([req["from"]], u"Monaka. Thank you for your friend application.")

    elif req["eventType"] == "138311609000106303":
        """
Come here when you receive a conversation message.
When you say "Monaka", a photo and a message are returned.
Other than that, the prepared text is returned at random.
        """

        to = [req["content"]["from"]]
        if req["content"]["text"] == u"Monaka":
            #Send photo
            i = random.randint(0, len(IMAGES) - 1)
            send_picture(to, IMAGES[i])
            send_text(to, "What?")
        else:
            #Send Messege
            i = random.randint(0, len(TALKS) - 1)
            send_text(to, TALKS[i])

    #The return value is fixed at 200
    return Response(status=200)


def send_text(to, text):
    """
Send text to to
    """
    content = {
        "contentType": 1,
        "toType": 1,
        "text": text
    }
    events(to, content)


def send_picture(to, img):
    """
Send image to to
    """
    content = {
        "contentType": 2,
        "toType": 1,
        "originalContentUrl": img["origin"],
        "previewImageUrl": img["thumb"]
    }
    events(to, content)


def events(to, content):
    """
Data for to(Text / images / videos)Send
    """
    app.logger.info(content)
    data = {
        "to": to,
        "toChannel": "1383378250",
        "eventType": "138311608800106203",
        "content": content
    }
    r = requests.post(LINE_ENDPOINT + "/v1/events", json=data, headers=HEADERS)
    app.logger.info(r.text)

setting static IP Address

The server is whitelisted, so if you don't set an IP Address, Line's server will return an error. However, since it is GAE, there is no fixed IP Address. When I tried to access it, I got a 403 error and the following message was displayed.

{"statusCode":"427","statusMessage":"Your ip address [107.178.194.118] is not allowed to access this API."}

So, if you add this IP Address and move it

{"statusCode":"427","statusMessage":"Your ip address [107.178.194.122, 10.128.141.149] is not allowed to access this API."}

Next, I was asked to set something that seems to be an internal IP Address, so I will set it obediently.

It worked. There is a high possibility that the IP Address will change someday and it will not work. I will leave the solution to me in the future.

Apply for a friend

It seems that you can do it from the QR code. (I didn't understand and suffered all the time) This time my dog "Monaka Bot"

rjs9046g.png

You can add from.

Recommended Posts

I made my dog "Monaka Bot" with LineBot
I made a stamp substitute bot with line
I made a LINE Bot with Serverless Framework!
I made my goimports
I made a Mattermost bot with Python (+ Flask)
[AWS] I made a reminder BOT with LINE WORKS
I made a Twitter BOT with GAE (python) (with a reference)
I made a household account book bot with LINE Bot
I made a LINE BOT with Python and Heroku
I made blackjack with python!
I made my own language. (1)
I made my own language (2)
I made my own AML
I made a discord bot
I made COVID19_simulator with JupyterLab
I made Word2Vec with Pytorch
I made blackjack with Python.
I made wordcloud with Python.
I made a LINE BOT that returns parrots with Go
I made LINE-bot with Python + Flask + ngrok + LINE Messaging API
I made a surveillance camera with my first Raspberry PI.
When I made a Discord Bot, my classmates destroyed my computer
[AWS] I made a reminder BOT with LINE WORKS (implementation)
I made a wikipedia gacha bot
I made my own Python library
I made a fortune with Python.
I made a daemon with Python
I made a Twitter Bot with Go x Qiita API x Lambda
I made a character counter with Python
I made CORS custom middleware with Django
I made a Hex map with Python
I made a life game with Numpy
I made a stamp generator with GAN
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a WEB application with Django
I made a neuron simulator with Python
With LINEBot, I made an app that informs me of the "bus time"
I made a competitive programming glossary with Python
I made a weather forecast bot-like with Python.
I made a Twitter fujoshi blocker with Python ①
Procedure for creating a LineBot made with Python
[Python] I made a Youtube Downloader with Tkinter.
I made a simple Bitcoin wallet with pycoin
I made my own primitive static site generator
Serverless LINE bot made with IBM Cloud Functions
I tried to operate Linux with Discord Bot
I made a random number graph with Numpy
I made a bin picking game with Python
I made a QR code image with CuteR
I made my own parallel link robot (software version)
I made a ready-to-use syslog server with Play with Docker
I made a Christmas tree lighting game with Python
I made a vim learning game "PacVim" with Go
I made a window for Log output with Tkinter
I made a net news notification app with Python
I made a Python3 environment on Ubuntu with direnv.
I made a falling block game with Sense HAT
I made it with processing, "Sakanaction's live Othello guy".
I made my own parallel link robot (mechanical edition)