How to Turn off Twitter Retweets with Python


Alexis Madrigal wrote an article in the Atlantic proposing a new way of helping user to tame their Twitter feeds. Turn off retweets.

I really think that he is on to something and after having tried it for a while, I wanted to code a way of doing this without having to manually go to each user’s profile and turn off all retweets. Fortunately with python we have a pretty quick option.

Our basic script will look like this:

import twitter
import yaml

with open('settings.yaml', 'r') as yaml_file:
    config = yaml.load(yaml_file)

api = twitter.Api(consumer_key = config['consumer_key'],
consumer_secret= config['consumer_secret'],
access_token_key= config['access_token_key'],
access_token_secret= config['access_token_secret'])
user_info = api.VerifyCredentials()
friends = api.GetFriendIDs(user_info.screen_name)

print('modifying status for {0} relationships'.format(len(friends)))
for friend in friends:
    api.UpdateFriendship(user_id=friend, retweets=False)
print('finished')

To get this working you will need to install the python-twitter library using pip. This script is also using pyyaml to keep credentials, but you could replace the config section out with hard-coded(!) values.

You will also need to create a twitter app and generate access tokens for your account. The developers of python-twitter included a great tutorial here.

Once you have installed your dependencies and setup permissions for your new app, run:

python manage.py

and it will turn off retweets for all the users your follow:

modifying status for 135 relationships
finished

This is the kind of script that you could either run manually or automate with a cron job running on a Raspberry Pi or something.

You can check out the repository located on github here.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.