python twitter api v2 example for posting tweets

How To Create Tweets Using Twitter API v2 With Python

In this post, we’ll make a simple Python script for posting tweets using Twitter API v2. Furthermore, you can build upon this functionality to create a bot for posting tweets on your profile page automatically.

To give you an idea, you can generate endless stream of geeky jokes with GPT models using OpenAI API and share them with your friends. Another one would be, you can create images with DALL-E and share those. Or perhaps even combine both of these ideas to create visually engaging tweets to grow your audience.

Authenticate as a user

First of all, for us to be able to do anything with Twitter API, we need to authenticate with tokens. In case you’re not familiar with them, they are unique strings of characters and numbers Twitter generates for your app.

Before I get ahead of myself, you will need to create a developer profile on Twitters developer portal. Once you make it this far, you’ll need an App. Since Twitter only allows 1 app on free tier package, you’ll probably have one already created.

You can click on the app settings button (should look like a cog icon) on the Dashboard screen. This will take you to the, you guessed it, App settings screen. Here, you’ll need to setup User authentication settings.

It is important that you set your apps permissions to write data, since we’ll be posting tweets with our script.

Twitter API v2 user authentication settings permissions

Okay, once you’re done setting up the authentication settings, you’ll be able to get your consumer keys and access tokens. Furthermore, you can find these under the Keys and tokens tab under your apps title.

You’ll need to save these tokens, since our script will use them everytime it’ll make an API call.

So without further ado, let’s get coding. I stored my tokens in a json file, which my Python script will read everytime I run it. Purpose for this is so I don’t reveal it inside the code. In case you’re going to share your code with others, I suggest you do the same.

Additionally, we’ll be working with a Python library called Tweepy, which also supports Twitter API v2 functionality. You can install it using pip with the following command: pip install tweepy.

import os
import json
import tweepy

ROOT = os.path.dirname(__file__)

def get_tokens(token_name):
    with open(os.path.join(ROOT, 'auth.json'), 'r') as auth_file:
        auth_data = json.load(auth_file)
        tokens = auth_data[token_name]
        return tokens
    
tokens = get_tokens('twitter-tokens')

Now that we have the tokens ready, we can create a client and authenticate as a user.

client = tweepy.Client(
    consumer_key=tokens['consumer-key'],
    consumer_secret=tokens['consumer-secret'],
    access_token=tokens['access-token'],
    access_token_secret=tokens['access-token-secret']
)

Creating a tweet with Twitter API v2

Finally, we have everything ready to start creating tweets. The following code shows how to post a tweet, containing only text.

response = client.create_tweet(
    text='Hello everyone, I just made a tweet with python.'
)

print(f'https://twitter.com/user/status/{response.data["id"]}')

As you can see you can also retrieve the tweets data, such as its ID.

Here is also the entire code of this project.

import os
import json
import tweepy

ROOT = os.path.dirname(__file__)

def get_tokens(token_name):
    with open(os.path.join(ROOT, 'auth.json'), 'r') as auth_file:
        auth_data = json.load(auth_file)
        tokens = auth_data[token_name]
        return tokens
    
tokens = get_tokens('twitter-tokens')

client = tweepy.Client(
    consumer_key=tokens['consumer-key'],
    consumer_secret=tokens['consumer-secret'],
    access_token=tokens['access-token'],
    access_token_secret=tokens['access-token-secret']
)

response = client.create_tweet(
    text='Hello everyone, I just made a tweet with python.'
)

print(f'https://twitter.com/user/status/{response.data["id"]}')

Conclusion

To conclude, we made a simple Python script for posting tweets using Twitter API v2 functionality. I learned a lot while working on this project and I hope it proves itself helpful to you as well.

Share this article:

Related posts

Discussion(0)