Make a LINE bot with GoogleAppEngine / py. Simple naked version

LINEbot is 1on1, isn't it? Isn't it possible to add it to a group like a common bot?

By the way, although it is a LINE bot, the hurdle is raised where an SSL server is required. Let's make this quickly with https-ready GAE. The problem is how to fix the IP at the time of meg send, but this is muddy. I will describe it later.

Python library

I will use flask, so let's dig lib in the project folder and pip it

sh


$ pip install -t lib flask

GAE source

python



#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import urllib
import json
from google.appengine.ext import vendor
vendor.add('lib')
from google.appengine.api import urlfetch

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/')
def index():
  return 'hello my line bot'

@app.route('/callback', methods=["POST"])
def linebot():
  args = json.loads(request.get_data().decode('utf-8'))
  logging.debug('kick from line server,\n %s'%(args['result']))
  for msg in args['result']:
    kickBot( msg["content"]["from"], msg["eventType"], msg["content"]["text"] )
  return "{}"

def kickBot(tgt_id, event_type, msg_data):
  url = "https://trialbot-api.line.me/v1/events"
  form_fields = {
      "to": [str(tgt_id)],
      "toChannel": 1383378250,
      "eventType": 138311608800106203,
      "content":{
        "contentType":1,
        "toType":1,
        "text":u"Naked%s !"%(msg_data)
        }
      }
  logging.debug(form_fields)
  form_data = urllib.urlencode(form_fields)
  result = urlfetch.fetch(
    url=url,
    payload=json.dumps(form_fields,ensure_ascii=False),
    method=urlfetch.POST,
    headers={
                'Content-type':'application/json; charset=UTF-8',
                'X-Line-ChannelID':'<YOUR-ID>',
                'X-Line-ChannelSecret':'<YOUR-SECRET>',
                'X-Line-Trusted-User-With-ACL':'<YOUR-ACL>?',
            }
    )
  if result.status_code == 200:
    logging.debug(result.content)
  else:
    logging.debug(result.content)

yaml


application: <YOUR-GAE-NAME>
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: .*
  script: main.app

LINE bot settings

CallBack settings

Have / callback send LINE server messages. https://developers.line.me/channels/<YOUR-CHANNEL-ID> Register it in the Callback URL on the LINE Dev console.

https://your-gae.appspot.com:443/callback

How to register Whitelist IP

Let's release the above GAE app and tweet to the bot. No reply comes at this point. This is because the IP is not registered in the LINEbot server. In GAE, the IP associated with the published application name and the IP of the server on which urlfetch is executed are Since they are not the same, you need to actually hit LINEbot from GAE to investigate the IP.

On the GCP Logging console, Such an IP Shirangana! I think you're getting an error like . This is the one.

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

The IP that appears in this this time's address will be registered in the WhiteList of LINE's Dev console. If you do it several times, you may see some differences. Please register each time. In my case, I registered about 3 but it didn't increase any more. (GAE version is changed and deployed)

Now you will get a reply from the bot.

スクショ.png

Caution

This implementation is just for checking. It's just simple text, so what happens if you change the type, whether it's a video or an image? Please check it. The reason is that it can't handle even some traffic. Check here for details

In the future, I plan to use TQ to create a version that will be passed asynchronously.

Recommended Posts

Make a LINE bot with GoogleAppEngine / py. Simple naked version
Make a LINE WORKS bot with Amazon Lex
Make a LINE BOT (chat)
Make a morphological analysis bot loosely with LINE + Flask
[Super easy] Let's make a LINE BOT with Python.
Let's make a simple language with PLY 1
Let's make a Twitter Bot with Python!
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
Make a Twitter trend bot with heroku + Python
Create a LINE BOT with Minette for Python
Make a simple pixel art generator with Flask
[Python] Make a simple maze game with Pyxel
I made a LINE Bot with Serverless Framework!
Make LINE BOT (Echolalia)
[AWS] I made a reminder BOT with LINE WORKS
I made a household account book bot with LINE Bot
Make a simple Slackbot with interactive button in python
Let's make a simple game with Python 3 and iPhone
Make a parrot return LINE Bot on AWS Cloud9
I made a LINE BOT with Python and Heroku
[For play] Let's make Yubaba a LINE Bot (Python)
What is God? Make a simple chatbot with python
Make a Linux version of OpenSiv3D with find_package a little easier
Let's make a Discord Bot.
I made a LINE BOT that returns parrots with Go
Create a machine learning app with ABEJA Platform + LINE Bot
How to make a simple Flappy Bird game with pygame
Until I return something with a line bot in Django!
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Make a fortune with Python
[Python] Make a simple maze game with Pyxel-Make enemies appear-
Make a fire with kdeplot
Let's make a LINE bot using various services [ngrok edition]
[AWS] I made a reminder BOT with LINE WORKS (implementation)
Rubyist tried to make a simple API with Python + bottle + MySQL
Make a simple OMR (mark sheet reader) with Python and OpenCV
[LINE Messaging API] Create a BOT that connects with someone with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
[Python] Make your own LINE bot
Let's make a GUI with python.
Make a sound with Jupyter notebook
How to make a slack bot
Let's make a breakout with wxPython
Creating a simple app with flask
Make a recommender system with python
Make a filter with a django template
[LINE bot] I'm a ranger! Part 2
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Make a model iterator with PySide
Make a nice graph with plotly
Create a LINE Bot in Django
The story of making a university 100 yen breakfast LINE bot with Python
How to make an artificial intelligence LINE bot with Flask + LINE Messaging API
Make a wireless LAN Ethernet converter and simple router with Raspberry Pi
Tweet the weather forecast with a bot
Creating a simple PowerPoint file with Python
A simple RSS reader made with Django
Let's make a shiritori game with Python
Display Disney's waiting time with LINE bot