no message

This commit is contained in:
2025-06-30 16:03:34 +09:00
parent ca84b335d5
commit 8c84842a22

View File

@ -5,12 +5,13 @@ from datetime import datetime
app = Flask(__name__) app = Flask(__name__)
# 환경 변수에서 설정값 불러오기
DB_PATH = '/data/weather.sqlite' DB_PATH = '/data/weather.sqlite'
DOMAIN = os.getenv('DOMAIN', 'http://localhost:5000') DOMAIN = os.getenv('DOMAIN', 'http://localhost:5000')
debug_env = os.getenv('FLASK_DEBUG', '0') debug_env = os.getenv('FLASK_DEBUG', '0')
DEBUG_MODE = debug_env == '1' DEBUG_MODE = debug_env == '1'
def get_rain_data(date): def get_rain_data(date):
conn = sqlite3.connect(DB_PATH) conn = sqlite3.connect(DB_PATH)
curs = conn.cursor() curs = conn.cursor()
@ -25,20 +26,21 @@ def get_rain_data(date):
conn.close() conn.close()
return time_rain_list, total_rainfall return time_rain_list, total_rainfall
# 정적 파일 서빙: /data/ 경로로 이미지 접근 가능하게 함 # 정적 파일 서빙: /data/ 경로로 이미지 접근 가능하게 함
@app.route('/data/<path:filename>') @app.route('/data/<path:filename>')
def serve_data_file(filename): def serve_data_file(filename):
return send_from_directory('/data', filename) return send_from_directory('/data', filename)
@app.route('/webhook', methods=['POST']) @app.route('/webhook', methods=['POST'])
def webhook(): def webhook():
try: try:
data = request.get_json(silent=True) # 비어있어도 None 반환, 예외 없음 data = request.get_json(silent=True) # 사용자 메시지 참고 가능 (예: data['userRequest']['utterance'])
# 필요 시 data['userRequest']['utterance'] 사용 가능
today = datetime.today().strftime('%Y%m%d') today = datetime.today().strftime('%Y%m%d')
time_rain_list, total_rainfall = get_rain_data(today) time_rain_list, total_rainfall = get_rain_data(today)
# 메시지 생성
if not time_rain_list: if not time_rain_list:
response_text = f"{today} 날짜의 강수량 데이터가 없습니다." response_text = f"{today} 날짜의 강수량 데이터가 없습니다."
else: else:
@ -46,10 +48,10 @@ def webhook():
for time_str, rain in time_rain_list: for time_str, rain in time_rain_list:
rain_display = f"{rain}mm" if rain > 0 else "강수 없음" rain_display = f"{rain}mm" if rain > 0 else "강수 없음"
lines.append(f"{time_str}{rain_display}") lines.append(f"{time_str}{rain_display}")
lines.append(f"\n영업시간 내 총 강수량은 {total_rainfall:.1f}mm 입니다.") lines.append(f"\n영업시간 내 총 강수량은 {total_rainfall:.1f}mm 입니다.")
response_text = '\n'.join(lines) response_text = '\n'.join(lines)
# 이미지 파일 존재 확인
image_filename = f"weather_capture_{today}.png" image_filename = f"weather_capture_{today}.png"
image_path = f"/data/{image_filename}" image_path = f"/data/{image_filename}"
@ -68,6 +70,7 @@ def webhook():
} }
}) })
# 카카오 스킬 응답 JSON 생성
response_body = { response_body = {
"version": "2.0", "version": "2.0",
"template": { "template": {
@ -75,12 +78,13 @@ def webhook():
} }
} }
# JSON 응답 생성 및 Content-Type 명시 (charset=utf-8 포함) # 응답 헤더 명시: 카카오가 요구하는 정확한 Content-Type
resp = make_response(jsonify(response_body)) resp = make_response(jsonify(response_body))
resp.headers['Content-Type'] = 'application/json; charset=utf-8' resp.headers['Content-Type'] = 'application/json; charset=utf-8'
return resp return resp
except Exception as e: except Exception as e:
# 오류 발생 시 기본 메시지 반환
error_body = { error_body = {
"version": "2.0", "version": "2.0",
"template": { "template": {
@ -95,5 +99,6 @@ def webhook():
resp.headers['Content-Type'] = 'application/json; charset=utf-8' resp.headers['Content-Type'] = 'application/json; charset=utf-8'
return resp return resp
if __name__ == '__main__': if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=DEBUG_MODE) app.run(host='0.0.0.0', port=5000, debug=DEBUG_MODE)