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