Automating Twitter Using Python 3 and Tweepy

avatar


So far I have covered more Arduino/C and even AMOS Basic than anything else, but my main language on the daily is Python, and my main use of Python is for making my day job life easier!

Python is an excellent language for automation and interacting with APIs (Application Programming Interfaces). Even if you are familiar with another language, or a fan of another system, this use-case makes Python still a worthy tool in your toolkit.

While I have been long planning creating a tutorial around Python for hardware and microcontroller programming (and even wrote an introduction to MicroPython on the Real Python site), I will probably cover that in 2021.

For now let's take a look at how Python can be helpful by automating routine tasks in Twitter.

Why is Python good at automation and API interaction?

To be fair, Python isn't the only language that is good for these purposes. Here's what makes Python ideal, though, in my opinion:

  • Available on most modern platforms (and some old ones too), either out of the box or easily added.
  • Plentiful, helpful and easy to use libraries.
  • Excellent text string and JSON/XML support for interacting with the data.
  • Just requires a text editor to develop, and can be deployed using any file transfer or even copy and paste.
  • Interactive REPL console so you can test things interactively without needing compilation.
  • Fast enough when run from command line/shell, even though interpreted.
  • Great libraries for internet and web interaction.
  • Final code can be run reliably remotely, headless and hands-off.

Getting and installing Python on your computer

First, check to see if you already have Python. Drop to a command line and enter python then hit return.

If you don't get an error then you have Python already! You will need Python 3, so if Python launches but says version 2.x, trying entering python3 and hitting enter instead.

Strangely, it seems Apple decided to stop bundling Python after Catalina. Perhaps they want to push folks to Swift?

Fortunately installers exist. Head over to the official starting point here to grab the download for your machine, or you can sign up for a free Python Anywhere account and not need to install anything.

Setting up to talk to Twitter as a developer

You will need the Tweepy libraries to follow these examples:

pip install tweepy

If you will deploy elsewhere, it is good practice to use a virtual environment:

mkdir twittertools
cd twittertools
python3 -m venv venv
source ./venv/bin/activate
pip install tweepy

Next you will need to apply for a Twitter Developer Account and create your Twitter application with that account so that you can get the 4 x API key codes that you need:

twitter developer account
  1. Consumer key
  2. Consumer secret
  3. Access token
  4. Access secret

They will also provide a "Bearer Token" that can sometimes come in handy.

Twitter API keys

When you get those keys, it is a good idea to store them apart from your logic code. I create a "secrets.py" that I then link along with the libraries, and then I can exclude this file in Github.

The tokens they give you initially will be set as Read-Only, which is fine for many, but we want to be able to make changes programmatically so we need to reset the permissions then generate new keys:

Twitter API permissions

Your First Twitter API Python Code

If we set permissions correctly, and copied and pasted the correct codes into our SECRETS.py, then this should send one tweet to your timeline:

import tweepy
import SECRET

Authenticate to Twitter

auth = tweepy.OAuthHandler(SECRET.CONSUMER_KEY, SECRET.CONSUMER_SECRET)
auth.set_access_token(SECRET.ACCESS_TOKEN, SECRET.ACCESS_TOKEN_SECRET)

Create API object

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

api.update_status("Twitter API test from Python 3")

First we import the libraries, the Twitter API library, and our SECRETS where we hide the Twitter API keys. Those keys are passed to the Tweepy OAuth handler that authenticates us.

We then create an API object that we can use to update our "Status" (send a tweet).

One thing to note is Tweepy allows us to automatically comply with Twitter's rate-limiting - they don't want us hammering the API with constant requests.

That does NOT mean you are safe from Twitter thinking your activity is suspiciously spam-bot-like. Don't do lots of following/unfollowing all at once, at least not without behaving like a regular Twitter user.

Automate Following and Unfollowing with Twitter

Speaking of following, if you want to follow everyone who follows you, then you can automate it easily using this code:

import tweepy
import SECRET

Authenticate to Twitter

auth = tweepy.OAuthHandler(SECRET.CONSUMER_KEY, SECRET.CONSUMER_SECRET)
auth.set_access_token(SECRET.ACCESS_TOKEN, SECRET.ACCESS_TOKEN_SECRET)

Create API object

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

me=api.me()

print("BEFORE:\n")
print(f"Followers: {me.followers_count}\nFollowing: {me.friends_count}\nListed: {me.listed_count}\nCreated: {me.created_at}\n\n\n ")

for follower in tweepy.Cursor(api.followers).items():
follower.follow()

print("AFTER:\n")
print(f"Followers: {me.followers_count}\nFollowing: {me.friends_count}\nListed: {me.listed_count}\nCreated: {me.created_at}\n\n\n ")

This introduces Tweepy "Cursors", a way of navigating long streams of Twitter collections of data. We show our user's stats, follow everyone we can (remember Twitter might think you are up to no good and cut you off), then shows the results afterwards.

As well as following, you can of course un-follow:

api.destroy_friendship(screen_name=follower.screen_name)

In my case, due to working on this tutorial, I get the following error:

tweepy.error.TweepError: [{'code': 161, 'message': "You are unable to follow more people at this time

I will just have to leave the API alone for a while and try again!

Automating Twitter Lists

Twitter list automatically created with python

If you don't want to follow everyone, you can still keep an eye on them with a list:

list = api.create_list(name="nerds",mode="public", description="makers, hobby and gamers")

This creates a list called Nerds (a list I actually have created as my following list was getting out of hand).

To add someone to this list you simply call add_list_member

api.add_list_member(list_id=list_id,screen_name="makerhacks")

Reading the Twitter Timeline

Many bots "listen" for certain keywords before taking action. You can get your accounts timeline easily:

import tweepy
import SECRET

Authenticate to Twitter

auth = tweepy.OAuthHandler(SECRET.CONSUMER_KEY, SECRET.CONSUMER_SECRET)
auth.set_access_token(SECRET.ACCESS_TOKEN, SECRET.ACCESS_TOKEN_SECRET)

Create API object

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

timeline = api.home_timeline()
for tweet in timeline:
print(f"@{tweet.user.screen_name} said {tweet.text}")

Going further

Obviously there is a lot more you can do, so check out the Tweepy documentation here.



Posted from my blog with SteemPress : https://makerhacks.com/twitter-python3-tweepy-automation/


0
0
0.000
2 comments
avatar

Congratulations @makerhacks! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You received more than 20000 upvotes. Your next target is to reach 25000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last post from @hivebuzz:

The Hive Gamification Proposal #2
0
0
0.000