Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install python-dotenv
pip install requests python-dotenv
pip install requests
pip install python-dotenv pip install requests python-dotenv pip install requests
pip install python-dotenv
pip install requests python-dotenv
pip install requests

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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)
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)
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
send_tweet("Hello world", "https://images.quierolibros.com/images/articles/literature/50389_image01.jpg")
send_tweet("Hello world", "https://images.quierolibros.com/images/articles/literature/50389_image01.jpg")
send_tweet("Hello world", "https://images.quierolibros.com/images/articles/literature/50389_image01.jpg")

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

0

Leave a Comment