본문 바로가기

issue

블로그자동수익 티스토리 API와 python으로 블로그 글쓰기

서론

티스토리 블로그를 운영하고 있다면 글을 작성하고 관리하는 작업은 필수적입니다. 티스토리 API를 활용하면 이러한 작업을 코드로 작성하여 편리하게 처리할 수가 있습니다. 이번 포스팅에서는 티스토리 Open API와 python을 사용하여 글을 읽고 쓰는 방법을 단계별로 알아보겠습니다. 최근 글쓰기 과정을 자동화 하는 등 방식으로 티스토리 API 활용을 시도하는 분들이 많은데, 이를 위해 필요한 기본적인 내용이라고 할 수 있을 것 같습니다.

사용 기술

이 글은 티스토리의 Open API와 python을 활용하여 글을 읽고 쓰는 방법을 다룹니다. python 및 http리퀘스트에 대한 이해가 필요할 수 있습니다. 이 글에서는 python의 request 라이브러리를 사용하지만 다른 언어 및 라이브러리로도 동일한 방식으로 API를 사용할 수 있습니다.

전체 과정

전체 과정을 요약하면 다음과 같습니다.

  1. Open API 사용 신청(Tistory API 신청)
  2. Access Token 받기
  3. 글 읽기
  4. 글 쓰기
  5. 파일 첨부하기
  6. 전체 과정 자동화 코드
 

1. API 사용 신청

먼저, 티스토리 API를 사용하기 위해 API 키를 발급받아야 합니다. API 키는 앱 키(Client ID)와 시크릿 키(Client Secret)로 구성됩니다. 다음은 API 키를 발급하는 과정입니다.

  1. 티스토리 API 신청 페이지로 이동합니다.
  2. 가입하고 로그인한 후, 신청서를 작성합니다.
  3. 앱 키(Client ID)와 시크릿 키(Client Secret)를 발급받습니다.

2. Access Token 받기

API 키를 발급받았다면, 이제 Access Token을 받아야 합니다. Access Token은 API를 사용하기 위한 인증 수단입니다. 아래는 Access Token을 받는 과정입니다.

코드 실행시, 인증 페이지에서 티스토리 로그인 및 인증을 마치면 redirect_uri로 지정한 페이지로 이동하게 됩니다. 이때 주소에서 http://client.redirect.uri?code=xxxxx 처럼 되어있는 부분에서 code를 확인할 수 있습니다. 다음에 나오는 입력 프롬프트에서 해당 code를 입력해주면 됩니다.

(주의: code는 한 번 사용하거나 1시간이 지나면 만료되기 때문에, 만료된 경우 인증을 처음부터 다시 수행해야 합니다.)

셀레늄을 사용해서 이런 과정을 자동화하거나, redirect되는 페이지에서 code값을 가져와 사용하도록 프로그램을 만들면 더욱 유용하겠지만 이번 글에서는 생략하겠습니다.

python
import requests

# API 키와 리디렉션 URI 설정
client_id = 'YOUR_CLIENT_ID' # 발급받은 App key
client_secret = 'YOUR_CLIENT_SECRET' # 발급받은 Secret key
redirect_uri = 'http://client.redirect.uri' # API 신청시에 기입한 리디렉션 URI
state = 'SOME_VALUE'

# 인증 페이지 URL 생성
auth_url = f'https://www.tistory.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code&state={state}'

# 인증 페이지로 리디렉션
print('다음 URL로 이동하여 인증을 완료하세요:')
print(auth_url)

# 리디렉션된 URL에서 code 받기
code = input('code를 입력하세요: ')

# Access Token 요청
token_url = 'https://www.tistory.com/oauth/access_token'
params = {
    'client_id': client_id,
    'client_secret': client_secret,
    'redirect_uri': redirect_uri,
    'code': code,
    'grant_type': 'authorization_code'
}

response = requests.get(token_url, params=params)
access_token = response.json()['access_token']

print(f'Access Token: {access_token}')

3. 글 읽기

이제 위에서 발급받은 Access Token을 활용하면 API를 사용하여 티스토리 블로그의 글을 읽어올 수 있습니다. 아래는 글 목록을 읽고 특정 포스팅을 읽는 파이썬 코드입니다.

https://www.tistory.com/apis/post/read 엔드포인트를 사용합니다. 코드를 실행하면 특정 포스팅을 JSON 형식으로 받아옵니다.

python
import requests

# API 엔드포인트 설정
read_endpoint = 'https://www.tistory.com/apis/post/read'

# 요청 매개변수 설정
access_token = 'YOUR_ACCESS_TOKEN' # 2에서 받은 access_token
output_type = 'json'
blog_name = 'blog_name' # xxxx.tistory.com에서 "xxxx" 부분
page_number = 1

# 특정 포스팅 읽기 요청
post_id = '123'  # xxxx.tistory.com/123 에서 "123" 부분

read_params = {
    'access_token': access_token,
    'blogName': blog_name,
    'postId': post_id
}

response = requests.get(read_endpoint, params=read_params)
post = response.json()

print(post)
  • YOUR_ACCESS_TOKEN은 2에서 받은 access_token을 넣어주면 됩니다.
  • YOUR_CLIENT_ID와 YOUR_CLIENT_SECRET에는 API 신청시 받은 앱 키와 시크릿 키를 입력해야 합니다.
  • blog_name은 "xxxx.tistory.com"에서 "xxxx" 부분을 나타냅니다.
  • post_id는 읽고 싶은 포스팅의 ID로 설정합니다.

4. 글 쓰기

이제는 API를 사용하여 티스토리 블로그에 글을 작성해보겠습니다. https://www.tistory.com/apis/post/write 엔드포인트를 사용합니다.

아래 코드를 실행하면 새로운 글이 작성되고, 작성된 글의 ID가 출력됩니다.

참고

  • YOUR_ACCESS_TOKEN에는 Access Token을 입력해야 합니다.
  • blog_name은 "xxxx.tistory.com"에서 "xxxx" 부분을 나타냅니다.
  • title, content, visibility, category_id, published, slogan, tag, accept_comment, password는 글을 작성할 때 필요한 정보입니다.
python
import requests

# API 엔드포인트 설정
endpoint = 'https://www.tistory.com/apis/post/write'

# 요청 매개변수 설정
access_token = 'YOUR_ACCESS_TOKEN' # 2에서 받은 access_token
output_type = 'json'
blog_name = 'blog_name'  # xxxx.tistory.com에서 "xxxx" 부분
title = '새로운 글 제목'
content = '새로운 글 본문'
visibility = 0  # 0: 비공개, 1: 보호, 2: 발행
category_id = 0  # 카테고리 ID
published = 'false'  # 공개 예약 여부
slogan = '글 슬로건'
tag = 'tag1,tag2,tag3' # 태그 (선택 사항)
accept_comment = 1  # 댓글 허용 여부
password = '1234'  # 글 비밀번호 (선택 사항)

# 글 작성 요청
params = {
    'access_token': access_token,
    'output': output_type,
    'blogName': blog_name,
    'title': title,
    'content': content,
    'visibility': visibility,
    'category': category_id,
    'published': published,
    'slogan': slogan,
    'tag': tag,
    'acceptComment': accept_comment,
    'password': password
}

response = requests.post(endpoint, params=params)
post_id = response.json()['postId']

print(f'글 작성 완료! 글 ID: {post_id}')

5. 파일 첨부

티스토리 API를 사용해서 파일을 첨부할 수도 있습니다. 파일 첨부를 위해서는 apis/post/attach 엔드포인트를 사용합니다. 아래는 파일을 첨부하는 파이썬 코드입니다. path/to/file.jpg 부분을 첨부할 파일의 경로와 이름으로 바꾸어 주어야 합니다.

python
import requests

# API 엔드포인트 설정
attach_endpoint = 'https://www.tistory.com/apis/post/attach'

# 요청 매개변수 설정
access_token = 'YOUR_ACCESS_TOKEN'


blog_name = 'blog_name'  # xxxx.tistory.com에서 "xxxx" 부분

# 파일 첨부 요청
attachment_params = {
    'access_token': access_token,
    'blogName': blog_name
}

files = {'uploadedfile': open('path/to/file.jpg', 'rb')}  # 첨부할 파일의 경로와 이름

response = requests.post(attach_endpoint, params=attachment_params, files=files)
attachment_info = response.json()

print(f'파일 첨부 완료! 첨부 파일 URL: {attachment_info["tistory"]["url"]}')

코드를 실행하면 파일이 첨부되고, 첨부 파일의 URL이 출력됩니다.

6. 종합: 글쓰기 자동화

이번에는 위에서 알아본 전체 과정을 종합하여, 하나의 스크립트로 티스토리에 글을 쓰는 과정을 자동화하는 python 코드를 작성해보겠습니다.

사용자의 PC에서 특정 폴더를 스캔하여 이미지 파일이 있는 경우에 파일을 첨부하고, 해당 폴더 내의 txt 파일로부터 글을 업로드하는 방식으로 코드를 작성해 보았습니다.

python
import os
import requests

# 로그인 및 인증
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
redirect_uri = 'http://client.redirect.uri'
state = 'SOME_VALUE'

auth_url = f'https://www.tistory.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code&state={state}'

print('다음 URL로 이동하여 로그인 및 인증을 완료하세요:')
print(auth_url)

code = input('인가 코드를 입력하세요: ')

token_url = 'https://www.tistory.com/oauth/access_token'
token_params = {
    'client_id': client_id,
    'client_secret': client_secret,
    'redirect_uri': redirect_uri,
    'code': code,
    'grant_type': 'authorization_code'
}

response = requests.get(token_url, params=token_params)
access_token = response.json()['access_token']

print(f'인증 완료! Access Token: {access_token}')

# 특정 폴더 스캔 및 파일 첨부
folder_path = 'path/to/folder'  # 스캔할 폴더 경로
blog_name = 'blog_name'  # xxxx.tistory.com에서 "xxxx" 부분

attach_endpoint = 'https://www.tistory.com/apis/post/attach'

# 파일 첨부 함수
def attach_file(file_path):
    attachment_params = {
        'access_token': access_token,
        'blogName': blog_name
    }

    files = {'uploadedfile': open(file_path, 'rb')}  # 첨부할 파일의 경로와 이름

    response = requests.post(attach_endpoint, params=attachment_params, files=files)
    attachment_info = response.json()

    return attachment_info['tistory']['url']

# 폴더 스캔 및 파일 첨부
for file_name in os.listdir(folder_path):
    file_path = os.path.join(folder_path, file_name)
    if os.path.isfile(file_path) and file_name.lower().endswith(('.jpg', '.jpeg', '.png')):
        attached_file_url = attach_file(file_path)
        print(f'{file_name} 파일 첨부 완료! 파일 URL: {attached_file_url}')

# 글 입력
write_endpoint = 'https://www.tistory.com/apis/post/write'

title = '새로운 글 제목'
content = ''  # 글 내용 초기화

# txt 파일로부터 글 내용 읽어오기
txt_file_path = 'path/to/content.txt'  # 글 내용을 담고 있는 txt 파일의 경로
with open(txt_file_path, 'r', encoding='utf-8') as file:
    content = file.read()

# 글 작성 요청
write_params = {
    'access_token': access_token,
    'output': 'json',
    'blogName': blog_name,
    'title': title,
    'content': content,
    'visibility': 2,  # 발행
    'category': 0,  # 카테고리 ID
    'published': 'true',
    'slogan': '',
    'tag': '',
    'acceptComment': 1,
    'password': ''
}

write_response = requests.post(write_endpoint, params=write_params)
post_id = write_response.json()['postId']

print(f'글 작성 완료! 글 ID: {post_id}')

마무리

티스토리 API를 사용하여 글을 쓰고 파일을 첨부하는 방법을 알아보았습니다. 이번 포스팅에서는 글을 읽고 쓰는 기본적인 방법을 알아보았지만, 티스토리 API에는 더 많은 기능들이 제공됩니다. 예를 들어, 글 수정, 댓글 작성 및 수정, 파일 첨부 등 다양한 기능을 활용할 수 있습니다. 티스토리 API 공식 가이드 사이트(링크)를 방문하여 더 많은 기능과 활용 방법을 찾아보세요. API를 잘 활용하면 티스토리 블로그 운영을 보다 효율적으로 처리할 수 있습니다.