How to retweet users' tweets in Python (and not their followers' tweets/RTs)

Question:

I am building a bot that will copy and paste tweets from several users (candidates to a presidential election).
When I run the code, my bot is actually copying supporters’ tweets and retweets thus creating insane traffic on my page – all I want to copy is what the candidates themselves tweet from their account.

Anyone know how to do that?

I thought this:
if tweetText.startswith('RT @'):
pass

would solve the RT issue but apparently not…

Here is my code:

import twitter, sys, json, csv, time

# this app is being run by cast laboratory..@CASTlaboratory (4003669463)
consumer_key=""
consumer_secret=""
access_token=""
access_token_secret=""

auth = twitter.oauth.OAuth(access_token, access_token_secret,consumer_key, consumer_secret)
twitter_api = twitter.Twitter(auth=auth)

#Users we are following: Nicolas Dupont-Aignan, Francois Asselineau, Francois Fillon, Philippe Poutou, Jacques Cheminade, Emmanuel Macron, Nathalie Arthaud, Marine le Pen, Benoit Hamon, Jean Lassalle, Jean Luc Melenchon.

u = "38170599, 200659061, 551669623, 374392774, 150201042, 1976143068, 1003575248, 217749896, 14389177, 102722347, 80820758"

print >>sys.stderr, 'Retweeting everything for users="%s"' % (u)
twitter_stream = twitter.TwitterStream(auth=twitter_api.auth)
stream = twitter_stream.statuses.filter(follow=u)

for tweet in stream:

    tweetText = tweet['text'].encode('utf-8')
    print tweetText
    user = tweet['user']['screen_name']

    if tweetText.startswith('RT @'):
        pass

    else:

        print tweetText
        twitter_api.statuses.update(status = tweetText)
        time.sleep(60)

Thank you!

Asked By: WonderCee

||

Answers:

To filter the tweets to only match those coming from the users you’re looking at, you should be able to do something like the following:

for tweet in stream:
    tweet_text = tweet['text'].encode('utf-8')
    user_id = tweet['user']['id']
    user_name = tweet['user']['screen_name']

    if user_id in u:
        print '@{}: {}'.format(user_name, tweet_text)
        time.sleep(60)
    else:
        pass

As discussed in the comments, you should not be blanket-reposting tweets from different accounts. If this is something you’ve been explicitly asked to do in your assignment, maybe you should highlight this in your answer.

Answered By: asongtoruin

Hello @WonderCee did you eventually find a solution to this. I need the exact same kind of bot (just not for politicians) – but this doesn’t seem to work.

Best!

Answered By: Heimskr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.