Post Tweets with Image Using Python Twitter API v2

Tiempo de lectura: 2 minutos

Reading Time: 2 minutes

Hello, today we are going to learn how to publish Tweets with images using Python with the Twitter API v2.

The first thing we need to do is create a Twitter APP, for that, consult one of the previous tutorials.

Let’s install the necessary libraries:

pip install python-dotenv
pip install requests python-dotenv
pip install requests

Once created, let’s go to a text editor and add:

import os
import json
import requests
from requests_oauthlib import OAuth1Session
from dotenv import load_dotenv

def send_tweet_with_image(text, remote_image_url):
    # Load environment variables from a .env file
    load_dotenv()

    CONSUMER_KEY = os.getenv("TWITTER_API_KEY")
    CONSUMER_SECRET = os.getenv("TWITTER_API_SECRET_KEY")
    ACCESS_TOKEN = os.getenv("TWITTER_ACESS_TOKEN")
    ACCESS_TOKEN_SECRET = os.getenv("TWITTER_ACESS_TOKEN_SECRET")

    # Create an OAuth1Session instance with your keys and tokens
    twitter_auth = OAuth1Session(CONSUMER_KEY, client_secret=CONSUMER_SECRET,
                                resource_owner_key=ACCESS_TOKEN,
                                resource_owner_secret=ACCESS_TOKEN_SECRET)

    # Upload the image to Twitter and get the media_id
    media_url = remote_image_url
    media_response = requests.get(media_url)
    if media_response.status_code != 200:
        return {"error": "Unable to download the image"}

    files = {
        'media': ('media.jpg', media_response.content)
    }

    media = twitter_auth.post("https://upload.twitter.com/1.1/media/upload.json",
                             files=files)

    if media.status_code != 200:
        return {"error": "Unable to upload the image"}

    media_id = json.loads(media.text)["media_id"]

    # Publish the tweet with the image
    url = "https://api.twitter.com/2/tweets"

    payload = {
        "text": text,
        "media": {"media_ids": [str(media_id)]}
    }

    response = twitter_auth.post(url, json=payload, headers={'Content-Type': 'application/json'})

    return response.json()

# Example of usage
tweet_text = "My image on Twitter!"
image_url = (
    "https://images.quierolibros.com/images/articles/literature/50389_image01.jpg"
)
result = send_tweet_with_image(tweet_text, image_url)
print(result)

This code fetches an image from a URL and uploads it to Twitter to then attach it to the published Tweet.

To execute it, we will need to call the function like this:

send_tweet("Hello world", "https://images.quierolibros.com/images/articles/literature/50389_image01.jpg")

In this example, we would upload the image from QuieroLibros.

Leave a Comment