简体   繁体   English

在 python 中只转发带有 tweepy 的媒体的推文

[英]Retweeting only tweets with media with tweepy in python

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.要检查推文是否附加了媒体,您可以使用实体 object。 You would access the entities object, then check if there is a "media" key under it.您将访问实体 object,然后检查其下是否有“媒体”键。 When you get the tweet, you can try tweet.entities["media"] .当您收到推文时,您可以尝试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.如果有媒体附有推文,它将返回有关媒体的信息,如果没有,它将抛出 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.对于您的场景,您可以将tweet.entities["media"]放在您的 try 语句下,因此如果没有发生错误,则意味着媒体确实存在,您可以继续喜欢/转发该推文。 For the KeyError, you should add another except statement catching the error to skip liking/retweeting that tweet.对于 KeyError,您应该添加另一个捕获错误的 except 语句以跳过喜欢/转发该推文。

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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM