본문 바로가기
프로그래밍/PYTHON

[파이썬] PYTHON 을 활용한 티스토리 자동 포스팅 (다른 API 연동_자동 이미지넣기)(3/3)

by 루티즈 2023. 6. 16.
반응형

API를 사용하여 필요한 내용을 가지고 오는 방법은 다양할 수 있으며, 구체적인 API 엔드포인트나 요청 방식은 API 제공자에 따라 다를 수 있습니다. 아래 예시는 간단한 형태의 API를 사용하는 방법을 보여줍니다. 

 

import requests

QUOTE_API_URL = "https://api.adviceslip.com/advice"
IMAGE_API_URL = "https://picsum.photos/200/300"

# Quote API를 호출하여 명언을 가져오는 함수
def get_quote():
    response = requests.get(QUOTE_API_URL)

    if response.status_code == 200:
        data = response.json()
        quote = data['slip']['advice']
        return quote
    else:
        print("API 요청 실패:", response.status_code)

# Quote API를 호출하여 명언을 가져오는 함수
def get_image():
    response = requests.get(IMAGE_API_URL)

    if response.status_code == 200:
        url = response.url
        return url
    else:
        print("API 요청 실패:", response.status_code)


# 메인 함수
def main():
    quote = get_quote()
    print("명언:", quote)

    imge = get_image()


if __name__ == "__main__":
    main()

 

이 코드에서는 명언을 제공해주는 API를 사용하여 랜덤 명언을 가지고 오고 랜덤 이미지를 가지고 오는 API 를 사용하여 랜덤 이미지(URL)를 가지고 온다. 

 

이 샘플 코드를 사용하여 이전 글과 합치면 다음과 같은 형태로 만들 수 있다.

 

import requests
from datetime import datetime

# API 키
API_KEY = ""

# 블로그 정보
BLOG_NAME = "https://rootiel.tistory.com/"
CATEGORY_ID = "728894"  # 업로드할 카테고리 ID
TAGS = ["오늘의 명언", "명언", "좋은말", "실시간", "자동글작성"]  # 업로드할 태그 목록

QUOTE_API_URL = "https://api.adviceslip.com/advice"
IMAGE_API_URL = "https://picsum.photos/200/300"

# API 요청 URL
upload_url = "https://www.tistory.com/apis/post/attach"
write_url = "https://www.tistory.com/apis/post/write"


# 이미지 파일 업로드 함수
def upload_image(image_url):
    image_file = requests.get(image_url).content
    image_data = {"uploadedfile": image_file}
    response = requests.post(upload_url, params={"access_token": API_KEY, "output": "json","blogName": BLOG_NAME}, files=image_data)

    # API 요청 결과 확인
    if response.status_code == 200:
        data = response.json()
        if data["tistory"]["status"] == "200":
            image_url = data["tistory"]["url"]
            return image_url
        else:
            print("이미지 업로드 실패:", data["tistory"]["error_message"])
    else:
        print("API 요청 실패:", response.status_code)


# 명언 가져오기 함수
def get_quote():
    response = requests.get(QUOTE_API_URL)

    # API 요청 결과 확인
    if response.status_code == 200:
        data = response.json()
        quote = data['slip']['advice']
        return quote
    else:
        print("API 요청 실패:", response.status_code)

# Quote API를 호출하여 명언을 가져오는 함수
def get_image():
    response = requests.get(IMAGE_API_URL)

    if response.status_code == 200:
        url = response.url
        return url
    else:
        print("API 요청 실패:", response.status_code)


# 글 작성 및 업로드 함수
def post_to_tistory(quote, url):
    # 이미지 파일 업로드
    image_url = upload_image(url)
    
    # 글 내용
    post_title = str(datetime.today()) + "::오늘의 명언"
    post_content = f"""
    <p>{quote}</p>
    <p><img src="{image_url}" alt="명언 이미지"></p>
    """

    # 글 업로드
    params = {
        "access_token": API_KEY,
        "output": "json",
        "blogName": BLOG_NAME,
        "title": post_title,
        "content": post_content,
        "category": CATEGORY_ID,
        "tag": ",".join(TAGS),
    }
    response = requests.post(write_url, params=params)

    # API 요청 결과 확인
    if response.status_code == 200:
        data = response.json()
        if data["tistory"]["status"] == "200":
            print("글 업로드 성공!")
        else:
            print("글 업로드 실패:", data["tistory"]["error_message"])
    else:
        print("API 요청 실패:", response.status_code)


# 메인 함수
def main():
    quote = get_quote()
    image_url = get_image()
    post_to_tistory(quote, image_url)


if __name__ == "__main__":
    main()

그림을 랜덤으로 제공 받을 수 있는 API 에서 그림을 한 장 랜덤으로 제공 받고

명언을 랜덤으로 제공 받을 수 있는 API를 사용하여 명언을 아무거나 랜덤으로 제공 받은 후

제목을 오늘 날짜 오늘의 명언으로 글을 올림.

 

PYTHON 코드를 사용하여 실제 티스토리에 올라온 글.

2023.06.16 - [기타/블로그] - 2023-06-16 01:07:08.986037::오늘의 명언

 

 

[이전글]

2023.06.15 - [프로그래밍/PYTHON] - [파이썬] PYTHON 을 활용한 티스토리 자동 포스팅 (파이썬으로 글올리기)(2/3)

 

반응형