Lists are a helpful Twitter feature that allows us to keep up with interesting accounts. Let’s look at how we can use Tweepy to work with those lists.
This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.
Preparation
As with the examples before, we need the user authentication tokens to work on behalf of that user:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import tweepy import os from dotenv import load_dotenv load_dotenv() # read keys from .env api_key = os.getenv('api-key') api_secret = os.getenv('api-key-secret') user_token = os.getenv('access-token') user_token_secret = os.getenv('access-token-secret') # use user authentication tokens auth = tweepy.OAuthHandler(api_key, api_secret) auth.set_access_token(user_token,user_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) |
Create a list
With the method create_list() we can create a new list for our user:
1 2 3 4 5 6 7 |
# create a new list list_name = "News created with Tweepy" description='News about Python' list = api.create_list(name=list_name, mode='private', description=description) print(f"New list id: {list.id}: {list.name} [{list.member_count}]") |
This creates us a new private list:
New list id: 1500259857177452546: News created with Tweepy [0]
If we want to create a public list, we need to set the parameter mode to ‘public’.
Add accounts to a list
We can use the method add_list_member() to add accounts one by one:
1 2 3 |
# add a single account to a list result = api.add_list_member(list_id=list.id,screen_name='pythonbytes') print(f"Current members: {result.member_count}") |
Current members: 1
Since the number of requests per 15 minutes is limited, we can use the method add_list_members() to add a list of accounts at once (up to 100 per request):
1 2 3 4 |
# add accounts to a list accounts = ['PythonNewsread', 'PythonWeekly'] result = api.add_list_members(list_id=list.id, screen_name=accounts) print(f"Current members: {result.member_count}") |
Current members: 3
Currently Twitter does not allow you to add a lot of accounts to a list in a short amount of time. If this happens to you, you will get rate limit errors as described in the last post. In this case you can wait 12 to 24 hours and then reduce the number of accounts you add per hour.
Remove an account from a list
We can remove an account from a list with the method remove_list_member()
1 2 3 |
# remove an account from a list result = api.remove_list_member(list_id=list.id,screen_name='pythonbytes') print(f"Current members: {result.member_count}") |
Current members: 2
As with adding multiple members at once we can remove them in groups with remove_list_members().
Show the lists of a user
The method get_lists() shows us the lists of a user:
1 2 3 4 5 |
# show all lists owned by a user (default: current user) user_name = 'PythonFriday' lists = api.get_lists(screen_name=user_name) for entry in lists: print(f"{entry.id} - {entry.name} ({entry.mode}|{entry.member_count})") |
This gives for my Python Friday account this output:
1500259857177452546 – News created with Tweepy (private|2)
1499136580530941963 – A private list (private|0)
1498823450231771137 – Podcasts (public|4)
1500933128113770505 – News (public|2)
You only can fetch the private lists from your own user, but not from other users.
Show the timeline of a list
To show the tweets written by the accounts on your list, we can us the method list_timeline():
1 2 3 4 5 6 7 8 9 |
# show timeline of a list list_id = 1500933128113770505 timeline = api.list_timeline(list_id=list_id,include_rts=False,count=3) for tweet in timeline: print(f"{tweet.id} [{tweet.created_at}] (@{tweet.user.screen_name}):") print(f"{tweet.text}\n") print(len(timeline)) |
This gives us a list of tweets like these:
1500078707964264449 [2022-03-05 12:00:08+00:00] (@PythonNewsread):
Learn Python today, Saturday! https://t.co/Xi1GncLxO91499716309164212230 [2022-03-04 12:00:06+00:00] (@PythonNewsread):
Learn Python today, Friday! https://t.co/Xi1GncLxO91499580410203942913 [2022-03-04 03:00:05+00:00] (@PythonWeekly):
Python Weekly – Issue 540 https://t.co/qfxPOneLZP #python #django #fastapi #flask #machinelearning #pandas… https://t.co/OdaXpxvfJJ3
The option include_rts allows us to include (= True) or exclude (= False) retweets, while count limits the number of tweets we get (up to 200).
Delete a list
We can delete a list with the destroy_list() method:
1 2 3 4 5 6 |
# remove a list try: result = api.destroy_list(list_id=list.id) print(f"{result.id} removed") except tweepy.errors.NotFound: print("list already removed") |
If the list exists, the code above will remove it:
1500259857177452546 removed
Examples with the V2 endpoint client
I find the V1 API a bit simpler to use when you start learning Tweepy. If you like to see the V2 examples, you can find them in my Python Friday GitHub repository. The files are in the Twitter folder and have a V2 suffix.
Next
We can now manage our lists and see what the accounts post. Next week we look at search and how we can find tweets on Twitter.
1 thought on “Python Friday #115: Working With Twitter Lists in Tweepy”