walkingmask’s development log

IT系の情報などを適当に書いていきます

MENU

Python, requests-oauthlib で Twitter の自分のタイムラインの人気ツイートを Retweet

泣き言

post と get を間違えて結構時間つぶした😿

インストール

mkdir retweepy && cd $_
pyenv virtualenv 3.5.4 retweepy
pyenv local retweepy
pip install requests_oauthlib

サンプルコード

import json
from requests_oauthlib import OAuth1Session

CONSUMER_KEY=""
CONSUMER_SECRET=""
ACCESS_TOKEN=""
ACCESS_TOKEN_SECRET=""

HOME_TIMELINE = "https://api.twitter.com/1.1/statuses/home_timeline.json"
RETWEET="https://api.twitter.com/1.1/statuses/retweet/"

api = OAuth1Session(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

respons = api.get(HOME_TIMELINE, params={'count': 200})

timeline = json.loads(respons.text)
for tweet in timeline:
    if tweet['retweeted']:
        continue
    if tweet['retweet_count'] > 10 or tweet['favorite_count'] > 10:
        tweet_id = tweet['id_str']
        respons = api.post(RETWEET+tweet_id+'.json')

まとめ

retweet のサンプルは見かけなかったので書きました。