Create a LINE Bot in Django

Introduction

I've summarized the article about using LINE Bot with Django because it wasn't very clear, or even if it was old.

For the time being, I will create an Echolalia Bot that returns the text sent as an introduction to LINE Bot as it is.

The article here uses the SDK, but I'm a Python beginner and I can't even make HTTP requests with Python, so I'll do it myself for training. I would like to do it.

I'm a Django beginner with less than a week of Django history. Also, since the language I usually use is functional Elixir, the implementation may not be object-oriented.

If you have any advice on what is wrong or what you need to improve, please leave a comment.

Although it is my past article, I will refer to the following articles as a whole. Using LINE Messaging API with Elixir / Phoenix

Register with LINE Developer / Register channel

↓ Register from here https://developers.line.biz/ja/

Although it is different from the current situation in various ways, we will register the channel referring to the following article https://qiita.com/nkjm/items/38808bbc97d6927837cd

Project creation

Create a project as you like.

$ django-admin startproject qiita_linebot
$ cd qiita_linebot/
$ python manage.py startapp qiita_linebot_ai

Create urls.py

qiita_linebot_ai/urls.py


from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='callback'),
]

Reflect in qiita_linebot / urls.py.

qiita_linebot/urls.py


from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('qiita_linebot_ai/', include('qiita_linebot_ai.urls')),  #add
    path('admin/', admin.site.urls),
]

Creating a LineMessage class

I'm not good at object-oriented thinking because I usually use only Elixir, but I think it's better to encapsulate (?) In such a case, so create a LineMessage class and create a reply method in it. To do.

Send an HTTP request to the LINE Messaging API by referring to the following article Urllib.request is sufficient for Python HTTP client

line_message.py


from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

import urllib.request
import json


REPLY_ENDPOINT_URL = "https://api.line.me/v2/bot/message/reply"

ACCESSTOKEN = 'Your access token'   #Messaging API settings|>Get an access token from a channel access token
HEADER = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + ACCESSTOKEN
}

class LineMessage():
    def __init__(self, messages):
        self.messages = messages

    def reply(self, reply_token):
        body = {
            'replyToken': reply_token,
            'messages': self.messages
        }
        print(body)
        req = urllib.request.Request(REPLY_ENDPOINT_URL, json.dumps(body).encode(), HEADER)
        try:
            with urllib.request.urlopen(req) as res:
                body = res.read()
        except urllib.error.HTTPError as err:
            print(err)
        except urllib.error.URLError as err:
            print(err.reason)

Here, the message passed to the method reply assumes the following format.

{
 type: "text",
 text: "hogehoge" #This time, the received message is returned as it is
}

Look at this "You only have to take the message to send (" hogehoge "in the above) as an argument." As you might think, the LINE Messaging API also supports sending multiple messages at the same time. Also, type exists in addition to text.

I thought about dividing the class further, but this time I will implement it in this way.

Create message_creater

util/message.creater.py


def create_single_text_message(message):
    test_message = [
                {
                    'type': 'text',
                    'text': message
                }
            ]
    return test_message

Create a module message_creater for the argument message used in LineMessage.reply.

edit view

view.py


from django.shortcuts import render
from django.http import HttpResponse
import json
from django.views.decorators.csrf import csrf_exempt

from utils import message_creater
from qiita_linebot_ai.line_message import LineMessage

@csrf_exempt
def index(request):
    if request.method == 'POST':
        request = json.loads(request.body.decode('utf-8'))
        events = request['events']
        for event in events:
            message = event['message']
            reply_token = event['replyToken']
            line_message = LineMessage(message_creater.create_single_text_message(message['text']))
            line_message.reply(reply_token)
        return HttpResponse("ok")

This completes the implementation.

Test with ngrok

ngrok settings

I will actually try it. Since localhost cannot be specified in the Webhook URL, use ngrok.

Please install ngrok referring to the following article. ngrok is too convenient

Once installed

$ ngrok http 8000

Then

スクリーンショット 2020-01-08 16.23.00.png

You can start it like this. Please replace the ngrok URL that appears after this with your own as appropriate.

Webhook URL settings

Messaging API settings|>Webhook settings|>WebhookURL From Enter https://ecdb2a20.ngrok.io/qiita_linebot_ai/.

Editing ALLOWED_HOSTS

Add ngrok to ALLOWED_HOSTS as follows.

settings.py


ALLOWED_HOSTS = ["ecdb2a20.ngrok.io"]

test

You're ready to go!

If you start the server and return it as follows, you are successful!

スクリーンショット 2020-01-08 16.30.28.png

Recommended Posts

Create a LINE Bot in Django
Until I return something with a line bot in Django!
Create a Django schedule
Create a slack bot
Create a LINE BOT with Minette for Python
How to create a Rest Api in Django
Until you create a new app in Django
Create a dictionary in Python
Create a homepage with django
Make a LINE BOT (chat)
Create a Django login screen
Create a data collection bot in Python using Selenium
[LINE Messaging API] Create a rich menu in Python
Create a CSV reader in Flask
Create a DI Container in Python
Steps to create a Django project
Create a machine learning app with ABEJA Platform + LINE Bot
Create a binary file in Python
Create a Kubernetes Operator in Python
[LINE bot] I'm a ranger! Part 2
Create a random string in Python
Create a file uploader with Django
[Python / Django] Create a web API that responds in JSON format
[LINE Messaging API] Create a BOT that connects with someone with Python
Install Django in a pipenv virtual environment
Create a bot to retweet coronavirus information
Create a model for your Django schedule
Create a simple GUI app in Python
Creating a LINE bot ~ Creating, deploying, and launching ~
Create a JSON object mapper in Python
Dynamically specify a ModelChoiceField queryset in Django
Create a Python-GUI app in Docker (PySimpleGUI)
[GPS] Create a kml file in Python
Create a bot that boosts Twitter trends
Implement a Custom User Model in Django
Create a web service in Flask-SQLAlchemy + PostgreSQL
Models in Django
[Can be done in 10 minutes] Create a local website quickly with Django
I made a stamp substitute bot with line
Create a Vim + Python test environment in 1 minute
Create a GIF file using Pillow in Python
Create an executable file in a scripting language
I want to create a window in Python
Create a standard normal distribution graph in Python
How to create a JSON file in Python
Create a virtual environment with conda in Python
Enable Django https in just a few lines
Build a Django environment with Vagrant in 5 minutes
Create a dashboard for Network devices with Django!
Make a rock-paper-scissors game in one line (python)
I made a LINE Bot with Serverless Framework!
Create a protein sequence mutation library in pandas
Steps to create a Twitter bot with python
Create a simple momentum investment model in Python
Create a new page in confluence with Python
How to create a Kivy 1-line input box
Create a datetime object from a string in Python (Python 3.3)
Create a one-file hello world application with django
Create a package containing global commands in Python
Insert a date without line breaks in CotEditor
Make a LINE WORKS bot with Amazon Lex