作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
经过一番搜索,我找到了一种从给定用户下载最近推文的方法。现在我想得到每条推文的回复。我知道 Twitter API 不提供获取推文回复的端点,除非我们有高级帐户。但我可以在互联网上找到一些解决方法。我找到了一种使用 Getting tweet replies to a particular tweet from a particular user 获取一些推文及其回复的方法。下面也给出了该代码。
如何修改代码 (getData.py) 以将每条推文的回复连同推文一起保存在 csv 中?
My code to download a user's tweets as csv (getData.py)
import tweepy
import csv
# Twitter API credentials
consumer_key = "###########"
consumer_secret = "################"
access_key = "#################"
access_secret = "#####################"
def get_all_tweets(screen_name):
# Twitter only allows access to a users most recent 3240 tweets with this method
# authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
# initialize a list to hold all the tweepy Tweets
alltweets = []
# make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name=screen_name, count=200)
# save most recent tweets
alltweets.extend(new_tweets)
# save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
# keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
print
"getting tweets before %s" % (oldest)
# all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.user_timeline(screen_name=screen_name, count=200, max_id=oldest)
# save most recent tweets
alltweets.extend(new_tweets)
# update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
print
"...%s tweets downloaded so far" % (len(alltweets))
# transform the tweepy tweets into a 2D array that will populate the csv
outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8"), tweet.favorite_count, tweet.retweet_count]
for tweet in alltweets]
# write the csv
with open('%s_tweets.csv' % screen_name, mode='w', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(["id", "created_at", "text"])
writer.writerows(outtweets)
pass
def main():
get_all_tweets("tartecosmetics")
if __name__ == '__main__':
main()
How I get the replies for a given tweet
此代码将获取用户(名称)最近的 10 条推文以及对该特定推文的回复。
replies=[]
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
for full_tweets in tweepy.Cursor(api.user_timeline,screen_name='tartecosmetics',timeout=999999).items(10):
for tweet in tweepy.Cursor(api.search,q='to:'+'tartecosmetics',result_type='recent',timeout=999999).items(1000):
if hasattr(tweet, 'in_reply_to_status_id_str'):
if (tweet.in_reply_to_status_id_str==full_tweets.id_str):
replies.append(tweet.text)
print("Tweet :",full_tweets.text.translate(non_bmp_map))
for elements in replies:
print("Replies :",elements)
replies.clear()
最佳答案
user_name = "@nameofuser"
replies = tweepy.Cursor(api.search, q='to:{}'.format(user_name),
since_id=tweet_id, tweet_mode='extended').items()
while True:
try:
reply = replies.next()
if not hasattr(reply, 'in_reply_to_status_id_str'):
continue
if reply.in_reply_to_status_id == tweet_id:
logging.info("reply of tweet:{}".format(reply.full_text))
except tweepy.RateLimitError as e:
logging.error("Twitter api rate limit reached".format(e))
time.sleep(60)
continue
except tweepy.TweepError as e:
logging.error("Tweepy error occured:{}".format(e))
break
except StopIteration:
break
except Exception as e:
logger.error("Failed while fetching replies {}".format(e))
break
关于python - 如何使用 tweepy 和 python 获取给定推文的回复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52307443/
我想开发一个 Skype 机器人,它将用户名作为输入,并根据用户输入以相反的字符大小写表示hello username。简而言之,如果用户输入他的名字 james,我的机器人会回复他为 Hello J
我是一名优秀的程序员,十分优秀!