🍿 5 min. read

How I automatically created a Twitter List of FreeCodeCampers in 5 minutes

Monica Powell

Using Twython Twitter API wrapper to add users to a Twitter List

We are going to create a Python script that will automatically search Twitter for individuals who use the #freeCodeCamp hashtag and add them to a Twitter list of "FreeCodeCampers". Twitter lists are a way to curate a group of individuals on Twitter and collect all of their tweets in a stream, without having to follow each individual accounts. Twitter lists can contain up to 5,000 individual Twitter accounts.

We can accomplish this by doing the following:

  • Installing the necessary Python packages
  • Registering an application with Twitter
  • Generating and accessing our Twitter credentials
  • Making Twitter Search and List API calls

So lets get started.

1. Installing the necessary Python packages

Create a file named addToFreeCodeCampList.py, that will contain our main script and then import two Python modules into this file:

  • Import Config: In the same directory as ouraddToFreeCodeCampList.py script, create a file named config.py that stores our confidential Twitter API credentials. We are going to import our API credentials from that file into our addToFreeCodeCampList.py script by including the line import config. Twitter requires a valid API key, API secret, access token and token secret for all API requests.
  • Import Twython: Twython is a Python wrapper for the Twitter API that makes it easier to programmatically access and manipulate data from Twitter using Python. We can import Twython with the following line from twython import Twython, TwythonError.

Your addToFreeCodeCampList.py script should now look like this.

1import config
2 from twython import Twython, TwythonError

2. Registering an application with Twitter

We need to authenticate our application in order to access the Twitter API. You need to have a Twitter account in order to access Twitter's Application Management site. The Application Management site is where you can view/edit/create API keys, API secrets, access tokens and token secrets.

  1. In order to create these credentials, we need to create a Twitter application. Go to the Application Management site and click on "Create New App". This should direct you to a page that looks similar to the one below.

  1. Fill out of the required fields and click on "Create your Twitter application". You will then be redirected to a page with details about your application.

3. Generating and accessing our Twitter credentials

  1. Click on the tab that says "Keys and Access Tokens" and copy the "Consumer Key (API Key)" and "Consumer Secret (API Secret)" into the config.py file
  2. Scroll down to the bottom of the page and click on "Create my access token". Copy the generated "Access Token" and "Access Token Secret" into the config.py file.

2) Currently, all of our Twitter credentials live inside our config.py file and we've imported config into our addToFreeCodeCampList.py file. However, we have not actually passed any information between the files.

Let's change that by creating a Twython object and passing in the necessary API key, API secrets and API token from our config.py file with the following:

1twitter = Twython(config.api_key, config.api_secret, config.access_token, config.token_secret)

The addToFreeCodeCampList.py file should now look similar to this:

1import config
2 from twython import Twython, TwythonError
3 # create a Twython object by passing the necessary secret passwords
4 twitter = Twython(config.api_key, config.api_secret, config.access_token, config.token_secret)

4. Making Twitter Search and List API calls

Let's make an API call to search Twitter and return the 100 most recent tweets

1# return tweets containing #FreeCodeCamp
2 response = twitter.search(q='"#FreeCodeCamp" -filter:retweets', result_type="recent", count=100)
1# for each tweet returned from search of #FreeCodeCamp
3 for tweet in response['statuses']:
5 # print tweet info if needed for debugging
7 print(tweet)
8 print(tweet['user']['screen_name'])

A single tweet returned by this API call looks like this in JSON:

1{'created_at': 'Sun Dec 24 00:23:05 +0000 2017', 'id': 944725078763298816, 'id_str': '944725078763298816', 'text': 'Why is it so hard to wrap my head around node/express. Diving in just seems so overwhelming. Templates, forms, post…
2 'truncated': True, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/ae52rro63i', 'expanded_url': 'https://twitter.com/i/web/status/944725078763298816', 'display_url': 'twitter.com/i/web/status/9…', 'indices': [117, 140]}]}, 'metadata': {'iso_language_code': 'en', 'result_type': 'recent'}, 'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 48602981, 'id_str': '48602981', 'name': 'Matt Huberty', 'screen_name': 'MattHuberty', 'location': 'Oxford, MS', 'description': "I'm a science and video game loving eagle scout with a Microbio degree from UF. Nowadays I'm working on growing my tutoring business at Ole Miss. Link below!", 'url': 'https://t.co/dfuqNNoBYZ', 'entities': {'url': {'urls': [{'url': 'https://t.co/dfuqNNoBYZ', 'expanded_url': 'http://www.thetutorcrew.com', 'display_url': 'thetutorcrew.com', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 42, 'friends_count': 121, 'listed_count': 4, 'created_at': 'Fri Jun 19 04:00:44 +0000 2009', 'favourites_count': 991, 'utc_offset': -28800, 'time_zone': 'Pacific Time (US & Canada)', 'geo_enabled': False, 'verified': False, 'statuses_count': 199, 'lang': 'en', 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'C0DEED', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/777294001598758912/FVOIrnb4_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/777294001598758912/FVOIrnb4_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/48602981/1431670621', 'profile_link_color': '1DA1F2', 'profile_sidebar_border_color': 'C0DEED', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': True, 'default_profile': True, 'default_profile_image': False, 'following': False, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 1, 'favorite_count': 0, 'favorited': False, 'retweeted': False, 'lang': 'en'}

Add Tweet-ers to our Twitter list

In order to add the author of the tweet to our Twitter list we need the username associated with the tweet tweet['user']['screen_name']

Let's try to add the users from these tweets to our Twitter list "FreeCodeCampers". I created my Twitter list at https://twitter.com/waterproofheart/lists/freecodecampers which means for my script the slug is freecodecampers and the owner_screen_name is mine, waterproofheart.

1for tweet in response['statuses']:
3# try to add each user who has tweeted the hashtag to the list
5twitter.add_list_member(slug='YOUR_LIST_SLUG', owner_screen_name='YOUR_USERNAME', screen_name= tweet['user']['screen_name'])
7#if for some reason Twython can't add user to the list print exception message
8except TwythonError as e:

You can create your own Twitter list by navigating to your Twitter profile, clicking on "Lists" on desktop and clicking on the right hand side to "Create new list". View the official Twitter List documentation for more information.

You can test your script by running python addToFreeCodeCampList.py in the terminal.

My final script looks like this:

1import config
3from twython import Twython, TwythonError
5# create a Twython object by passing the necessary secret passwords
6twitter = Twython(config.api_key, config.api_secret, config.access_token, config.token_secret)
8# return tweets containing #FreeCodeCamp
9response = twitter.search(q='"#FreeCodeCamp" -filter:retweets', result_type="recent", count=100)
12# for each tweet returned from search of #FreeCodeCamp
13for tweet in response['statuses']:
14 # print each username if needed for debugging
15 # print(tweet['user']['screen_name'])
17 # try to add each user who has tweeted the hashtag to the list
18 try:
19 twitter.add_list_member(slug='YOUR_LIST_SLUG', owner_screen_name='YOUR_SCREEN_NAME', screen_name= tweet['user']['screen_name'])
20 except TwythonError as e:
21 print(e)

This script can be set to automatically run locally or remotely via a cron job which allows tasks to be performed at a set schedule.

Feel free to tweet at me if you have any questions, suggestions or want to share how you modified this script!

This article was published on January 17, 2018.

Don't be a stranger! πŸ‘‹πŸΎ

Thanks for reading "How I automatically created a Twitter List of FreeCodeCampers in 5 minutes". Join my mailing list to be the first to receive my newest web development content, my thoughts on the web and learn about exclusive opportunities.


    I won’t send you spam. Unsubscribe at any time.


    • Fit Coders World 🧼 πŸ‘ 🚰
    • pew
    • Marien
    • Maxim Leyzerovich
    • knut 🏠 working from cyberspace
    • Dan Abramov
    • Sophia Li
    • Aaron
    • Joe Previte πŸ¦€
    • Joe Martire
    • Sara De La Cruz
    • 𝓙𝓲𝓢 😷 Stay at home 😷 𝓛𝓲𝓾
    • Dave E
    • Angie Gonzalez
    • Melinda Golden
    • Florida Elago
    • anniezheng
    • florapdx @ #WomenOfReact2020
    • Ricky @ WomenOfReact
    • Melissa Em
    • ⚑️ leila ⚑️