[PYTHON] Best practices for dynamically handling LINE Flex Messages in Django

Hello! I will post to Qiita for the first time, so please briefly introduce yourself. I am a student attending a certain information cooperation department. (Even if you say something ...) My favorite browsers are Firefox and Edge (Chromium).

By the way, in the latter half of the first grade, all of us will develop a team using Django in class. I created a LINE bot last year, but at that time, I did not find a good way to handle Flex Messages of the LINE Messaging API dynamically with Django, so I also wrote a memorandum of my personal best practices. I will write it here as well. See here for Flex Message.

approach

Django provides a template language called Django Template Language. In addition, Flex Message of LINE Messaging API is written in JSON format. Using them, I would like to take the approach of embedding information in a template JSON file and sending a Flex Message when the Django server sends a message. (It's the same as working with HTML files in Django)

Specific method

I think that you usually use render () etc. to embed information in an HTML file and send it with Django, but since this is for HTTP response, I will not use it this time. Use render_to_string () instead.

This time, as shown in the image below, let's take an example of a bot that displays the sent sentence and date with Flex Message. linebot.jpg The full text of message.json and views.py used in the example can be found in GitHub Gist.

Code example

This is a slightly modified version of the official LINE sample code for Django.

import json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.template.loader import render_to_string
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.models import (
    MessageEvent, TextMessage, FlexSendMessage, BubbleContainer
)

#settings.Get access token etc. from py (here you like)
line_bot_api = LineBotApi(channel_access_token=settings.LINE_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(channel_secret=settings.LINE_CHANNEL_SECRET)

#(abridgement)

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    msg_text=event.message.text
    today_date = datetime.datetime.now()
    msg = render_to_string("message.json", {"text": msg_text, "date": today_date})
    line_bot_api.reply_message(
        event.reply_token,
        FlexSendMessage(alt_text = msg_text, contents = BubbleContainer.new_from_json_dict(json.loads(msg)))
    )

** The important thing is here **

msg_text=event.message.text
today_date = datetime.datetime.now()
msg = render_to_string("message.json", {"text": msg_text, "date": today_date})

In the {{text}} part of message.json placed under the templates folder, msg_text which is the content entered in LINE is in the part of{{date}}, which is the current date and time. today_date is now filled with render_to_string ().

Summary

These are my personal best practices when working with LINE Flex Messages dynamically in Django. I hope you find it useful.

reference

--Django Template Language Documentation -Documentation for render_to_string function

Recommended Posts

Best practices for dynamically handling LINE Flex Messages in Django
Best practices for Django views.py and urls.py (?)
Personal best practices for putting command line launch Python projects in Docker containers
Dynamically add form fields in Django
Configuration file best practices in Flask
Create a LINE Bot in Django
Same-Site attribute setting for cookies in Django
Dynamically specify a ModelChoiceField queryset in Django
Get query parameters for GET requests in Django
Sample for handling eml files in Python
Best practices for messing with data with pandas