It still seems like a library or authentication issue to me - because i can successfully get the image like this in python:
from requests_oauthlib import OAuth1Session
import shutil
api = OAuth1Session(
client_key="...",
client_secret="...",
resource_owner_key="...-...",
resource_owner_secret="...",
)
response = api.get("https://ton.twitter.com/i/ton/data/dm/.../.../....jpg", stream=True)
print(response.status_code)
with open("image.jpg", "wb") as f:
shutil.copyfileobj(response.raw, f)
Not sure how helpful this is, but this makes an oAuth1 authenticated GET to a Media URL from a DM, and saves it as a file. There are no redirects in this request, the status is 200.
Now to complete the Retrieving media | Docs | Twitter Developer Platform guide, you would implement an endpoint on your backend, that will take an image URL, authenticate it with oAuth1, and serve it like this:
<img src="fetch_dm_image?url=https://ton.twitter.com/i/ton/data/dm/....jpg">
for example, in python:
Need these dependencies:
pip install fastapi uvicorn requests requests-oauthlib
This would be fetch_image_api.py :
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from requests_oauthlib import OAuth1Session
app = FastAPI()
@app.get("/fetch_dm_image")
def fetch_dm_image(url: str):
api = OAuth1Session(
client_key="...",
client_secret="...",
resource_owner_key="...-...",
resource_owner_secret="...",
)
response = api.get(
url,
stream=True,
)
print(url)
print(response.status_code)
return StreamingResponse(response.raw, media_type="image/jpeg")
Run it
uvicorn fetch_image_api:app --reload
And now this should work:
http://127.0.0.1:8000/fetch_dm_image?url=https://ton.twitter.com/i/ton/data/dm/.../.../....jpg
and so will this on a page:
<img src="fetch_dm_image?url=https://ton.twitter.com/i/ton/data/dm/....jpg">