Recently I've been working to develop a bot. But I got stuck for retweeting only media tweets and not the texts. So is there any way to filter them out? here is my part of code with liking and retweeting.
for tweet in tweepy.Cursor(api.search, search).items(nrTweets):
try:
i += 1
print(str(i) + '. Tweet Liked')
tweet.favorite()
time.sleep(30)
print(str(i) + '. Retweeted')
tweet.retweet()
os.system('cls')
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
To check if a tweet has media attached to it, you can use the entities object. You would access the entities object, then check if there is a "media" key under it. When you get the tweet, you can try tweet.entities["media"]
. If it there's media attached with a tweet, it would return information about the media, and if not, it would throw a KeyError.
For your scenario, you could put tweet.entities["media"]
under your try statement so if no error occurs, it means that media does exist and you can continue to like/retweet that tweet. For the KeyError, you should add another except statement catching the error to skip liking/retweeting that tweet.
try:
media = tweet.entities["media"]
# like & retweet the tweet
except KeyError:
print("Skipping tweet -- no media.")
# your other except statements
Here's the docs on the Twitter API's entities object: https://developer.twitter.com/en/docs/twitter-api/v1/data-dictionary/object-model/entities#entitiesobject
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.