2026/02/21

오늘의 이야기

오호라... 피트에 있는 글들에 글을 달기 시작했더니, 방문해 주시고 댓글도 달아주시고... 감사 감사...


이런 걸 말로만 해서는 안되고 댓글에 또한 댓글로 인사를 해야 할 것 같아서 티스토리 API을 찾아 찾아서 댓글에 또한 댓글을 달아보자...


 


#coding=utf-8
#
import json
import sqlite3
import time
from datetime import datetime
import requests
import TELEGRAM_BOT as bot

conn = sqlite3.connect("test.sqlite", isolation_level=None)
rs = conn.cursor()
rs.execute("CREATE TABLE IF NOT EXISTS feedRecomment \
(id integer PRIMARY KEY, tid text, date text, postId text, name text, homepage text, comment text, open text, link text)")

#blog_name = "autoposting"
blog_name="billcorea"
client_id = "cf6.......................753a"
seckey = "cf6e................................1c5c0efb7"
callback_url = "http://billcorea.tistory.com"
getUrl = 'https://www.tistory.com/oauth/authorize?client_id={0}&redirect_uri={1}&response_type=code&state=someValue'
getUrl = getUrl.format(client_id, callback_url)
res = requests.get(getUrl)
# 아래 code 을 받기 위해서 getUrl 을 표시해서 IE 등으로 접속을 해야지 code 에 들어갈 값을 받는다.
# print("code=" +getUrl)
# input('... Enter')

# 등록시 입력
# 그때 마다 token 을 변경하면 다시 받아야 함.
def getToken():
code = "3955............................6377"
token_url="https://www.tistory.com/oauth/access_token?client_id={0}&client_secret={1}&redirect_uri={2}&code={3}&grant_type=authorization_code".format(client_id, seckey, callback_url, code)
res = requests.get(token_url)
access_token = res.text.split("=")[1]
print(':' + access_token)

# getToken()
# input('... Enter')


accessToken = 'cef406................................................f45333'
output_type='json'


def reComment(post_id, parentId):
days = ['월요일', '화요일', '수요일', '목요일', '금요일', '토요일', '일요일']
dayOfWeek = datetime.today().weekday()
hour = datetime.today().strftime("%H")
sMesg = "하루"
if int(hour) > 12:
sMesg = "오후"
if int(hour) > 17:
sMesg = "저녁"
if int(hour) > 20:
sMesg = "밤"
content = '행복한 {0} 평온한 {1} 되세요. \n오늘도 방문해 주셔서 감사합니다. \n댓글 달아 주셔서 감사합니다. \n항상 좋은 일만 있으시길 바랄께요. '.format(days[dayOfWeek], sMesg)
secret = '0'
writeUrl = 'https://www.tistory.com/apis/comment/write?access_token={0}&output={1}&blogName={2}&postId={3}&parentId={4}&content={5}&secret={6}'.format(accessToken, output_type, blog_name, post_id, parentId, content, secret)
res = requests.post(writeUrl)
jsonR = json.loads(res.text)
print(jsonR['tistory']['status'])
return jsonR['tistory']['status']


for iPage in range(1, 11):
print(str(iPage))
newEstUrl = 'https://www.tistory.com/apis/comment/newest?access_token={0}&output=json&blogName={1}&page={2}&count=10'.format(accessToken, blog_name, iPage)
print(newEstUrl)
res = requests.get(newEstUrl)
jsonRs = json.loads(res.text)

for comment in jsonRs['tistory']['item']['comments']:
name = comment['name']
name = name.encode('utf-8').decode('iso-8859-1')
print(name)
try:
if 'Billcorea' != name:
print('[' + str(1) + '] postId=' + comment['postId'] + ' id=' + comment['id'] + ' name=' + name + ' data=' +
comment['date'])
rs.execute(''' select count(*) from feedRecomment
where tid = "{0}" and postId = {1} '''.format(comment['id'], comment['postId']))
if rs.fetchone()[0] == 1:
print(comment['postId'] + ' is exists')
else:
resCode = reComment(comment['postId'], comment['id'])
bot.sendMessage('write...post=' + comment['postId'] + ' name=' + name + ', resCode=' + resCode)
if resCode == '200':
rs.execute(''' insert into feedRecomment (tid, postId, date, name, homepage, comment, open, link)
values ("{0}", "{1}", "{2}", "{3}", "{4}", "{5}", "{6}", "{7}")
'''.format(comment['id'], comment['postId'], comment['date'], name,
comment['homepage'], comment['comment'].replace('"', ''), comment['open'],
comment['link']))
print('insert Data ...')
except Exception as e:
print('...', e)
bot.sendMessage('error message=' + e)

time.sleep(10)

bot.sendMessage("tistory recomment Job END.")
print('end Job')

여기서 주의가 필요한 것은 reComment(post_id, parentId) 함수를 호출하는 부분일 것 같다.


잠시 잠깐 착각을 하면 내 글에만 댓글을 내가 다는 꼴이 된다. writeUrl의 파라미터 에는 내 글의 postId와 댓글번호인 parentId을 전달해야 하니 정신 차리고 잘 전달을 해 주어야 소중한 댓글에 답글을 다는 함수처리가 완성된다.


p.s 이 스크립트도 반복적으로 실행하다 보면 동일한 댓글에 답급을 달까 싶어서 답급을 달은 댓글의 정보를 기록해 두었다. 그래야 같은 댓글에 답급을 반복해서 다는 불편한 일이 생기지 않을 테니 말이다.


그럼... 이 스크립트를 이용해서 할 수 있는 것이 하나 더 생길 것 같은 느낌적인 느낌은 뭘까? 


그건 다음에...





댓글 없음:

댓글 쓰기

오늘의 이야기

제주도를 가고 싶었는데, 아직인 데... 제주도에 가면 어떤 맛집이 있는 지 궁금하기도 하고 해서  많은 블로거 들이 작성한 글을 찾아서 제주 맛집을 찾아 보려고 한다. import requests from bs4 import BeautifulSoup...