블로그 새 글 수집.py

import feedparser
import time
from notion_client import Client

# Notion API 설정
notion = Client(auth="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")
database_id = "1362840db3088040beb0db2681f4ed3e"

# RSS 피드 URL
rss_url = "<https://rss.blog.naver.com/moeblog.xml>"

def fetch_and_update():
    feed = feedparser.parse(rss_url)
    
    for entry in feed.entries:
        try:
            # 이미 존재하는 글인지 확인
            query = notion.databases.query(
                **{
                    "database_id": database_id,
                    "filter": {
                        "property": "URL",
                        "url": {
                            "equals": entry.link
                        }
                    }
                }
            )
            
            if not query['results']:
                # 날짜 문자열 조작을 통해 ISO 8601 형식으로 변환
                try:
                    # 'Tue, 07 Nov 2023 08:00:00 +0900' 형식의 문자열 처리
                    published = entry.published[5:]  # 요일 제거 ('Tue, ' 부분)
                    parts = published.strip().split()
                    day = parts[0]
                    month_str = parts[1]
                    year = parts[2]
                    time_str = parts[3]
                    tzoffset = parts[4]

                    # 월 문자열을 숫자로 변환
                    month_map = {
                        'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04',
                        'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08',
                        'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'
                    }
                    month = month_map.get(month_str, '01')  # 기본값 '01'

                    # 시간대 오프셋에 콜론 추가 (+0900 -> +09:00)
                    tzoffset_formatted = tzoffset[:3] + ':' + tzoffset[3:]

                    # ISO 8601 형식의 날짜 문자열 생성
                    published_date = f"{year}-{month}-{day}T{time_str}{tzoffset_formatted}"
                except Exception as e:
                    print(f"Date parsing error for entry '{entry.title}': {e}")
                    published_date = None  # 또는 기본값 설정

                # 속성 설정
                properties = {
                    "제목": {"title": [{"text": {"content": entry.title}}]},
                    "URL": {"url": entry.link},
                }

                if published_date:
                    properties["작성일"] = {"date": {"start": published_date}}
                
                # 새 글이면 데이터베이스에 추가
                notion.pages.create(
                    parent={"database_id": database_id},
                    properties=properties
                )
                print(f"Added: {entry.title}")
        except Exception as e:
            print(f"An error occurred while processing entry '{entry.title}': {e}")

while True:
    fetch_and_update()
    time.sleep(600)  # 10분 대기

이 코드는 지정된 RSS 피드에서 새 글을 가져와 Notion 데이터베이스에 추가합니다. 주요 기능은 다음과 같습니다:

사용하기 전에 다음 사항을 설정해야 합니다:

  1. 필요한 라이브러리 설치: pip install feedparser notion-client
  2. Notion API 토큰을 환경 변수로 설정: export NOTION_TOKEN='your_secret_token'
  3. database_id를 실제 Notion 데이터베이스 ID로 변경
  4. rss_url을 실제 RSS 피드 URL로 변경

이 스크립트는 RSS 피드에서 새 글을 가져와 Notion 데이터베이스에 추가합니다.