Send Tweet From Python

import tweepy

import os

# take these from developer.twitter.com

ACCESS_KEY = "xxxxxx"

ACCESS_SECRET = "xxxxxx"

CONSUMER_KEY = "xxxxxx" #API_key

CONSUMER_SECRET = "xxxxxx"

BEARER_TOKEN = "xxxxxx"

# 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.

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.

sampletweet = f"""Robots doing science, could it happen?"""

# upload an image using the old api

media = api.media_upload(os.path.join(os.path.abspath(os.path.dirname(__file__)), "robot-doing-science.jpg"))

# 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])

# send tweet only # post_result = newapi.create_tweet(text=sampletweet) # prints the response from the API.

print(post_result)

  

📝 📜 ⏱️  ⬆️