In Python, I made a LINE Bot that sends pollen information from location information.

(1) Background

・ I always suffer from pollen from this time. ・ This year, there is corona, and people with hay fever are having a hard time. ・ Insufficient mask. ・ I want to make something using python, scraping, and heroku. ・ Output image ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ unnamed.png

(2) Environment construction

Create a directory line_kafun on your desktop. Create main.py that handles line-sdk and weather.py that collects pollen information from Yahoo weather information.

The directory structure is as follows.

line_kafun
├main.py
├weather.py
├Procfile
├runtime.txt
└requirements.txt

Install the required packages.

pip install flask
pip install line-bot-sdk
pip install beautifulsopu4
pip install gunicorn
pip install lxml
pip install requests

(3)main.py

.py:main.py


from flask import Flask, request, abort
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,LocationMessage
)
import os
import weather as wt #weather.Import py


app = Flask(__name__)

#Heroku environment variable settings
YOUR_CHANNEL_ACCESS_TOKEN = os.environ["YOUR_CHANNEL_ACCESS_TOKEN"]
YOUR_CHANNEL_SECRET = os.environ["YOUR_CHANNEL_SECRET"]

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)

@app.route("/")
def hello_world():
    return "hello world!"


@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return 'OK'



@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    if 'pollen' in event.message.text:
        line_bot_api.reply_message(
            event.reply_token,
       [
            TextSendMessage(text='What is your current location information?'),
            TextSendMessage(text='https://line.me/R/nv/location/'),
            ]
        )
  

@handler.add(MessageEvent, message=LocationMessage)
def handle_location(event):
    text = event.message.address
    result = wt.get_weather(text)
    line_bot_api.reply_message(
    event.reply_token,
    TextSendMessage(text=result + '\uDBC0\uDC20')
    )


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

Supplementary explanation

-For the address in the place of text = event.message.address, refer to [api reference] of line developers (https://developers.line.biz/ja/reference/messaging-api/#audio-message). Screenshot 2020-03-25 22.51.02.png -For the TextSendMessage part, I referred to the URL scheme of the LINE api reference. スクリーンショット 2020-03-25 23.03.19.png ・ ** The URL scheme can only be used for one-on-one talks, not for groups. ** ** ・'\ UDBC0 \ uDC20' is an emoji, and I referred to Use "LINE emoji" in LINE BOT. ..

(4)weather.py Scraping pollen information from Yahoo.

.py:weather.py


import requests
from bs4 import BeautifulSoup
import re
import lxml


def get_weather(text):
    location = re.findall('\d{3}-\d{4}',text)
    location2 = location[0].replace('-','')
    url1 = "https://weather.yahoo.co.jp/weather/search/?p={}".format(location2)
    url2 = ""

    #Get the html information from the first url and get the second url from there
    res = requests.get(url1)
    res.encoding = res.apparent_encoding
    html_doc = res.text
    soup = BeautifulSoup(html_doc,"lxml")
    content_1 = soup.find_all(id = 'rsltmuni')
    for i in content_1:
        content_2 = i.find('a')
        url2 = 'https:' + content_2.get('href')


    #Get today and tomorrow dates from the second url(today、nextday)
    res = requests.get(url2)
    res.encoding = res.apparent_encoding
    html_doc = res.text
    soup = BeautifulSoup(html_doc,"lxml")
    content_3 = soup.find_all('p',class_='date')
    today = content_3[0].get_text()
    nextday = content_3[1].get_text()

    #Get pollen status today and tomorrow
    content_4 = soup.find_all('p',class_='flying')
    today_kafun = content_4[0].get_text()
    nextday_kafun = content_4[1].get_text()

    #Get area
    content_5 = soup.find_all('h2',class_='yjM')
    area = content_5[0].get_text()


    result = today + 'of' + area + 'Is' + '「{}」'.format(today_kafun) + 'That's right.' + '\n' +'\n'+ nextday + 'of' + area + 'Is' + '「{}」'.format(nextday_kafun) + 'That's right.' + '\n' +'\n' + 'be careful.'

    return result

(5) Deploy to Heroku and set up LINE Developers webhooks

Finally, create the required files (requirements.txt, Procfile, runtime.txt) and deploy to Heroku. Since the deployment method is introduced on many sites, it is omitted. For details, refer to Making a bulletin board with Heroku, Flask, SQLAlchemy. Also, the LINE Developers Webhook settings are also introduced on many sites, so I will omit them. For details, refer to Making a LINE BOT.

When you enter "pollen" in the completed LINE Bot, you will be asked for location information, so tap it to get pollen information (completed).

Recommended Posts

In Python, I made a LINE Bot that sends pollen information from location information.
[Python] I made a Line bot that randomly asks English words.
I made a Discord bot in Python that translates when it reacts
I made a LINE BOT with Python and Heroku
I made a Line Bot that uses Python to retrieve unread Gmail emails!
I made a LINE Bot that sends recommended images every day on time
I want to send a message from Python to LINE Bot
I made a payroll program in Python!
I made a Line bot that guesses the gender and age of a person from an image
I made a garbled generator that encodes favorite sentences from UTF-8 to Shift-JIS (cp932) in Python
I made a web application in Python that converts Markdown to HTML
[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]
I made a stamp substitute bot with line
A memo that I wrote a quicksort in Python
I made a LINE Bot with Serverless Framework!
I made a Caesar cryptographic program in Python.
I made a Mattermost bot with Python (+ Flask)
[Python] I made a bot that tells me the current temperature when I enter a place name on LINE
I made a Docker image that can call FBX SDK Python from Node.js
[AWS] I made a reminder BOT with LINE WORKS
I made a Twitter BOT with GAE (python) (with a reference)
I made a prime number generation program in Python
I made a household account book bot with LINE Bot
I made a VM that runs OpenCV for Python
I made a prime number generation program in Python 2
A template that I often use when making Discord BOT in Python (memorial note)
I made a python text
I made a discord bot
I made a simple typing game with tkinter in Python
python Condition extraction from a list that I often forget
I made a quick feed reader using feedparser in Python
Until I return something with a line bot in Django!
I made a Chatbot using LINE Messaging API and Python
[AWS] I made a reminder BOT with LINE WORKS (implementation)
I made a program to collect images in tweets that I liked on twitter with Python
I made a Line-bot using Python!
I made a fortune with Python.
I made a daemon with Python
I tried Line notification in Python
Create a LINE Bot in Django
[Python3] I made a decorator that declares undefined functions and methods.
I made a package that can compare morphological analyzers with Python
I made a program that solves the spot the difference in seconds
Easy! Implement a Twitter bot that runs on Heroku in Python
Describe a network that accepts annotation information from users in Keras
How to get a string from a command line argument in python
I made a Twitter bot that mutters Pokemon caught by #PokemonGO
I made a shuffle that can be reset (reverted) with Python
[LINE Messaging API] Create a BOT that connects with someone with Python
I made a library that adds docstring to a Python stub file.
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
[python] I made a class that can write a file tree quickly
I made a plugin to generate Markdown table from csv in Vim
[Python] I made a decorator that doesn't seem to have any use.
A story about a beginner making a VTuber notification bot from scratch in Python
I made a character counter with Python
I tried to develop a Formatter that outputs Python logs in JSON
[Python] I made a utility that can access dict type like a path
I made a script in python to convert .md files to Scrapbox format
I made a simple timer that can be started from the terminal
I made a Hex map with Python