Script en Python para escribir un tweet con imagen en 2024

Este script utiliza la versión 2 de la API de Twitter para publicar el tweet y la versión 1 de la API para subir previamente las imágenes. Las imágenes se localizan en la misma carpeta del script con la extensión .jpg. Además, comprueba si la carpeta «archives» y si no la crea para poder archivar la imagen una vez publicada.

import tweepy
from datetime import date
import shutil, pathlib, os

# take these from developer.twitter.com
CONSUMER_KEY = "YOUR_CONSUMER_KEY"
CONSUMER_SECRET = "YOUR_CONSUMER_SECRET"
BEARER_TOKEN = "YOUR_BEARER_TOKEN"
ACCESS_KEY = "YOUR_ACCESS_KEY"
ACCESS_SECRET = "YOUR_ACCESS_SECRET"

 

# Authenticate to Twitter
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(
    ACCESS_KEY,
    ACCESS_SECRET,
)
# this is the syntax for twitter API 2.0. It uses the client credentials that we created
newapi = tweepy.Client(
    bearer_token=BEARER_TOKEN,
    access_token=ACCESS_KEY,
    access_token_secret=ACCESS_SECRET,
    consumer_key=CONSUMER_KEY,
    consumer_secret=CONSUMER_SECRET,
)

# Create API object using the old twitter APIv1.1
api = tweepy.API(auth)

# adding the tweet content in a multiline string. The {mydays} part is updated dynamically as the number of days from 6th Nov, 2023
sampletweet = "Test tweet!!!"

# I add the screenshot in the same directory as the code and add only one image. Since it is a screenshot taken using windows Snip, it is in png
for images in os.listdir(os.path.abspath(os.path.dirname(__file__))):
    # check if the image ends with png and take the first image that you find
    if images.endswith(".jpg"):
        img = images
        break


# Verificar si la carpeta 'archives' existe, si no, crearla
archives_folder = os.path.join(os.path.abspath(os.path.dirname(__file__)), "archives")
if not os.path.exists(archives_folder):
    os.makedirs(archives_folder)


# upload the media using the old api
media = api.media_upload(os.path.join(os.path.abspath(os.path.dirname(__file__)), img))
# create the tweet using the new api. Mention the image uploaded via the old api
post_result = newapi.create_tweet(text=sampletweet, media_ids=[media.media_id])
# the following line prints the response that you receive from the API. You can save it or process it in anyway u want. I am just printing it.
print(post_result)
today = date.today()
# get the file extension. This would be png by default but I was experimenting with different images. Will update this if required
file_extension = pathlib.Path(img).suffix
# Move the image to archives folder and rename it as per the date it was uploaded. I am only adding one post per day so this makes more sense
shutil.move(
    os.path.join(os.path.abspath(os.path.dirname(__file__)), img),
    os.path.join(
        os.path.abspath(os.path.dirname(__file__)),
        "archives",
        today.strftime("%Y%m%d") + file_extension,
    ),
)

Fuente: https://medium.com/@cn.april/posting-to-twitter-with-python-the-experience-and-code-fe62418e5af1

4 comentarios en «Script en Python para escribir un tweet con imagen en 2024»

  1. Lo primero es que es el unico script que me a funcionado para publicar imagenes sin que me den permisos elevados y sin pagar nada en Twitter.

    Lo segundo agradecerte todo el trabajo que haces y que compartes.

    Tercero si se podria subir un video corto sin tener permisos elevados y sin pagar en twiter y como?

    1. Muchas gracias por tus palabras Jose, me alegro de que te haya ayudado. Supongo que modificando un poco este script podrías subir también vídeos, pero no lo he probado. La clave es utilizar la api v1.1 para subir la imagen o vídeo, para después publicar el tweet haciendo referencia a la imagen/vídeo que hemos subido.

        1. import tweepy
          from datetime import date
          import shutil, pathlib, os

          # take these from developer.twitter.com
          CONSUMER_KEY = «YOUR_CONSUMER_KEY»
          CONSUMER_SECRET = «YOUR_CONSUMER_SECRET»
          BEARER_TOKEN = «YOUR_BEARER_TOKEN»
          ACCESS_KEY = «YOUR_ACCESS_KEY»
          ACCESS_SECRET = «YOUR_ACCESS_SECRET»

          # Authenticate to Twitter
          auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
          auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

          # Create API object using the old Twitter APIv1.1
          api = tweepy.API(auth)

          # Create API object using Twitter APIv2.0
          newapi = tweepy.Client(
          bearer_token=BEARER_TOKEN,
          access_token=ACCESS_KEY,
          access_token_secret=ACCESS_SECRET,
          consumer_key=CONSUMER_KEY,
          consumer_secret=CONSUMER_SECRET,
          )

          # Tweet content
          sampletweet = «Test tweet with a video!!!»

          # Get the first video found in the same directory as the script
          for videos in os.listdir(os.path.abspath(os.path.dirname(__file__))):
          # check if the video ends with a common video format and take the first video you find
          if videos.endswith((«.mp4», «.mov», «.avi»)):
          video = videos
          break

          # Verificar si la carpeta ‘archives’ existe, si no, crearla
          archives_folder = os.path.join(os.path.abspath(os.path.dirname(__file__)), «archives»)
          if not os.path.exists(archives_folder):
          os.makedirs(archives_folder)

          # Upload the video using the old API
          media = api.media_upload(
          os.path.join(os.path.abspath(os.path.dirname(__file__)), video), media_category=»tweet_video»
          )

          # Create the tweet using the new API. Mention the video uploaded via the old API
          post_result = newapi.create_tweet(text=sampletweet, media_ids=[media.media_id])

          # Print the response from the API
          print(post_result)

          # Move the video to the archives folder and rename it with the current date
          today = date.today()
          file_extension = pathlib.Path(video).suffix
          shutil.move(
          os.path.join(os.path.abspath(os.path.dirname(__file__)), video),
          os.path.join(
          os.path.abspath(os.path.dirname(__file__)),
          «archives»,
          today.strftime(«%Y%m%d») + file_extension,
          ),
          )

Deja un comentario