Maker Hacks

Ideas, news & tutorials for makers and hackers – Arduino/Raspberry Pi, 3D printing, robotics, laser cutting, and more

  • Home
  • About Maker Hacks
  • Blog
  • YouTube Channel
  • Recommendations
  • Contact
You are here: Home / Hacks, Tips, and Tutorials / Automating Twitter Using Python 3 and Tweepy

Automating Twitter Using Python 3 and Tweepy

Chris Garrett

FacebookTweetPin

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.

Related

FacebookTweetPin

by Chris Garrett Filed Under: Hacks, Tips, and Tutorials Tagged With: api, developer, programming, tweepy, twitter

About Chris Garrett

StudioPress Marketing Director at WP Engine. Co-author of the Problogger Book with Darren Rowse. Maker of things. 🇨🇦 Canadian

☕️ Support Maker Hacks on Ko-Fi and get exclusive content and rewards!

« Triangle Labs Dragon Hotend Review
Quit Zoom Call Macro Key – How to Make a Custom Cherry MX USB Macro Keyboard/Keypad with Arduino »

The website for makers and hackers – Arduino, Raspberry Pi, 3D Printing and more

Get fresh makes, hacks, news, tips and tutorials directly to your inbox, plus access to the 30 Days to Arduino course

Recently Popular

  • How to choose the right 3D printer for you
  • Glowforge Review – Glowforge Laser Engraver Impressions, Plus Glowforge Versus Leading Laser Cutters
  • Original Prusa i3 Mk3S Review
  • Best 3D Printing Facebook Groups
  • Elegoo Mars Review – Review of the Elegoo Mars MSLA Resin 3D Printer
  • Glowforge ‘Pass-Through’ Hack: Tricking the Front Flap of the Glowforge with Magnets to Increase Capacity
  • How to Make a DIY “Internet of Things” Thermometer with ESP8266/Arduino
  • Wanhao Duplicator i3 Review
  • IKEA 3D Printer Enclosure Hack for Wanhao Di3
  • Creality CR-10 3d printer review – Large format, quality output, at a low price!
  • 3D Printed Tardis with Arduino Lights and Sounds
  • Anet A8 Review – Budget ($200 or less!) 3D Printer Kit Review
  • Make your own PEI 3D printer bed and get every print to stick!
  • Upgrading the Wanhao Di3 from Good to Amazing
  • How to Install and Set Up Octopi / Octoprint
  • Creality CR-10 S5 Review

Copyright © 2021 Maker Hacks