前提に質問の内容を詳しく書いてください。
tweepyとurllibでTwitterのdmに来た画像、動画を保存するプログラムを作ろうと思っています。
urllib.request.urlopen(media_url_https)
にするとHTTPS 401 エラーが出てしまいます
公式ドキュメントを見るとこのようなサンプルコードがあるのですがこのプログラムはPythonでできますか?oauth_consumer_keyなどの値はTwitterのTwitterのデロッパー画面から見れる値でいいのですか?
curl --request GET \ --url https://ton.twitter.com/1.1/ton/data/dm/1034828552951160836/1034828533812486145/oP5p359h.jpg \ --header 'authorization: OAuth oauth_consumer_key="6NxxxxxxCS", oauth_nonce="Sbxxxxxx2G", oauth_signature="637xxxxxxM%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1535557741", oauth_token="600-SQxxxxxxcqIF", oauth_version="1.0"'
実現したいこと
dmから画像を取得する
発生している問題・エラーメッセージ
HTTP Error 401: Unauthorized 401 Unauthorized date: Thu, 10 Nov 2022 05:48:33 UTC perf: 7626143928 server: tsa_m set-cookie: guest_id_marketing=v1%3A166805931393967493; Max-Age=63072000; Expires=Sat, 09 Nov 2024 05:48:33 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None set-cookie: guest_id_ads=v1%3A166805931393967493; Max-Age=63072000; Expires=Sat, 09 Nov 2024 05:48:33 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None set-cookie: personalization_id="v1_cdec8ll7FnUiYZ4o+SN4HQ=="; Max-Age=63072000; Expires=Sat, 09 Nov 2024 05:48:33 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None set-cookie: guest_id=v1%3A166805931393967493; Max-Age=63072000; Expires=Sat, 09 Nov 2024 05:48:33 GMT; Path=/; Domain=.twitter.com; Secure; SameSite=None cache-control: no-cache content-length: 0 x-transaction-id: b1e93c82ffe8df1d timing-allow-origin: https://twitter.com, https://mobile.twitter.com x-content-type-options: nosniff strict-transport-security: max-age=631138519 x-response-time: 117 x-connection-hash: f35c54b0b33dec3e74b2a38d0e913323c659a18ddd16d900d3f052ce925f96f9 connection: close None
該当のソースコード
python
1import urllib.error 2import urllib.request 3def download_file(url, dst_path): 4 try: 5 with urllib.request.urlopen(url) as web_file: 6 data = web_file.read() 7 with open(dst_path, mode='wb') as local_file: 8 local_file.write(data) 9 except urllib.error.HTTPError as e: 10 print(e) 11 print(e.code) 12 print(e.reason) 13 print(e.headers) 14 print(e.headers['WWW-Authenticate']) 15url="https://ton.twitter.com/1.1/ton/data/dm/1589771642997121033/1589771637129216005/pTaJerJk.jpg" 16download_file(url,"C:/Users/PC2006/Downloads/ko.png")
試したこと
requests.post('https://ton.twitter.com/1.1/ton/data/dm/1589771642997121033/1589771637129216005/pTaJerJk.jpg',auth=("Twitter_id","Twitter_password")
これを追加して"Twitter_id","Twitter_password"をいろいろ変えてみたりしました。
https://python.softmoco.com/basics/python-http-request.php#3
このサイトにありました
見当違いなことなのでしょうか?
補足情報(FW/ツールのバージョンなど)
OAuth2.0だと思う?、Twitter API v2です。
参考にしたサイトです
https://note.com/mitsuru_h_cc/n/n6a4e0b2134a8#UvDHG
https://python.softmoco.com/basics/python-http-request.php#3

あなたの回答
tips
プレビュー