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,
),
)