|
# coding: utf-8 |
|
|
|
import requests |
|
import time |
|
from urlparse import parse_qsl |
|
from bs4 import BeautifulSoup |
|
|
|
class KakaostoryAPI(object): |
|
def __init__(self, raw_cookie): |
|
self.session = requests.Session() |
|
self.cookies = dict(parse_qsl(cookie)) |
|
self.headers = { |
|
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Gecko/20100101 Firefox/37.0', |
|
'Accept': 'application/json', |
|
'Accept-Language': 'ko', |
|
'Accept-Encoding': 'gzip, deflate', |
|
'X-Kakao-ApiLevel': 19, |
|
'X-Kakao-DeviceInfo': 'web:-;-;-', |
|
'X-Requested-With': 'XMLHttpRequest', |
|
'Referer': 'https://story.kakao.com/', |
|
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' |
|
} |
|
|
|
def feeds(self, since=None): |
|
url = 'https://story.kakao.com/a/feeds?_={}'.format(self._get_timestamp()) |
|
params = {} |
|
if since: |
|
params['since'] = since |
|
response = self._get(url, params=params) |
|
if response.status_code == 200: |
|
return response.json() |
|
|
|
def add_comment(self, sid, text): |
|
url = 'https://story.kakao.com/a/activities/{}/comments?_={}'.format(sid, self._get_timestamp()) |
|
params = { |
|
'text': text, |
|
'decorators': json.dumps([{'type': 'text', 'text': text}]) |
|
} |
|
response = self._post(url, params=params) |
|
if response.status_code == 200: |
|
return True |
|
else: |
|
return False |
|
|
|
def _get(self, url, **kwargs): |
|
return self.session.get(url, headers=self.headers, cookies=self.cookies, **kwargs) |
|
|
|
def _post(self, url, **kwargs): |
|
return self.session.post(url, headers=self.headers, cookies=self.cookies, **kwargs) |
|
|
|
@staticmethod |
|
def _get_timestamp(): |
|
return '{:.5f}'.format(time.time()).replace('.', '') |
|
|
|
def get_naver_keyword_rank(): |
|
response = requests.get('http://www.naver.com/', headers={'Accept-Encoding': 'gzip, deflate'}) |
|
soup = BeautifulSoup(response.text) |
|
|
|
result = [] |
|
for index, item in enumerate(soup.find('dl', id='ranklist').find_all('li')[:-1]): |
|
result.append('{:2}위 {}'.format(index + 1, item.a['title'].encode('utf-8'))) |
|
|
|
return result |
|
|
|
cookie = 'Your cookie here...' # You must edit this line! |
|
kakaostory = KakaostoryAPI(cookie) |
|
visited = {} |
|
while True: |
|
print 'loading feeds...' |
|
feeds = kakaostory.feeds() |
|
for feed in feeds['feeds']: |
|
if 'sid' in feed and feed['sid'] not in visited: |
|
if u'!네이버실시간검색어' in feed['content']: |
|
print 'adding comment on {}...'.format(feed['sid']), |
|
if kakaostory.add_comment(feed['sid'], '\n'.join(get_naver_keyword_rank())): |
|
print 'success' |
|
else: |
|
print 'failed' |
|
visited[feed['sid']] = True |
|
time.sleep(5) |