98 lines
3.2 KiB
Python
98 lines
3.2 KiB
Python
import os
|
|
from flask import Flask, request, jsonify, send_from_directory, make_response
|
|
import sqlite3
|
|
from datetime import datetime
|
|
|
|
app = Flask(__name__)
|
|
|
|
# 환경 변수에서 설정값 불러오기
|
|
DB_PATH = '/data/weather.sqlite'
|
|
DOMAIN = os.getenv('DOMAIN', 'http://localhost:5000')
|
|
debug_env = os.getenv('FLASK_DEBUG', '0')
|
|
DEBUG_MODE = debug_env == '1'
|
|
|
|
def get_rain_data(date):
|
|
conn = sqlite3.connect(DB_PATH)
|
|
curs = conn.cursor()
|
|
|
|
curs.execute('SELECT time, rainfall FROM precipitation WHERE date = ? ORDER BY time', (date,))
|
|
time_rain_list = curs.fetchall()
|
|
|
|
curs.execute('SELECT total_rainfall FROM precipitation_summary WHERE date = ?', (date,))
|
|
row = curs.fetchone()
|
|
total_rainfall = row[0] if row else 0.0
|
|
|
|
conn.close()
|
|
return time_rain_list, total_rainfall
|
|
|
|
# 정적 파일 서빙: /data/ 경로로 이미지 접근 가능하게 함
|
|
@app.route('/data/<path:filename>')
|
|
def serve_data_file(filename):
|
|
return send_from_directory('/data', filename)
|
|
|
|
@app.route('/webhook', methods=['POST'])
|
|
def webhook():
|
|
try:
|
|
data = request.get_json(silent=True) # 사용자 발화가 필요한 경우: data['userRequest']['utterance']
|
|
today = datetime.today().strftime('%Y%m%d')
|
|
time_rain_list, total_rainfall = get_rain_data(today)
|
|
|
|
# 메시지 구성
|
|
if not time_rain_list:
|
|
response_text = f"{today} 날짜의 강수량 데이터가 없습니다."
|
|
else:
|
|
lines = []
|
|
for time_str, rain in time_rain_list:
|
|
rain_display = f"{rain}mm" if rain > 0 else "강수 없음"
|
|
lines.append(f"{time_str} → {rain_display}")
|
|
lines.append(f"\n영업시간 내 총 강수량은 {total_rainfall:.1f}mm 입니다.")
|
|
response_text = '\n'.join(lines)
|
|
|
|
# 이미지 포함 여부 확인
|
|
image_filename = f"weather_capture_{today}.png"
|
|
image_path = f"/data/{image_filename}"
|
|
outputs = [{
|
|
"simpleText": {
|
|
"text": response_text
|
|
}
|
|
}]
|
|
if os.path.isfile(image_path):
|
|
image_url = f"{DOMAIN}/data/{image_filename}"
|
|
outputs.append({
|
|
"image": {
|
|
"imageUrl": image_url,
|
|
"altText": "오늘의 날씨 캡처 이미지"
|
|
}
|
|
})
|
|
|
|
# 응답 본문 구성 (version을 최상단에)
|
|
response_body = {
|
|
"version": "2.0",
|
|
"template": {
|
|
"outputs": outputs
|
|
}
|
|
}
|
|
|
|
# 응답 헤더 설정
|
|
resp = make_response(jsonify(response_body))
|
|
resp.headers['Content-Type'] = 'application/json; charset=utf-8'
|
|
return resp
|
|
|
|
except Exception as e:
|
|
error_body = {
|
|
"version": "2.0",
|
|
"template": {
|
|
"outputs": [{
|
|
"simpleText": {
|
|
"text": f"서버 오류가 발생했습니다: {str(e)}"
|
|
}
|
|
}]
|
|
}
|
|
}
|
|
resp = make_response(jsonify(error_body))
|
|
resp.headers['Content-Type'] = 'application/json; charset=utf-8'
|
|
return resp
|
|
|
|
if __name__ == '__main__':
|
|
app.run(host='0.0.0.0', port=5000, debug=DEBUG_MODE)
|