LoginSignup
2
0

More than 5 years have passed since last update.

Twitter API を使って思い出を振り返る

Posted at

自分は思い出を大切にするタイプで写真を結構とります。
写真はたまに見返さないと意味ないと思っています。なので Twitter に定期的に投稿して、それを見ることで思い出を振り返ります。

Google photo の「X年前の今日」写真をまとめてくれるのがとても良い機能なのですが、負荷抑制のためかたまにしかあの機能が発動しない。あれが毎日発動してくれれば満足なのだが、、、、。
とりあえずただランダムに HDD の写真をツイートします。うちにはラズパイがいるので定期的にツイートさせる。

参考サイト

写真のパスと日付を取得

写真は jpeg しかないので jpeg に絞る。ツイート時に撮影日時もツイートしたいので日付を取得する関数も作る。

getPhoto.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import random
import imghdr
from PIL import Image
from PIL.ExifTags import TAGS

STORAGE_ROOT = "/Volumes/UNTITLED/Pictures"


def get_rand_photo_path():

    path = STORAGE_ROOT

    while True:
        if os.path.isdir(path):
            path += "/" + random.choice(os.listdir(path))
            continue

        if imghdr.what(path) == "jpeg":
            return path
        else:
            print(path + " is not jpeg file.")
            path = STORAGE_ROOT


def _get_exif(img):
    exif = img._getexif()
    try:
        for id, val in exif.items():
            tg = TAGS.get(id, id)
            if tg == "DateTimeOriginal":
                return val
    except AttributeError:
        return "NON"

    return "NON"


def get_photo_day(path):
    img = Image.open(path)
    date = _get_exif(img)
    img.close()
    return date

写真をアップロード

ほとんどPython で画像付きツイート - Qiitaのコードを利用しています。

upload_media.py
#!/usr/bin/env python
# coding: utf-8

import json
from requests_oauthlib import OAuth1Session
from getPhoto import get_rand_photo_path, get_photo_day

CK = 'XXXXXXXXXXXXXx'
CS = 'XXXXXXXXXXXXXx'
AT = 'XXXXXXXXXXXXXx'
AS = 'XXXXXXXXXXXXXx'

url_media = "https://upload.twitter.com/1.1/media/upload.json"
url_text = "https://api.twitter.com/1.1/statuses/update.json"

# OAuth認証 セッションを開始
twitter = OAuth1Session(CK, CS, AT, AS)

# 画像投稿
photo_path = get_rand_photo_path()
files = {"media" : open(photo_path, 'rb')}
req_media = twitter.post(url_media, files=files)

# レスポンスを確認
if req_media.status_code != 200:
    print("画像アップデート失敗: %s", req_media.text)
    exit()

# Media ID を取得
media_id = json.loads(req_media.text)['media_id']
print("Media ID: %d" % media_id)

# Media ID を付加してテキストを投稿
params = {'status': get_photo_day(photo_path), "media_ids": [media_id]}
req_media = twitter.post(url_text, params=params)

# 再びレスポンスを確認
if req_media.status_code != 200:
    print("テキストアップデート失敗: %s", req_media.text)
    exit()

print("OK")

cron でお好きな時に実行

これで思い出用のアカウントをフォローすれば写真を定期的に振り返れます。
意外と簡単ですね。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0