First, log in with your line account to get a line developers account
Create a new provider from console home in the upper left
Select create new channel from the provider of that, and the channel type is messaging API
After that, make each setting. At this point, you can register your own line bot with the qr code.
This time, if I press this meeting reservation, I would like the user to automatically send the reservation and return something to it.
First, log in here and select the account you created earlier https://www.linebiz.com/jp/login/ Select the rich menu from the menu on the left Click the create button on the upper right Display settings are OK by default except for the title
For the content settings below it, select a template and paste an image, or create an image with text yourself. If you can make it, make a reservation with the type as text in the action. If you tap the menu you saved and actually created on your smartphone, you will receive a message saying that you have made a reservation.
Now that I've done this, I'd like to return something to the booking message sent by Django.
This time I'll install django using anaconda, the python version and package management system. https://www.anaconda.com/products/individual If you haven't put it in, please download it from the top of ↑ When anaconda is installed, launch anaconda navigator Select Environments Select create at the bottom left Name it django37 etc. and select python and version 3.7 Select create at the bottom right to complete the environment construction In this state, django is not included yet, so open the terminal
$ conda activate django37
Launch the environment with afterwards
$ conda install django37
Install Django with Now you have an environment.
Then first
$ django-admin startproject reception_line_bot
Create a project with.
reception_line_bot/
manage.py
reception_line_bot/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
I think I made it like this. Next, create an application.
$cd reception_line_bot
After entering reception_line_bot with,
$ python manage.py startapp bot
Then
bot/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
I think it became. Next, edit reception_line_bot / urls.py with an editor.
urls.py
"""reception_line_bot URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
import bot.views
urlpatterns = [
path('admin/', admin.site.urls),
]
I think this is the case, but in urlpatterns, specify which function in which file the line bot request received by django should be sent.
So this time
urls.py
import bot.views
urlpatterns = [
#path('admin/', admin.site.urls),
path('', bot.views.reception),
]
will do. reception is a function that we will write in views.py.
The channel secret and access token issued when I created the line bot before writing the code in views.py is bad if I write it directly in the code, so I would like to make it available in views.py through json. So create setting.json under line_reception_bot at the top and Select a channel from providers, issue an access token at the top of the messaging API, and copy and paste. next Get the Channel secret from the Basic settings next to the messaging API. I will copy and paste those two to the setting.json I made earlier
setting.json
{
"LINE":{
"channel_secret":"fakfkajpdpaida132941",
"access_token":"a3nm7yOY7IoUt8blZ6QqK6RShadfsajdjfadfljfafdsdjsdfailfajjpqjpoejpqjpfjpqejiepqwifqpjdjidcS9yEBGieq+VMQs0EL+mQDtwdB04daft89/aad1O/w1cDnyilFU="
}
}
Like this (channel_secret and access_token have been changed appropriately) Then open views.py and write some code to send something to the message sent by the user.
views.py
from django.views.generic import TemplateView
from django.shortcuts import render
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
import urllib.request
from reception_line_bot.settings import BASE_DIR
# Create your views here.
@csrf_exempt
def reception(request):
json_open = open('setting.json', 'r')
json_load = json.load(json_open)
channel_secret = json_load['LINE']['channel_secret']
access = json_load['LINE']['access_token']
request_body = request.body
data = confirm_json_loads(request_body)
request_body = request.body
body = request.body.decode('utf-8')
print(body)
reply_token = data["events"][0]["replyToken"]
reply_message(reply_token,access)
return JsonResponse({"message":"OK"})
def confirm_json_loads(body:str)->dict:
"""
json_Check if loads are working
Args:
body str:
request json string
Return:
dict:
Seccess:json.loads(body)Return value of
Error:Login failure message
"""
try:
return json.loads(body)
except Exception as e:
print("error")
message = JsonResponse({'message': 'Login failure.'}, status=403)
return message
def reply_message(token:str,access)->None:
return False
"""
Send a reply message to the user
Args:
token str:
line token
message str:
select_The message returned by the message function
user_id str:
Message sender's line user id
"""
url = 'https://api.line.me/v2/bot/message/reply'
print(url)
data = {
'replyToken': token,
'messages':[
{
'type': 'text',
'text': "hello world"
},
]
}
print(f"data{data}")
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer'+" "+access
}
print(f"headers:{headers}")
req = urllib.request.Request(url, json.dumps(data).encode(), headers)
print(req)
with urllib.request.urlopen(req) as res:
body = res.read()
That's all there is to it.
Recommended Posts