Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationEventAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

Python Twitterに画像を投稿

import sys
import json
import ssl
import string
import io
from PIL import Image
from requests_oauthlib import OAuth1Session
import urllib.request

# Twitter APIのAuthToken等は事前に用意
# OAuth認証 セッションを開始
twitter = OAuth1Session(CK, CS, AT, AS)

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

# 画像 URL
img_url = 'http://www.dmm.com/xxx.jpg'  # など
response = urllib.request.urlopen(img_url)
data = response.read()
files = {"media" : data}
req_media = twitter.post(url_media, files = files)

# レスポンス
if req_media.status_code != 200:
    print ("画像アップロード失敗: %s", req_media.text)

# media_id を取得
media_id = json.loads(req_media.text)['media_id']

# 投稿した画像をツイートに添付したい場合はこんな風に取得したmedia_idを"media_ids"で指定してツイートを投稿
message = '投稿メッセージ'
params = {'status': message, "media_ids": [media_id]}
req_media = twitter.post(url_text, params = params)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Help us understand the problem. What are the problem?