[PYTHON] The easiest line bot in the world to lose weight

Introduction

This line bot was produced three months after starting programming for the school's product presentation. If anyone is wondering what to make after starting learning, I hope it will be helpful. Also, since this is the first product I made, there are a few parts where the code is rough. What if this is like this? If there is a part, I would appreciate it if you could let me know in the comments.

Why i made it

I was always dissatisfied with getting fat and being too difficult to lose weight. ** A diet will not succeed unless you exercise ideally and continue to eat calorie-calculated rice for 3 months, at least 1 month. ** However, to achieve that, you have to avoid temptations like Mara. Unbearable resting desire at the end of work. Ramen craving and drinking craving that can be said to be chronic. A feeling of repulsion to exercise due to lack of exercise. The battle of modern people is always difficult. So ** If you eat and get fat, you can lose weight just by eating! ** This line bot was created with such an easy service in mind.

Why you lose weight

By the way, do you know how many kilograms you need to burn to lose 1 kilogram? ** Actually, this is said to be 7,000 kilokcal. ** ** In this line bot, basal metabolism is calculated based on the height, weight, age, and gender entered, the target intake kcal 1000 kcal less than that is calculated, and a menu is randomly created from LAWSON and 7-Eleven products, and on the line. It will send it to you. ** In other words, you can save 7,000 kcal per week and lose 1 kg just by purchasing and eating the menu items you received on the line. A monthly diet of 4 kg is a success! !! All you have to do is eat as you are told! !! !! ** **

target

People who want to lose weight without exercising (especially women who are not good at exercising) People who want to maintain their current body shape (recommended the day before and after a party or drinking party!) People who live alone and have trouble thinking about what to eat every day

Register as a friend

If you would like to try this line bot, please add friends on LINE below. 646hrric.png

How to use

<img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/578416/0b681596-8685-e688-bf75-4ff3cdc4ac03.jpeg "width=70%>

  1. First, add a friend and send "Settings" to receive the message.
  2. Complete the personal data settings according to the format sent (Input example: ** Registration. 178-78-25-1 **)
  3. After that, you can receive the menu by sending "Lawson" or "Seven".

Implemented function

  1. Save the results of scraping web pages in a list as a file
  2. Calculate the kcal to be ingested in the morning, day and night from the personal data received from the user, and save it in the database together with the acquired user id.
  3. When the menu request is received from the user, the data of the corresponding user is called from the database.
  4. Randomly select products from the convenience store product list and loop until they are close to the target kcal. Send the result to the user

About the code

Only the scraping code and the main code are listed. If you want to see the full text, please visit my git hub. git hub

Scraping code

Since it is long to put Lawson on it, only Seven is listed.

mk-data.py


import requests
from bs4 import BeautifulSoup as bs
import pickle

Use BeautifulSoup for scraping and pickle to save to a file.

mk-data.py


#Seven scraping function
def seven_scraping(url):
    header = {"User-Agent" : "Mozilla/5.0"}
    s = bs(requests.get(url, headers=header).content, 'html.parser')
    
    #name
    s_names = []
    for i in s.find_all('div', class_='itemName'):
        s_names.append(i.text)

    #image
    s_images = []
    for i in s.find_all('div', class_='image'):
        j = i.a.get("href")
        s_images.append("https://www.sej.co.jp"+j)

    #calorie
    s_kcals = []
    for i in s.find_all('div', class_='summary'):
        j = i.find('li', class_ ='n1')
        j = j.text
        j = j.strip("* Calories may vary depending on the region.")
        j = j.split("kcal")[0]
        j = int(j)
        s_kcals.append(j)

    return list(zip(s_kcals, s_names, s_images))

Create scraped data as a list of names, images and calories. A function that finally combines them into a single list and returns it.

mk-data.py


def main():
    seven_url ="https://www.sej.co.jp/i/products/anshin/calorie/"
    seven_list = seven_scraping(seven_url)
    f = open('seven_list.txt', 'wb')
    list_row02 = seven_list
    pickle.dump(list_row02, f)

if __name__ == '__main__':
    main()

Execute function and save to file using pickle

Main code

main.py


from flask import Flask, request, abort
import os
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

import re
import pickle
import random
import sqlite3

main.py


app = Flask(__name__)
LINE_CHANNEL_ACCESS_TOKEN = os.environ["LINE_CHANNEL_ACCESS_TOKEN"]
LINE_CHANNEL_SECRET = os.environ["LINE_CHANNEL_SECRET"]
line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(LINE_CHANNEL_SECRET)
f = open("./lawson_list.txt","rb")
list_row = pickle.load(f)
f02 = open("./seven_list.txt","rb")
list_row02 = pickle.load(f02)

Call up the product data saved earlier.

main.py


#Function to calculate basal metabolism and return target value
def base_energy(tall, weight, age, sex):
    if sex == 1:
        result = 13.397 * weight + 4.799 * tall - 5.677 * age + 88.362
        return result
    else:
        result = 9.247 * weight + 3.098 * tall - 4.33 * age + 447.593
    
    result = (result * 1.75) -1000
    return round(result)

Basal metabolic rate is calculated using the Harris-Benedict equation (improved version). Male: 13.397 x weight kg + 4.799 x height cm-5.677 x age + 88.362 Female: 9.247 x weight kg + 3.098 x height cm-4.33 x age +447.593 Reference: "https://keisan.casio.jp/exec/system/1161228736"

main.py


#Calculate calories in the morning and day / night
def create_before(aim_kcal):
    return int(aim_kcal * 0.2)
def create_after(aim_kcal):    
    return int(aim_kcal * 0.4)

#Function to randomly select a menu
def make_menu(aim_num, conv_list):
    menu = []
    x = 0
    #Loop until the target calorie is 100 kcal
    for i in range(150):
        i = random.choice(conv_list)
        if aim_num -100 <= x <= aim_num + 100:
            return menu
            break
        if i[0] + x <= aim_num + 100:
            x += i[0]
            menu.append(i)
        else:
            continue 

Set the daily target kcal to a ratio of 2: 4: 4 in the morning: day: night. The menu creation function is a power play that keeps calling from the product list at random until it approaches the target value. ↓ A little omitted

main.py


@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    word = event.message.text
    if word in ["Lawson"]:
        #Call up basal metabolic data in the morning, day and night
        profile = line_bot_api.get_profile(event.source.user_id)
        user_id = profile.user_id
        conn = sqlite3.connect('database.sqlite3')
        c = conn.cursor()
        c.execute('SELECT * FROM user WHERE id=?', (user_id,))
        list1 = c.fetchone()
        before_noon = list1[1]
        after_noon = list1[2]
        conn.commit()
        conn.close()
        today_morning = make_menu(before_noon, list_row)
        today_lunch = make_menu(after_noon, list_row)
        today_dinner= make_menu(after_noon, list_row)
        today_menu = []
        for i in today_morning:
            today_menu .append( "\n breakfast" + str(i))
        for i in today_lunch:
            today_menu.append("\n Lunch" + str(i))
        for i in today_dinner:
            today_menu.append("\n night meal" + str(i))
        reply = ','.join(today_menu)

        line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=reply))

When you receive a menu request, get user_id and call the target calorie of the corresponding user. Send the menu and the menu created from the product list to the user.

main.py


    elif word in ["Setting"]:
        setup_text = """Please enter in the following format\
        
Registration. height-body weight-age-Gender (1 male or 2 female)
* Please use half-width numbers
* Example: Registration. 168-68-24-1
        """
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=setup_text))

    elif 0 <= word.find('Registration.') :
        #Divide the received data by height, weight, age and gender
        #Base it_Pass to energy
        personal_data = event.message.text
        personal_data = personal_data.replace("Registration.", "")
        personal_data = personal_data.replace("-", ",")
        personal_data = personal_data.split(',')
        tall = int(personal_data[0])
        weight = int(personal_data[1])
        age = int(personal_data[2])
        sex = int(personal_data[3])
        aim_kcal = base_energy(tall, weight, age, sex)
        #Calculate calories for each meal
        #Write to database
        profile = line_bot_api.get_profile(event.source.user_id)
        prof_dict = {}
        prof_dict["id"] = profile.user_id
        prof_dict["before_noon"] = create_before(aim_kcal)
        prof_dict["after_noon"] = create_after(aim_kcal)
        conn = sqlite3.connect('database.sqlite3')
        c = conn.cursor()
        c.execute('insert into user(id, before_noon, after_noon) values(:id, :before_noon, :after_noon);', prof_dict)
        conn.commit()
        conn.close()

        line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text="The setting is complete"))

    else:
        line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text="Enter Lawson or Seven or Settings"))

if __name__ == "__main__":
    port = int(os.getenv("PORT", 5000))
    app.run(host="0.0.0.0", port=port)
    app.run()

Process the data sent from the user according to the format, set the target value, and divide it into morning, day and night.

$ heroku login
heroku create <Application name>

Register your application on heroku

$ git init
$ git add .
$ git commit -m "new commit"
$ git push heroku master

Push and finish.

Usability

I used it myself for a week after it was completed. As an impression

Benefits

  1. Surprisingly many salads are healthy (low-calorie salads are easily selected by a loop that calls products at random)
  2. I eat things that I don't usually buy, so I sometimes come across products that impress me.
  3. There is a feeling of fullness unexpectedly 4, ** I lost 1 kg! !! ** ** IMG_20200202_112624.jpg One day supper (unexpectedly volumey)



Disadvantages

  1. Not suitable for saving (it costs 1500-2000 yen a day) 2, many out of stock
  2. I get tired of continuous use (even if I use it without overdoing it, it is effective)

Profit plan (if a major convenience store introduces a similar service)

1. Advertising effect

** Since the daily purchase cost is 1500 yen or more, it is expected that sales will increase by about 45,000 yen or more per month with one active user. If you have 100 people, you can expect more than 4.5 million yen. ** ** In addition, the advertising effect is quicker to directly lead to purchasing behavior than other media. For example, when we learn about a new product on a TV commercial, we have some time lag before we actually buy it. It is rare that you actually see an advertisement and purchase it immediately, and the advertising effect works on your subconscious mind, which leads to purchasing behavior after a while. In that case, since it unknowingly affected customer behavior, the only way to measure advertising effectiveness is to infer from the increase or decrease in sales. On the other hand, with this service, users are highly expected to make purchases on the day they receive the menu, and it is easy for Line developers to determine how many active users they have. Moreover, the cost itself is the highest, about 30,000 yen a month, which is cheaper than other media. ** In other words, it has high advertising effectiveness, immediate effect, grasping power, and can be implemented at low cost. ** **

2. Good compatibility between the review function and coupons

If you answer "whether you want to eat again", you can expect an increase in the repeat rate of users and the acquisition of customer product evaluations by adding a function to issue discount coupons limited to the next day. From the user's point of view, not only the merit of "thinning" but also the merit of "buying cheaply" the next day can be obtained, and the weak point of this service, "not suitable for saving", can be covered to some extent. It also helps to continue the diet. From the perspective of companies, if the continuation rate goes up, sales will go up, and since the menus are random, there is a big merit that data on a wide range of products can be obtained.

3. Usefulness as big data

Convenience store loyalty cards only collect data on what gender and age people purchased the product. In other words, it's just the data up to the point of purchase. However, the business does not end at the time of purchase. We think that "this product will meet our needs", buy it, use it, have an impression, and decide whether to repeat it. Collecting post-purchase data is important for creating a mechanism for continuous customer acquisition. ** Purchasing data and product evaluation data for each customer. ** The merit of combining two data is very large.

4, utilization example

Divide the products into four groups from the above two data. ① Sales are high, </ font> evaluation is also high </ font> products ② Sales are high, </ font> evaluation is low </ font> products ③ Sales are low, </ font> evaluation is high </ font> products ④ Sales are low, </ font> evaluation is also low </ font> products

無題のプレゼンテーション.jpg

Dividing into the above groups will greatly benefit in terms of product development strategy and distribution management. First of all, in terms of distribution management, high sales can be expected for product (1) in the future, but for (4), it is unlikely that customers will purchase it, and even if it is purchased, repeats cannot be expected. ** By discontinuing production of ④ early and increasing production of ①, it is expected to reduce waste at stores and improve operating income. ** ** Next, regarding product development, we can receive great merits by analyzing (2) and (3). ② is harmful. This is because it is a product that disappoints the expectations of many customers. Many people find it attractive to buy, but they are disappointed when they go home and eat. However, there is no doubt that ** ② is a very attractive product ** until you buy it, and there is something that customers can get. ** In other words, product marketing itself is likely to be successful. ** ③ is not selling now, but it may start selling with wrinkles over time, or it may sell by changing the design or naming. If the analysis of (2) is used, there is a possibility that sales will increase significantly.

5. Business expansion

Convenience stores are the business that has the potential to collect data on the purchases and preferences of the most Japanese people. Also, since we handle not only our own products but also other companies' products (major confectionery companies, food companies, etc.), we think that if we sell big data and its analysis to those companies, we will be able to make even more profits. I also think it would be interesting to use the know-how cultivated through data analysis to produce local products from local companies.

Recommended Posts