Post on Twitter API using Tweepy and Python

Share this post

In this article, you will learn how to make a post on Twitter using Python and the Twitter API.

This tutorial is part of the complete guide on the Twitter API with Python.

Getting Started

Before you can use the Twitter API, you will need:


Subscribe to my Newsletter


  1. Python Installed. Read How to install Python with Anaconda
  2. Apply for a Twitter Developer Account
  3. Twitter API Credentials (API Keys)
    • api_key
    • api_secret
    • access_token
    • access_secret

Authenticate with Tweepy

To authenticate to the Twitter API with Tweepy, use this function.

import tweepy

api_key = "..."
api_secrets = "..."
access_token = "..."
access_secret = "..."

# Authenticate to Twitter
auth = tweepy.OAuthHandler(api_key,api_secrets)
auth.set_access_token(access_token,access_secret)

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)

Post a Simple Status

Now that we are authenticated, let’s make a very simple status post to your Twitter Profile.

status = "This is my first post to Twitter using the API"
api.update_status(status=status)

Mention a user in your Status

Now, let’s mention a user.

mention = 'ChouinardJC'
post_title = 'Post on Twitter API using Tweepy and Python'

status = f"Hey @{mention}, I managed to use the Twitter API!\n\n{post_title}"

api.update_status(status=status)

Add a link to a Post

link = 'https://www.jcchouinard.com/post-on-twitter-api-with-python/'
mention = 'ChouinardJC'

status = f'I am learning how to post to the Twitter API using #python by reading @{author} post\n {link}"
  
api = authpy(credentials)
api.update_status(status=status)

Post an Image on Twitter

Now, let’s post an image on Twitter.

imagePath = "image.png"
status = "Look at this"

api.update_with_media(imagePath, status)

Quote a Tweet

Now instead of just posting on Twitter, sometimes it is good to quote a Tweet. Luckily, Tweepy lets you do that.

author = 'ChouinardJC'
tweet_id = 'XXXXX'

link = f'https://twitter.com/{author}/status/{tweet_id}'
status = f"Love this! @{author}\n{link}"

api.update_status(status=status)

Retweet a Post

tweet_id = 'XXXXX'
api.retweet(tweet_id)

Conclusion

Here you have it.

You now know how to Post on Twitter API using Tweepy and Python.

5/5 - (1 vote)