[PYTHON] Until I return something with a line bot in Django!

Make a line bot with Django!

First, log in with your line account to get a line developers account image.png

Create a new provider from console home in the upper left line.png

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. IMG_0891.jpg

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 image.png Display settings are OK by default except for the title image.png

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.

Return a message using with Django

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 ↑ image.png 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 image.png Select a channel from providers, issue an access token at the top of the messaging API, and copy and paste. next image.png 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

Until I return something with a line bot in Django!
Create a LINE Bot in Django
I made a stamp substitute bot with line
I made a LINE Bot with Serverless Framework!
[AWS] I made a reminder BOT with LINE WORKS
I made a household account book bot with LINE Bot
I made a LINE BOT with Python and Heroku
I made a LINE BOT that returns parrots with Go
[AWS] I made a reminder BOT with LINE WORKS (implementation)
[Python] [LINE Bot] Create a parrot return LINE Bot
I made a WEB application with Django
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
Create a LINE BOT with Minette for Python
Start Django in a virtual environment with Pipenv
Build a Django environment with Vagrant in 5 minutes
Configure a module with multiple files in Django
Until you create a new app in Django
Make a LINE WORKS bot with Amazon Lex
I made a Mattermost bot with Python (+ Flask)
In Python, I made a LINE Bot that sends pollen information from location information.
I made a Twitter BOT with GAE (python) (with a reference)
I tried to create a table only with Django
Make a morphological analysis bot loosely with LINE + Flask
I want to transition with a button in flask
Make a parrot return LINE Bot on AWS Cloud9
I want to work with a robot in python.
Output a character string with line breaks in PyYAML
I can't manipulate iframes in a page with Selenium
[Super easy] Let's make a LINE BOT with Python.
[LINE Messaging API] Create parrot return BOT with Python
Explaining how to make LINE BOT in the world's easiest way (2) [Preparing a bot application in a local environment with Django in Python]
Try running python in a Django environment created with pipenv
I made a simple typing game with tkinter in Python
[In one line] Visualize like a lawn with just Pandas
Make a LINE bot with GoogleAppEngine / py. Simple naked version
Create a machine learning app with ABEJA Platform + LINE Bot
I want to make a blog editor with django admin
Create a homepage with django
I made a command to generate a table comment in Django
Make a LINE BOT (chat)
I want to send a message from Python to LINE Bot
I can't log in to the admin page with Django3
I made a puzzle game (like) with Tkinter in Python
Parrot return LINE BOT creation
I made a discord bot
[Python] I made a Line bot that randomly asks English words.
I want to know the weather with LINE bot feat.Heroku + Python
Create a temporary file with django as a zip file and return it
I made a Twitter Bot with Go x Qiita API x Lambda
[LINE Messaging API] Create a BOT that connects with someone with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I made a development environment for Django 3.0 with Docker, Docker-compose, Poetry
reload in django shell with ipython
I get a UnicodeDecodeError in mecab-python3
I made a wikipedia gacha bot
I get a KeyError in pyclustering.xmeans
Deploy a Django application with Docker
I made a fortune with Python.
Django Tips-Create a ranking site with Django-
Build a web application with Django
Make a filter with a django template