[Python] I made a bot that tells me the current temperature when I enter a place name on LINE

The finished product looks like this. It also supports place names that you have never heard of. If there is no spill in the place name → Geocoder → Dark Sky, it will be displayed. Personally, I always want to check Vostok Station.

Screenshot_20200417-192323.png

Referenced Qiita page, account acquisition procedure, I will gradually add to it, such as deploying to Heroku.

About the environment etc. ・ Windows 10 ・ Python 3.7.5 ・ Heroku ・ Git ・ Line developer account ・ Darksky API

I created 4 files Procfile requirements.txt runtime.txt python:main.py

web: python main.py

requirements.txt


Flask==1.1.1
line-bot-sdk==1.16.0
geocoder==1.38.1

runtime.txt


python-3.7.5

main.py



from flask import Flask, request, abort
import os
#Try below
#import time
import requests
import geocoder
#import tweepy
#Try above

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

app = Flask(__name__)

#Get environment variables
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():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
#0327 added
    place = event.message.text
    ret = geocoder.osm(place, timeout=5.0)
#Remove unnecessary parentheses from acquired geodata to post to darksky
    locate = str(ret.latlng)
    locate2 = locate.replace('[','')
    locate3 = locate2.replace(']','')
#Set the desired acquisition location to Celsius by specifying the SI unit for post url0
    url0='?units=si'
    url1='https://api.darksky.net/forecast/*API_KEY*/'
    url2=url1 + locate3 + url0
#Get in JSON format
    data=requests.get(url2).json()
    data2=data['currently']['temperature']
    word=str(data2)
    word += "℃ Death"
#Latitude and longitude display added in the following two lines 2020_04_11
    word += "\n\n latitude and longitude\n"
    word = word + locate
#0327

    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=word))
#0327        TextSendMessage(text=event.message.text))

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

Errors etc. have not been processed. Let's do it soon ...

Information as of April 2020 DarkSky has been acquired by Apple and new APIs are no longer accepted. The service will be until the end of 2021 (crying) It will be necessary to verify whether the OpenWetherMap API can be used as an alternative.

Recommended Posts

[Python] I made a bot that tells me the current temperature when I enter a place name on LINE
I made a slack bot that notifies me of the temperature
[Python] I made a Line bot that randomly asks English words.
I made a Discord bot in Python that translates when it reacts
I started to work at different times, so I made a bot that tells me the time to leave
I made a LINE BOT that returns a terrorist image using the Flickr API
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
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
[Discode Bot] I created a bot that tells me the race value of Pokemon
In Python, I made a LINE Bot that sends pollen information from location information.
I made a LINE BOT with Python and Heroku
I made a LINE bot that tells me the type and strength of Pokemon in the Galar region with Heroku + Flask + PostgreSQL (Heroku Postgres)
I made a LINE BOT that returns parrots with Go
[Python] I tried to make a simple program that works on the command line using argparse.
When Selenium tells me that the Chrome driver version is different (Python)
I made a stamp substitute bot with line
A memo that I stumbled upon when doing a quote RT on Twitter Bot
I made a Linebot that notifies me of nearby evacuation sites on AWS
I made a LINE Bot with Serverless Framework!
[Python] A program that calculates the difference between the total numbers on the diagonal line.
The story of making a Line Bot that tells us the schedule of competitive programming
A story that I was addicted to when I made SFTP communication with python
I made a Mattermost bot with Python (+ Flask)
I tried to make the weather forecast on the official line by referring to the weather forecast bot of "Dialogue system made with python".
I want a Slack bot that calculates and tells me the salary of a part-time job from the schedule of Google Calendar!
A story that got stuck when trying to upgrade the Python version on GCE
A template that I often use when making Discord BOT in Python (memorial note)
The world changed when I opened a big Python project (Django) on Sourcetrail (Linux)
[Python / C] I made a device that wirelessly scrolls the screen of a PC remotely.
[AWS] I made a reminder BOT with LINE WORKS
I made a Twitter BOT with GAE (python) (with a reference)
I made a household account book bot with LINE Bot
I made a VM that runs OpenCV for Python
I made a Python3 environment on Ubuntu with direnv.
A memo that I touched the Datastore with python
I made a program to collect images in tweets that I liked on twitter with Python
A story that stumbled when I made a chatbot with Transformer
[Python] I asked LINE BOT to answer the weather forecast.
I want to send a message from Python to LINE Bot
I made a VGG16 model using TensorFlow (on the way)
When I made a Discord Bot, my classmates destroyed my computer
I made a Chatbot using LINE Messaging API and Python
I made a neural network generator that runs on FPGA
[AWS] I made a reminder BOT with LINE WORKS (implementation)
Workaround for the problem that sys.argv is not passed when executing a Python script with only the file name in Python2.7 on Windows
Hannari Python At the LT meeting in December, I made a presentation on "Python and Bayesian statistics".
I made something with python that NOW LOADING moves from left to right on the terminal
I made a python text
A story that didn't work when I tried to log in with the Python requests module
I made a discord bot
About the error I encountered when trying to use Adafruit_DHT from Python on a Raspberry Pi
Life game with Python [I made it] (on the terminal & Tkinter)
[Python3] I made a decorator that declares undefined functions and methods.
I made a package that can compare morphological analyzers with Python
I want to know the weather with LINE bot feat.Heroku + Python
I made a program that solves the spot the difference in seconds
Easy! Implement a Twitter bot that runs on Heroku in Python
I created a Python library to call the LINE WORKS API
I made a Twitter bot that mutters Pokemon caught by #PokemonGO
I made a shuffle that can be reset (reverted) with Python