Convert Twitter-Id’s to Twitter-handles (Python script)

If you need to convert a lot of Twitter-ID’s to Twitter-handles frequently, you might consider downloading “Anaconda” (or another Python-environment) for your own operating system.

Below you will find a script, that are able to take a comma separated line of ID’s and convert them to handles. The script will output to command line and create a csv-file in the same directory as the file is run from.

Prior to running the script, you will need to create a Twitter-app to grant the script acces to Twitters’ API. You will also need to install Tweepy and its’ dependencies either through a terminal or the Anaconda interface. The script can be run in Jupyter Notebook. Please note, there is no error handling in the script, but Jupyter Notebook does provide friendly error messages for debugging input.

# TAKE IDs AND CONVERT TO HANDLES COMMA SEPARATED

import tweepy
import csv
import time

# GLOBAL VARS
consumer_key = 'CREATE_AND_INSERT'
consumer_secret = 'CREATE_AND_INSERT'
access_token = 'CREATE_AND_INSERT'
access_token_secret = 'CREATE_AND_INSERT'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

# SET OBJECT AND AUTHENTICATE
api = tweepy.API(auth)

# Prompt for usernames
print('Format input like this userid1,userid2,userid3')
print('Eg. Provide a comma separated list that looks like: 92454545,555787894,65656478')

myIds = input("Feed a comma separated list of user id numbers ")

#Check for valid input
if myIds:
    # Clear the input, prepare for lookup
    myIds = myIds.replace(' ','')
    myIds = myIds.split(',')
    # Set a new list object
    myHandleList = []
    i = 0
    # Loop trough the list of usernames
    for idnumber in myIds:
        u = api.get_user(myIds[i])
        uid = u.screen_name
        myHandleList.append(uid)
        i = i+1
    # Print the lists
    print('Twitter-Ids',myIds)
    print('Usernames',myHandleList)
        #set a filename based on current time
    csvfilename = "csvoutput-"+time.strftime("%Y%m%d%-H%M%S")+".csv"
    print('We also outputted a CSV-file named '+csvfilename+' to your file parent directory')
    with open(csvfilename, 'w') as myfile:
        wr = csv.writer(myfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        wr.writerow(['username','twitter-id'])
        j = 0
        for handle in myHandleList:
            writeline = myHandleList[j],myIds[j]
            wr.writerow(writeline)
            j = j+1
else:
    print('The input was empty')