Posting Tweets On Twitter using Python and Tweepy

In a previous article, we have shown how to retrieve social media data via the Twitter API in Python. However, we can do many more cool things with the Twitter API. Another cool thing is interacting with the Twitter user account and posting automated tweets. This article shows how this works. We will use the Twitter API and the Tweepy library to submit tweets to our Twitter account.

A common use case for submitting tweets via the Twitter API is a Twitter bot. Today, many bots on Twitter send automated tweets, for example, about unusual movements in the stock market or other types of events. However, it is worth mentioning that bots are also used for evil purposes, for example, to lure people into scams or influence political opinions.

This tutorial lays the foundation for building a simple Twitter bot with Python and Tweepy. The remainder of this article is structured as follows: We’ll begin by briefly looking at the tweet object on Twitter. Then, we will write some code that requests authentication via the Twitter API and submit some test tweets to the API.

The Tweet Object of the Twitter API

Tweets are the basic building blocks of Twitter. They have several customization options, such as media, hashtags, and emojis. We can use all of these options by specifying respective parameters in our requests to the Twitter API.

First of all, a tweet contains up to 280 characters of text. The text can include hashtags or emojis, which also occupy space in terms of characters.

While hashtags are indicated via the #-sign, emojis are displayed via standard Unicode. Most emojis occupy two characters of the maximum text length, but some may require more. Here you can find an overview of the emoji Unicode.

Optionally, tweets can contain media objects such as images, GIFs, or Polls. We can attach these elements via a separate API function.

Submitting a Twitter Tweet
Submitting a Twitter Tweet

Implementation: Posting Tweets via the Twitter API in Python

This tutorial shows how to write a short Python script that authenticates against Twitter. Then we will submit some test Tweets using your Twitter account. We will look at two different cases:

  • Submitting a simple text-only tweet
  • Submitting a tweet that contains text and a media file

The code is available on the GitHub repository.

Prerequisites

Using the Twitter API requires a Twitter developer account. If you don’t have one yet, you can follow the steps described in this tutorial to create an account for free.

Before starting the coding part, make sure that you have set up your Python 3 environment and required packages. If you don’t have an environment set up yet, you can follow this tutorial to set up the Anaconda environment.

Also, make sure you install all required packages. In this article, we will be working with the following standard packages: 

In addition, we will be using Tweepy. Tweepy is an easy-to-use Python library for accessing the Twitter API.

You can install packages using console commands:

  • pip install <package name>

Step #1: Load Twitter Account Credentials for Authentication

Before interacting with the Twitter API, we must authenticate with our developer account credentials. The developer account is linked to the Twitter account specified during registration. So, when you execute an API request, it will use the associated Twitter user.

Storing the Account Credentials in a Python File

We should not store the user credentials directly in our Python notebooks. Instead, we should use a Python file and import it into our notebook. You can use the following sample file and replace the values with your Twitter API keys, secrets, and tokens.

# Twitter Consumer API keys
CONSUMER_KEY    = "api123"
CONSUMER_SECRET = "api123"

# Twitter Access token & access token secret
ACCESS_TOKEN    = "api123"
ACCESS_SECRET   = "api123"

BEARER_TOKEN = "api123"

class TwitterSecrets:
    """Class that holds Twitter Secrets"""

    def __init__(self):
        self.CONSUMER_KEY    = CONSUMER_KEY
        self.CONSUMER_SECRET = CONSUMER_SECRET
        self.ACCESS_TOKEN    = ACCESS_TOKEN
        self.ACCESS_SECRET   = ACCESS_SECRET
        self.BEARER_TOKEN   = BEARER_TOKEN
        
        # Tests if keys are present
        for key, secret in self.__dict__.items():
            assert secret != "", f"Please provide a valid secret for: {key}"

twitter_secrets = TwitterSecrets()

Once you have stored the API keys in the file and the file in the right folder, you can load the API keys into your Python project with the following code.

import pandas as pd
import tweepy 

# place the twitter_secrets file under <User>/anaconda3/Lib
from twitter_secrets import twitter_secrets as ts

consumer_key = ts.CONSUMER_KEY
consumer_secret = ts.CONSUMER_SECRET
access_token = ts.ACCESS_TOKEN
access_secret = ts.ACCESS_SECRET

### Print API Auth Data (leave disabled for security reasons)
# print(f'consumer_key: {consumer_key}')
# print(f'consumer_secret: {consumer_secret}')
# print(f'access_token: {access_token}')
# print(f'access_secret: {access_token}')

Alternative: Storing the Account Credentials in a YAML File

Alternatively, you can also put the credentials into a YAML file (called “api_config_twitter.yml.” The file should then look as follows, and you can place it in a subfolder “API Keys” in your working directory:

api_key: api123 
api_secret: api123
access_token: api123
access_secret: api123

You can then import the token and access keys with the code below.

## In case you prefer to load the auth data from a local yaml file, use the following code
import yaml
# load the API keys and further data from your local yaml file
# place the api_config_twitter.yml file under <python notebook>/API_Keys/
yaml_file = open('API Keys/api_config_twitter.yml', 'r')  
p = yaml.load(yaml_file, Loader=yaml.FullLoader)

try:
    consumer_key = p['api_key']
    consumer_secret = p['api_secret']
    access_token = p['access_token']
    access_secret = p['access_secret']
except ValueError: 
        print('error')

Step #2: Request User Authentication via the API

When you have the auth data available in your project, you can authenticate against the Twitter API.

#authenticating to access the twitter API
auth=tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_secret)
api=tweepy.API(auth)

Step #3: Post a Text-only Tweet on Twitter

Once we successfully authenticate at the Twitter API, we can interact with our Twitter user account. The code below will submit a test tweet via Twitter API. As you can see, we also indicated two hashtags.

# Define the tweet text
tweet='this is an automated test tweet using #Python $BTC $ETH'

# Generate text tweet
api.update_status(tweet)

Once you run the code, the tweet will immediately appear in the feed of our Twitter account:

A simple test tweet sent via the Twitter API
A simple test tweet sent via the Twitter API

Step #4: Include Mediafiles in Tweets via the API

We can also include media files such as photos and videos in our tweets. For this case, Tweety provides a separate function called “update_with_media.” This function takes two arguments: the image path and tweet_text.

Before running the code below, you need to change the image_path to reference an image file on your computer.

# Define the tweet text
tweet_text='This is another automated test tweet using #Python'
image_path ='Test Images/ETH_price.png'

# Generate text tweet with media (image)
status = api.update_with_media(image_path, tweet_text)

Et voilà: Another Tweet has appeared on our Twitter Account. This time, the post includes the sample text and a media file.

Twitter tweet with an image attached
Twitter tweet with an image attached

Summary

This article has shown how you can use Tweepy and Python to submit tweets via the Twitter API. You have learned to authenticate against the Twitter API and submit tweets containing text and media files.

Understanding how to interact with Twitter via the API is essential when creating a Twitter bot. I have written another article about creating a Twitter signaling bot that analyzes financial data and tweets about relevant price movements. If you want to learn more about this topic, check out this article on Generating crypto trading signals in Python

Sources and Further Reading

The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.

0 0 votes
Article Rating
Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x