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 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
Create a project as you like.
$ django-admin startproject qiita_linebot
$ cd qiita_linebot/
$ python manage.py startapp qiita_linebot_ai
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),
]
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.
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
.
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.
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
You can start it like this. Please replace the ngrok URL that appears after this with your own as appropriate.
Messaging API settings|>Webhook settings|>WebhookURL
From
Enter https://ecdb2a20.ngrok.io/qiita_linebot_ai/
.
Add ngrok to ALLOWED_HOSTS as follows.
settings.py
ALLOWED_HOSTS = ["ecdb2a20.ngrok.io"]
You're ready to go!
If you start the server and return it as follows, you are successful!
Recommended Posts