11
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python Twitterに画像を投稿

Last updated at Posted at 2018-06-25
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)
    exit()

# 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)
11
14
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
11
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?