joep1
joep1

Reputation: 323

Tweepy follow Twitter users from text file using user_id (Python script)

I am trying to follow user_ids from a text file with 27 user_ids - one per line, e.g. :

217275660
234874181
27213931
230766319
83695362
234154065
68385750

I have some code that seems to work except it says user_id isn't defined (see pasted error at the bottom)... but user_id should be the correct variable in Tweepy... with or without [,follow] afterwards. My code is as follows:

# Script to follow Twitter users from text file containing user IDs (one per line)

# Header stuff I've just thrown in from another script to authenticate

import json
import time
import tweepy
import pprint
from tweepy.parsers import RawParser
from auth import TwitterAuth
from datetime import datetime

auth = tweepy.OAuthHandler(TwitterAuth.consumer_key, TwitterAuth.consumer_secret)

auth.set_access_token(TwitterAuth.access_token, TwitterAuth.access_token_secret)

rawParser = RawParser()

api = tweepy.API(auth_handler = auth, parser = rawParser)

# Open to_follow.txt

to_follow = [line.strip() for line in open('to_follow.txt')]
print to_follow

# Follow everyone from list?!

for user_id in to_follow:
    try:
        api.create_friendship(user_id)
    except tweepy.TweepError as e:
        print e
        continue

print "Done."

The error is:

$ python follow.py
['217275660', '234874181', '27213931', '230766319', '83695362', '234154065', '68385750', '94981006', '215003131', '30921943', '234526708', '229259895', '88973663', '108144701', '233419650', '70622223', '95445695', '21756719', '229243314', '18162009', '224705840', '49731754', '19352387', '80815034', '17493612', '23825654', '102493081']
Traceback (most recent call last):
  File "follow.py", line 30, in <module>
    api.create_friendship(user_id)
NameError: name 'user_id' is not defined

Upvotes: 3

Views: 4294

Answers (1)

Boaz
Boaz

Reputation: 5084

Indeed user_id isn't defined anywhere in your code.

I think you meant to do:
for user_id in to_follow:

The user_id's are in the list

And on a side note - the following code is better and more orthodox:

with open('to_follow.txt') as f:
    for line in f:
        user_id = line.strip()
        api.create_friendship(user_id)

Upvotes: 7

Related Questions