Tweepy Twitter get all tweet replies of particular user - python

I am trying to get all replies of this particular user. So this particular user have reply_to_user_id_str of 151791801. I tried to print out all the replies but I'm not sure how. However, I only manage to print out only 1 of the replies. Can anyone help me how to print out all the replies?
My codes are:
for page in tweepy.Cursor(api.user_timeline, id="253346744").pages(1):
for item in page:
if item.in_reply_to_user_id_str == "151791801":
print item.text
a = api.get_status(item.in_reply_to_status_id_str)
print a.text

First, find the retweet thread of your conversation with your service provider:
# Find the last tweet
for page in tweepy.Cursor(api.user_timeline, id="253346744").pages(1):
for item in page:
if item.in_reply_to_user_id_str == "151791801":
last_tweet = item
The variable last tweet will contain their last retweet to you. From there, you can loop back to your original tweet:
# Loop until the original tweet
while True:
print(last_tweet.text)
prev_tweet = api.get_status(last_tweet.in_reply_to_status_id_str)
last_tweet = prev_tweet
if not last_tweet.in_reply_to_status_id_str:
break
It's not pretty, but it gets the job done.
Good luck!

user_name = "#nameofuser"
replies = tweepy.Cursor(api.search, q='to:{} filter:replies'.format(user_name)) tweet_mode='extended').items()
while True:
try:
reply = replies.next()
if not hasattr(reply, 'in_reply_to_user_id_str'):
continue
if str(reply.in_reply_to_user_id_str) == "151791801":
logging.info("reply of :{}".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

Related

Tweepy auto run

Can some help me understand why when I run this code once it is done it doesn't continue to loop? I want it to run every 12 hrs or so.
def searchBot():
for tweet in tweets:
try:
tweet.retweet()
tweet.favorite()
print ("Done")
time.sleep(5)
except tweepy.TweepError as e:
print (e.reason)
time.sleep(5)
while True:
searchBot()
time.sleep(11)

Python/Tweepy retweet following twitter accounts

I am trying to create a twitter bot using tweepy/python to use as a filter account, to retweet relevant tweets.
I am able to search for tweets that contain a certain word/# etc but was wondering if there is code to enable the account (of which the app is registered with) to retweet all tweets of the accounts it is following.
Please find attached code underneath.
user = api.me()
print(user.name)
def main():
search = ("example1")
numberofTweets = 5
for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
try:
tweet.retweet()
print("Tweet Retweeted")
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
main()
def main2():
search = ("example2")
numberofTweets = 5
for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
try:
tweet.retweet()
print("Tweet Retweeted")
except tweepy.TweepError as e:
print(e.reason)
except StopIteration:
break
main2()
while True:
time.sleep(15)
api.update_status("#" + username + " " + certain_word, in_reply_to_status_id = tweetId)
You can take a look at this tutorial.

Reply to tweets in tweepy

So I have searched all over the place and all the solutions that were presented to me all posted a new tweet and didnt actually reply to the tweets I have collected. My goal is for the script to reply to the 2 tweets I retrieve but for some reason nothing works, I would really appreciate if anyone could help solve this.
while True:
for tweet in tweepy.Cursor(api.user_timeline,
since='2017-12-24',
screen_name='something'
).items(2):
try:
if not tweet.retweeted:
tweet.retweet()
m = "Something"
t = api.update_status(status=m, in_reply_to_status_id=tweet.id)
print("Something, Working...")
sleep(10)
except tweepy.TweepError as e:
print(e.reason)
sleep(5)
break
except StopIteration:
break
I tried "in_reply_to_status_id" as it was stated in the tweepy documentation but it doesn't work either, it simply tweets it out instead of replying.
When replying, prefix the #UserName to the status:
while True:
for tweet in tweepy.Cursor(api.user_timeline,
since='2017-12-24',
screen_name='something'
).items(2):
try:
if not tweet.retweeted:
tweet.retweet()
m = "#UserName Something" # <---
t = api.update_status(status=m, in_reply_to_status_id=tweet.id)
print("Something, Working...")
sleep(10)
except tweepy.TweepError as e:
print(e.reason)
sleep(5)
break
except StopIteration:
break
Notice that I set:
m = "#UserName Something"
with the #UserName prefix.

How to auto follow someone with Twython

I am making a bot that automatically re-tweets and favorites anything containing the keyword 'Australia'
I am successfully able to re-tweet and favorite the tweet automatically, but I have no idea how to follow them automatically (follow everyone I re-tweet automatically)
search_results = twitter.search(q='Australia', count=10)
try:
for tweet in search_results["statuses"]:
try:
twitter.retweet(id = tweet["id_str"])
twitter.create_favorite(id = tweet["id_str"])
twitter.create_friendship(user_id=?????)
except TwythonError as e:
print (e)
except TwythonError as e:
print (e)
After lot of trying found this. Try the below
twitter = Twython(consumer_key,consumer_secret, access_token, access_secret)
search_results = twitter.search(q='Australia', count=10)
try:
for tweet in search_results["statuses"]:
try:
twitter.retweet(id = tweet["id_str"])
twitter.create_favorite(id = tweet["id_str"])
st=tweet["entities"]["user_mentions"]
if st != []:
twitter.create_friendship(screen_name=st[0]["screen_name"])
except TwythonError as e:
print e
except TwythonError as e:
print e
use screen_name to follow the respective handle.

TweepError Failed to parse JSON payload - random error

I am using Tweepy package in Python to collect tweets. I track several users and collect their latest tweets. For some users I get an error like "Failed to parse JSON payload: ", e.g. "Failed to parse JSON payload: Expecting ',' delimiter or '}': line 1 column 694303 (char 694302)". I took a note of the userid and tried to reproduce the error and debug the code. The second time I ran the code for that particular user, I got results (i.e. tweets) with no problem. I adjusted my code so that when I get this error I try once more to extract the tweets. So, I might get this error once, or twice for a user, but in a second or third attempt the code returns the tweets as usual without the error. I get similar behaviour for other userids too.
My question is, why does this error appear randomly? Nothing else has changed. I searched on the internet but couldn't find a similar report. A snippet of my code follows
#initialize a list to hold all the tweepy Tweets
alltweets = []
ntries = 0
#make initial request for most recent tweets (200 is the maximum allowed count)
while True:
try: #if process fails due to connection problems, retry.
if beforeid:
new_tweets = api.user_timeline(user_id = user,count=200, since_id=sinceid, max_id=beforeid)
else:
new_tweets = api.user_timeline(user_id = user,count=200, since_id=sinceid)
break
except tweepy.error.RateLimitError:
print "Rate limit error:", sys.exc_info()[0]
print("Timeout, retry in 5 minutes...\n")
time.sleep(60 * 5)
continue
except tweepy.error.TweepError as er:
print('TweepError: ' + er.message)
if er.message == 'Not authorized.':
new_tweets = []
break
else:
print(str(ntries))
ntries +=1
pass
except:
print "Unexpected error:", sys.exc_info()[0]
new_tweets = []
break

Categories