printf("ho_tari\n");

카카오톡으로 일기예보 메세지 보내기 (python) 본문

Raspberry Pi

카카오톡으로 일기예보 메세지 보내기 (python)

호타리 2023. 9. 22. 14:49

<weathersendtokakaotalk.py>

import requests
# requests 라이브러리는 웹페이지에서 데이터를 가져오고 카카오톡 메시지를 전송하기 위해 사용
import re
# re 라이브러리는 정규 표현식을 사용하여 첵스트에서 원하는 패턴을 검색하는 데 사용
import json
# json 라이브러리는 JSON 데이터를 다루기 위해 사용
import time
# time 라이브러리는 프로그램을 일정 시간 동안 일시 중지하기 위해 사용
from bs4 import BeautifulSoup


# beautifulsoup 라이브러리는 HTML 파싱을 위해 사용

def sendToMeMessage(text):  # 주어진 텍스트 메세지를 카카오톡으로 보내는 함수
    header = {"Authorization": "Bearer " + KAKAO_TOKEN}
    # authorization 헤더에는 카카오톡 API 토큰이 포함
    url = "https://kapi.kakao.com/v2/api/talk/memo/default/send"
    post = {
        "object_type": "text",
        "text": text,
        "link": {
            "web_url": "https://developers.kakao.com",
            "mobile_web_url": "https://developers.kakao.com"
        },
        "button_title": "immediately confirm"
    }
    # post 딕셔너리는 메시지의 내용과 링크 정보가 설정
    data = {"template_object": json.dumps(post)}
    # data 딕셔너리는 template_object 키를 사용하여 메시지 데이터 JSON 형식으로 변환
    return requests.post(url, headers=header, data=data)
    # requests.post() 함수를 사용하여 메시지를 카카오톡으로 전송


KAKAO_TOKEN = "카카오톡 토큰"  # 사람마다 토큰 다 다름, 카카오톡 API 토큰 설정


def getWeather():
    url = "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4139054000"
    # 기상청 RSS 데이터를 제공하는 특정 URL을 설정, zone 매개 변수를 통해 특정 지역의 날씨 정보를 가져옴
    response = requests.get(url)
    # response.get() 함수를 사용하여 지정된 URL에 HTTP GET 요청을 보내고 응답을 response 변수에 저장

    time = re.findall(r'<hour>(.+?)</hour>', response.text)
    temp = re.findall(r'<temp>(.+)</temp>', response.text)
    humi = re.findall(r'<reh>(.+?)</reh>', response.text)
    wfKor = re.findall(r'<wfKor>(.+?)</wfKor>', response.text)
    # re.findall() 함수를 사용하여 정규 표현식을 기반으로 XML 형식의 텍스트에서 원하는 데이터를 추출
    # r'<hor>(.+?)</hour> 와 같은 패턴은 <hour> 태그 내의 내용을 추출하는 패턴을 나타냄

    text = " "

    for i in range(8):
        text = text + "(" + str(time[i]) + "시 "
        text = text + str(temp[i]) + "C "
        text = text + str(humi[i]) + "% "
        text = text + str(wfKor[i]) + ")"

        # for 루프를 사용하여 시간당 날씨 정보를 포맷팅하여 하나의 문자열인 text에 저장,
        # # 이 문자열에는 시간, 온도, 습도 및 날씨 상태가 나열

        return text


try:
    while True:
        # 무한 루프를 사용하여 현재 날짜와 시간을 가져옴
        now = datetime.datetime.now()
        hms = now.strftime('%H:%M:%S')
        # strftime 함수를 사용하여 현재 시간을 "시:분:초" 형식의 문자열로 변환
        print(hms)
        if hms == "14:48:05":
            text = getWeather()
            # 만약 현재 시간이 "14:48:05"인 경우(원하는 시간 설정) getWeather 함수를 호출하여 날씨 정보를 가져오고 이 정보 출력
            print(sendToMeMessage(text).text)
        time.sleep(1.0)

except KeyboardInterrupt:
    pass

<compile 결과>