Profile picture

[Python] 티스토리 API를 활용하여 글 올려보기

JaehyoJJAng2023년 10월 12일

◾️ 사전 준비

먼저 티스토리 API의 Access Token이 발급 되어있는 상태이어야 한다.

다음 게시글을 참고하여 access token을 발급 받아오자 👉 https://jaehyojjang.dev/etc/tistory-blog-postiong/


예제 스크립트

from src.utilities.config import get_api_key
from datetime import datetime
import requests as rq
import base64

def main() -> None:
    # tistory Access Token
    _ACCESS_TOKEN : str = get_api_key()

    # 블로그 정보
    blog_name : str = "ljh-network" # 블로그 이름
    tags : list[str] = ["tag1","tag2"] # 업로드 할 태그 목록

    # 글과 그림 정보
    post_title  : str = '글 제목 테스트!' # 글 제목
    post_content : str = '글 내용 테스트!' # 글 내용
    image_path   : str = './test.png'  # 업로드 할 그림 파일 경로
    
    # 이미지 파일 읽기 및 base64로 인코딩
    with open(image_path,'rb') as img_file:
        image_data = img_file.read()
        image_b64 = base64.b64encode(image_data).decode('utf-8')

    # API 요청 URL
    url : str = f'https://www.tistory.com/apis/post/write'
    params : dict[str,str] = {
        'access_token': _ACCESS_TOKEN,
        'output': 'json',
        'blogName': blog_name,
        'title': post_title,
        'content': post_content,
        'tag': ','.join(tags),
        'attach': {
            'image': {
                'imageurl': image_path,
                'data': image_b64
            }
        }
    }

    response = rq.post(url,params=params)

    # API 요청 결과 확인
    if response.status_code == 200:
        data = response.json()
        now_time : str = datetime.now().strftime('%Y-%m-%d %H:%M')
        if data['tistory']['status'] == '200':
            print(f'업로드 성공! ({now_time})') 
        else:
            print(f"업로드 실패! ({now_time}) - data['tistory']['error_message']")
    else:
        print(f"API 요청 실패! - {response.text}")

if __name__ == '__main__':
    main()

Loading script...