Your first elif
does not appear to match up to the specification you describe at the top of your question.
The if
statement checks if the first hashtag is ≦20 characters. If so, it tweets; if not, it doesn't. So far, so good. Then, your first elif
statement is guaranteed to execute - because if len(hashtags[0])
is not <= 20
, then it certainly is > 20
, and so you'll never get to the second elif
. If you want to check whether or ot the second hashtag is ≦20 characters, your first elif
should read as follows:
elif len(hashtag[1]) <= 20:
trend_hashtag = hashtags[1] # you have a typo here btw
api.update_status(line + trend_hashtag)
Finally, your last elif
should just be an else
. If you want it to sleep for 3 hours between tweets, you should have the call to time.sleep(10800)
after each time it tweets. Taken together, your code should end up looking more like this:
for line in f:
trends1 = api.trends_place(1)
hashtags = [x['name'] for x in trends1[0]['trends'] if x['name'].startswith('#')]
trend_hashtag = None
if len(hashtags[0]) <= 20:
trend_hashtag = hashtags[0]
elif len(hashtags[1]) <= 20:
trend_hashtag = hashtags[1]
if trend_hashtag:
api.update_status(line + trend_hashtag)
time.sleep(3*60*60)
else:
time.sleep(15*60)
This way, you only do a 3-hour sleep after you've tweeted - otherwise (if you haven't tweeted), you only sleep for 15 minutes and then try again.