Posting Tweets On Twitter using Python and Tweepy

posted in: Twitter API | 0
0

In a previous article on streaming Twitter data, I outlined how the Twitter API can provide access to valuable social media information that we can use for analytics. However, the Twitter API has much more to offer! One cool feature is that it enables us to interact with our Twitter accounts and to automate certain activities, for example, submitting tweets. A common use case, for example, is a Twitter bot that analyses financial market data and proactively informs its users when it encounters a trading signal. This tutorial demonstrates how we can create such a simple Twitter bot with Python. We’ll write some simple code that requests authentication via the Twitter API and then post a test tweet.

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

The Tweet Object

Tweets are the basic building blocks of Twitter and have several customization options that we can address through the API. So before we start with the coding parts, let’s take a quick look at these attributes.

First of all, a tweet contains a maximum of 280 characters of text. In addition, the text can contain hashtags or emojis. While hashtags are simply indicated via the # sign, smilies can be added via their standard Unicode. An overview of the emoji Unicode can be found here. Most emojis occupy two characters of the maximum text length.

Submitting a Twitter Tweet
Submitting a Twitter Tweet

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

Implementation: Posting Tweets via the Twitter API in Python

In the following, we will write a short Python script that authenticates against Twitter and then submits a Tweet via your Twitter account. We will look at two cases:

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

Prerequisites

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

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

In addition, we will be using the Tweepy package, which 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 the Auth Data

Interacting with the API requires us to first authenticate with our developer account credentials. All activities that you carry out via the API will be carried out by the user that you have provided during the developer account registration.

Storing the Account Credentials in a Python File

It is a good idea to not store the user credentials directly in your notebook and instead in a separate file. One way is to store them into a python file and then import the file. The code below shows an example of how this file should look. 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 be placed 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

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. In this example, we will send a very simple test tweet with a couple of hashtags.

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

# Generate text tweet
api.update_status(tweet)

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: Post a Tweet with an Image on Twitter

Ok, so what if we want to include a media file in our tweet? Well, for this case Tweety provides another useful function, which takes two arguments: the text (1) and the image path (2). Before you run this code, make sure you 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 = 

Et voilà: Another Tweet in our Twitter Account

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

Summary

This short tutorial demonstrated how to post using the Twitter API. We first authenticated against the API and then submitted two test tweets. Knowing how to interact with the Twitter account via the API is the basis for creating Twitter bots that provide automated information. In the next article, I will show how to create such a bot that analyzes financial data and automatically posts trading signals.

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