LoginSignup
5
8

More than 5 years have passed since last update.

pythonでツイッターの画像を複数投稿

Posted at

1. はじめに

画像の複数投稿をしたかったのですがちょっとはまったところがあったので投稿します。
python 3系列で動かすことを想定しています

2. 画像の投稿とその引数

1枚の画像の投稿はほかにも記事が多く、簡単に実装ができます。
参考: Python で画像付きツイート
こちらに記述されているソースコードを流用しましょう。

3. 複数枚投稿

複数枚投稿にはmedia/uploadをその分使います。

(media/upload -> media_idの取得) * 枚数 -> statuses/update

media_idですが複数枚投稿にはカンマ区切りの文字列を挿入しましょう。
上記のソースコードをお借りして次のように書き換えました。

media.py

def tweet_with_image(oauth_sess, tweet_text, path_list_images):

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

    media_ids = ""

    # 画像の枚数分ループ
    for path in path_list_images:
        files = {"media" : open(path, 'rb')}
        req_media = oauth_sess.post(url_media, files = files)

        # レスポンスを確認
        if req_media.status_code != 200:
            print ("画像アップデート失敗: {}".format(req_media.text))
            return -1

        media_id = json.loads(req_media.text)['media_id']
        media_id_string = json.loads(req_media.text)['media_id_string']
        print ("Media ID: {} ".format(media_id))
        # メディアIDの文字列をカンマ","で結合
        if media_ids == "":
            media_ids += media_id_string
        else:
            media_ids = media_ids + "," + media_id_string

    print ("media_ids: ", media_ids)
    params = {'status': tweet_text, "media_ids": [media_ids]}
    req_text = oauth_sess.post(url_text, params = params)

    # 再びレスポンスを確認
    if req_text.status_code != 200:
        print ("テキストアップデート失敗: {}".format(req_text.text))
        return -1

    print ("tweet uploaded\n")
    return 1

5
8
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
5
8