Posting Tweets via the Twitter API v2.0

Posting Tweets On Twitter using Python and Tweepy

posted in: Twitter API | 0

In a previous article, we have shown how to retrieve social media data via the Twitter API in Python. However, there are many more cool things that we can do with the Twitter API. Another cool thing is to interact with the Twitter user account and post 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 in 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

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 a maximum of 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 indicated via standard Unicode. Here you can find an overview of the emoji Unicode. Most emojis occupy two characters of the maximum text length, but some may require more.

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

In the following, we will 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

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 we start 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 we can interact with the Twitter API, we must first 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 Twitter user associated with it.

Storing the Account Credentials in a Python File

The user credentials should not be stored directly in your notebook and instead in a separate file. One option is to keep them in a Python file and then import the file. The following code shows how this file might look. To use this approach, you need to replace the values below with your own 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()
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:

# config.yaml file

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 have successfully authenticated 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 that exists 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 in 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.

Interacting with Twitter via the API is an essential step to create 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 the article under the link below.

Author

  • Hi, I am Florian, a Zurich-based consultant for AI and Data. Since the completion of my Ph.D. in 2017, I have been working on the design and implementation of ML use cases in the Swiss financial sector. I started this blog in 2020 with the goal in mind to share my experiences and create a place where you can find key concepts of machine learning and materials that will allow you to kick-start your own Python projects.

Leave a Reply