Posted at

#Twitter #API でタイムラインから最新5件を取得して、はてなブックマークを一斉追加する #python スクリプトの例。 #sh


Twitter #API でタイムラインから最新5件を取得して、はてなブックマークを一斉追加する #python スクリプトの例。 #sh


準備

Twitter API Key とか取得しておく

はてな API key とか取得しておく

適当にググってみて!

yuma inaura はてな api - Google Search

yumainaura twitter api - Google Search

それぞれトークンとか config.py に置いておく


twitter/timeline-url.py

日付処理とか余計なものも入ってるので、適度に無視して読んでもらえれば

# https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline.html


import json, config, os, re
from requests_oauthlib import OAuth1Session
import time
import datetime
from datetime import timedelta

CK = config.CONSUMER_KEY
CS = config.CONSUMER_SECRET
AT = config.ACCESS_TOKEN
ATS = config.ACCESS_TOKEN_SECRET
twitter = OAuth1Session(CK, CS, AT, ATS)

url = "https://api.twitter.com/1.1/statuses/user_timeline.json"

params ={
'count' : os.environ.get('COUNT') or 1000,
'trim_user' : True,
'exclude_replies' : True,
'tweet_mode' : 'extended'

}
res = twitter.get(url, params = params)

if res.status_code != 200:
print("Failed: %d" % res.status_code)
exit()

def convert_datetime(datetime_str):
tweet_time = time.strptime(datetime_str,'%a %b %d %H:%M:%S +0000 %Y')

tweet_datetime = datetime.datetime(*tweet_time[:6])
return(tweet_datetime)

def in_jst_yesterday(tweet_datetime):
# Only before JST 9 am it works
today_beggining_of_day = \
datetime.datetime.utcnow() \
.replace(hour=15, minute=0, second=0, microsecond=0) \

if os.environ.get('OVERTIME'):
today_beggining_of_day -= timedelta(days=1)

yesterday_beggining_of_day = \
today_beggining_of_day \
- timedelta(days=1)

if today_beggining_of_day > tweet_datetime >= yesterday_beggining_of_day:
return True

timelines = json.loads(res.text)

results = []

for line in timelines:
tweet_datetime = convert_datetime(line['created_at'])

if not in_jst_yesterday(tweet_datetime):
continue
if line['full_text'].find('RT') >= 0:
continue

results.append('https://twitter.com/YumaInaura/status/' + str(line['id']))

results.reverse()

for result in results:
print(result)


hatena/bookmark.py

import requests, sys, config, os

from requests_oauthlib import OAuth1

CK = config.CONSUMER_KEY
CS = config.CONSUMER_SECRET
AT = config.ACCESS_TOKEN
ATS = config.ACCESS_TOKEN_SECRET

auth = OAuth1(
CK,
CS,
AT,
ATS
)

bookmark_api_url = "http://api.b.hatena.ne.jp/1/my/bookmark"

def post(bookmark_url):
print(requests.post(bookmark_api_url + "?url=" + bookmark_url, auth=auth).content)

def delete(bookmark_url):
print(requests.delete(bookmark_api_url + "?url=" + bookmark_url, auth=auth).content)

if __name__ == "__main__":
stdin = str(sys.stdin.read())
urls = stdin.split()

for bookmark_url in urls:
if os.environ.get('DELETE'):
delete(bookmark_url)
else:
post(bookmark_url)


Run Example

Yumas-MacBook-Air:YumaInaura yumainaura$ python twitter/timeline-url.py | head -n 5 | python hatena/bookmark.py

b'{"comment":"","permalink":"http://b.hatena.ne.jp/yumainaura/20190216#bookmark-4664682265995545601","created_datetime":"2019-02-16T21:21:43+09:00","eid":"4664682265995545601","private":false,"created_epoch":1550319703,"user":"yumainaura","comment_raw":"","tags":[]}'
b'{"tags":[],"user":"yumainaura","comment_raw":"","private":false,"eid":"4664682266532416673","created_epoch":1550319703,"created_datetime":"2019-02-16T21:21:43+09:00","comment":"","permalink":"http://b.hatena.ne.jp/yumainaura/20190216#bookmark-4664682266532416673"}'
b'{"comment_raw":"","created_epoch":1550319704,"eid":"4664682267069287649","created_datetime":"2019-02-16T21:21:44+09:00","comment":"","tags":[],"private":false,"permalink":"http://b.hatena.ne.jp/yumainaura/20190216#bookmark-4664682267069287649","user":"yumainaura"}'
b'{"eid":"4664682267606158689","created_datetime":"2019-02-16T21:21:44+09:00","comment_raw":"","user":"yumainaura","tags":[],"permalink":"http://b.hatena.ne.jp/yumainaura/20190216#bookmark-4664682267606158689","private":false,"created_epoch":1550319704,"comment":""}'
b'{"created_epoch":1550319705,"comment_raw":"","eid":"4664682268143029665","created_datetime":"2019-02-16T21:21:45+09:00","tags":[],"comment":"","permalink":"http://b.hatena.ne.jp/yumainaura/20190216#bookmark-4664682268143029665","private":false,"user":"yumainaura"}'


Result Example


Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/599